我正在尝试添加一个标题到一个用node-webshot生成的PDF,但什么也没有显示。
我使用的是以下代码:
webshot('https://www.google.com', 'google.pdf', options, function (err) {
if(err) throw err;
console.log('Saved to PDF');
});使用如下的options对象:
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上显示的方式来做contents函数,但它不能工作,因为没有定义幻影。我找不到任何使用webshot添加页眉/页脚的示例。
PDF已正确生成,但标题为空,上面没有任何内容。
我该如何解决这个问题呢?
发布于 2016-02-18 20:41:34
我知道这个问题已经提了一年多了,但是对于其他和上面有相同问题的人来说,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将options对象中的所有数据串行化,因此使用phantomjs呈现页眉和页脚所需的phantom.callback不能正确串行化。相反,您只需要在options对象中添加要在页眉/页脚中使用的html,然后将其插入到上面代码中的phantom.callback中。这种方法的唯一问题是不能在回调中使用numPages和pageNum参数。
发布于 2014-11-17 04:58:36
因为选项是作为对象传递到webshot中的,而"callback“是直接的,所以没有办法修改webshot。
因此,将代码行从here (file node-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>'; })";它不能作为函数传递,因为在传递过程中,options对象会被字符串化,这会删除所有函数。
https://stackoverflow.com/questions/26961624
复制相似问题