2014-11-16 26 views
1

我试图将标题添加到使用node-webshot生成的PDF中,但没有显示出来。将标题添加到Node生成的PDF Webshot

我使用这个代码:

webshot('https://www.google.com', 'google.pdf', options, function (err) { 
    if(err) throw err; 
    console.log('Saved to PDF'); 
}); 

随着选项对象是这样的:

var options = { 
     "paperSize": { 
      "format": "A4", 
      "orientation": "portrait", 
      "border": "0.25cm", 
      "header": { 
       "height": "2cm", 
       "contents": function() { 
        return phantom.callback(function(pageNum, numPages) { 
         return '<h1>' + pageNum + '/' + numPages + '</h1>'; 
        }); 
       } 
      } 
     } 
    }; 

我试着做内容的功能它是如何表现的PhantomJS documentation但它不工作,因为幻像没有定义。我找不到任何如何使用webshot添加页眉/页脚的例子。

PDF生成正确,但标题为空,没有写入任何内容。

我该如何解决这个问题?

+0

我的回答有帮助吗?有什么问题吗?你可以[接受](http://meta.stackexchange.com/a/5235)一个答案,如果它解决了你的问题(只是你知道)。 –

回答

0

由于选项作为对象传递到webshot并且“回调”是直接的,所以没有办法绕过修改webshot。

因此改变从here到线(文件节点webshot/LIB/webshot.phantom.js):

optUtils.phantomPage.forEach(function(key) { 
    if (toOverwrite[key]) page[key] = toOverwrite[key]; 
    if (key === "paperSize" && page[key] && page[key].header && page[key].header.contents) { 
    page[key].header.contents = eval(page[key].header.contents); 
    } 
    if (key === "paperSize" && page[key] && page[key].footer && page[key].footer.contents) { 
    page[key].footer.contents = eval(page[key].footer.contents); 
    } 
}); 

前提是你撰写的标题内容的功能这样的字符串:

"contents": "phantom.callback(function(pageNum, numPages) { return '<h1>' + pageNum + '/' + numPages + '</h1>'; })"; 

它不能作为函数传递,因为沿着选项对象被字符串化的方式删除所有函数。

0

我知道这个问题已经超过一年了,但对于与上面相同的问题的其他人,eval()并不适用于我。我落得这样做是将在同一地点如下代码:

if (key === "paperSize" && page[key] && page[key].header && page[key].header.contents) { 
    var header = { 
     "height": page[key].header.height, 
     "contents": phantom.callback(function() {return options.paperSize.header.contents;}) 
    } 
    page.paperSize.header = header; 
    } 
    if (key === "paperSize" && page[key] && page[key].footer && page[key].footer.contents) { 
    var footer = { 
     "height": page[key].footer.height, 
     "contents": phantom.callback(function() {return options.paperSize.footer.contents;}) 
    } 
    page[key].footer = footer 
    } 
    if (key === "paperSize") { 
    page.paperSize = { 
     "format": options.paperSize.format, 
     "orientation": options.paperSize.orientation, 
     "margin": options.paperSize.margin, 
     "header": header, 
     "footer": footer 
    } 
    } 

这样做的原因是webshot stringifies在选项中的所有数据对象,所以phantom.callback呈现页眉和页脚与phantomjs没有按要求没有正确的字符串。相反,你需要在你的选项对象中添加你将要用在页眉/页脚中的html,然后将它插入到上面代码中的phantom.callback中。这种方法唯一的问题是你不能在回调中使用numPages和pageNum参数。

相关问题