Javascript 向节点Webshot生成的PDF添加标题
我正在尝试向使用生成的PDF添加标题,但没有显示任何内容 我正在使用以下代码:Javascript 向节点Webshot生成的PDF添加标题,javascript,node.js,pdf,phantomjs,Javascript,Node.js,Pdf,Phantomjs,我正在尝试向使用生成的PDF添加标题,但没有显示任何内容 我正在使用以下代码: webshot('https://www.google.com', 'google.pdf', options, function (err) { if(err) throw err; console.log('Saved to PDF'); }); 使用如下所示的选项对象: var options = { "paperSize": { "format": "
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>';
});
}
}
}
};
"contents": "phantom.callback(function(pageNum, numPages) { return '<h1>' + pageNum + ' / ' + numPages + '</h1>'; })";
var选项={
“纸张大小”:{
“格式”:“A4”,
“方向”:“肖像”,
“边框”:“0.25厘米”,
“标题”:{
“高度”:“2cm”,
“内容”:功能(){
返回phantom.callback(函数(pageNum,numPages){
返回'+pageNum+'/'+numPages+'';
});
}
}
}
};
我尝试过如何在PhantomJS上显示内容函数,但它不起作用,因为PhantomJS没有定义。我找不到任何关于如何使用webshot添加页眉/页脚的示例
PDF生成正确,但标题为空,上面没有任何内容
如何解决这个问题?因为选项是作为对象传递到webshot的,而“回调”是直接传递的,所以没有办法修改webshot 因此,将行从(文件节点webshot/lib/webshot.phantom.js)更改为: 假设您将标题内容函数组成如下字符串:
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>';
});
}
}
}
};
"contents": "phantom.callback(function(pageNum, numPages) { return '<h1>' + pageNum + ' / ' + numPages + '</h1>'; })";
“contents:“phantom.callback(函数(pageNum,numPages){return'+pageNum+'/'+numPages+';})”;
它不能作为函数传递,因为在传递过程中,options对象被字符串化,从而删除所有函数。我知道这个问题已经存在一年多了,但对于其他与上述问题相同的人来说,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参数。我的答案有帮助吗?有什么问题吗?如果它解决了你的问题,你可以给出一个答案(只是让你知道)。