gpt4 book ai didi

javascript - 如何在nodeJS中使用phantom包设置自定义页眉和页脚内容?

转载 作者:行者123 更新时间:2023-11-28 19:29:57 26 4
gpt4 key购买 nike

实际上,我正在使用nodeJS中的phantom包生成pdf报告。我发现我们可以使用 phantom.callback 方法来设置它。但是我有一个问题,当这个回调返回简单文本时它工作正常,但是当我尝试使用使用闭包和jade引擎生成html的复杂函数时,我在幻像输出中出现错误,说明jade变量未定义,我认为这个问题发生的原因是在子幻影进程上下文中提到了有关工作的回调,因此在该回调中我的代码中定义的所有变量都不起作用。那么,我该如何解决这个问题呢?也许你知道更好的 phantomJS 包装器可以做这些事情?我使用这个包 phantom": "0.7.x"

//there I define all varaibles (jade, fs, etc., so I am sure that they are correct)

function generatePage(_page, reportConfig, phantom, html, report) {
_page.set('viewportSize', reportConfig.viewportSize);
var config = _.extend(reportConfig.paperSize, {
header: {
height: "2cm",
//contents: phantom.callback(headerCallback)
contents: phantom.callback(function (pageNum, numPages) {
var fn = jade.compile(headerTemplate); //Jade in undefined in phantom stdout
var templateData = _.extend({ currentPage: pageNum, numberPages: numPages }, report);
var generatedHtml = fn(templateData);
return "<h1>HEADER</h1><br />" /*+ generatedHtml*/;
})
}
, footer: {
height: "1cm",
contents: phantom.callback(function (pageNum, numPages) {
return "<p>Page " + pageNum + " of " + numPages + "</p>"; //WORKS fine
})
}
}
);
_page.set('paperSize', config);
_page.setContent(html);
return _page;
}

最佳答案

幻像回调不会以这种方式工作,您作为回调发送的函数将被字符串化并在幻像上下文中重新编译,您的依赖项将未知。

这是一个迟到的答案,但我没有在野外找到类似的东西。所以也许会帮助其他人。

您必须在定义 jade 和其他内容之后立即从页面上下文中生成 html,并将结果编译到您将作为回调发送的函数中:

//there I define all varaibles (jade, fs, etc., so I am sure that they are correct)
var fn = jade.compile(headerTemplate); //Jade is undefined in phantom context
var templateData = report;
var generatedHtml = fn(templateData);
//You can use some patterns in your template for pageNum and numPages like #pageNum# and replace them after compilation.
//here you are compiling the result into a function which you will send
//as callback(you have to remove all spaces and all breaklines to avoid compilation errors)
var headerCallbak = 'function(pageNum, numPages) { var x = \''+ generatedHtml .trim().replace(/(\r\n|\n|\r)/gm,"") +'\'; return x.relpace("#pageNumber#", pageNum).replace("#numPages#",numPages);}';

function generatePage(_page, reportConfig, phantom, html, report) {
_page.set('viewportSize', reportConfig.viewportSize);
var config = _.extend(reportConfig.paperSize, {
header: {
height: "2cm",
contents: phantom.callback(headerCallbak)
}
, footer: {
height: "1cm",
contents: phantom.callback(function (pageNum, numPages) {
return "<p>Page " + pageNum + " of " + numPages + "</p>"; //WORKS fine
})
}
}
);
_page.set('paperSize', config);
_page.setContent(html);
return _page;
}

关于javascript - 如何在nodeJS中使用phantom包设置自定义页眉和页脚内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27044459/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com