实际上,我正在使用nodeJS中的phantom包生成pdf报告。我发现我们可以使用phantom.callback方法进行设置。但我有一个问题,当这个回调返回简单的文本它工作正常,但当我尝试使用复杂的功能,使用闭包和玉引擎生成HTML我幻影输出中的错误,没有定义玉变量,我认为这个问题是因为在儿童幻像过程的背景下提到了关于工作的回调,因此我回调的代码中定义的所有变量都不起作用。那么,我该如何解决这个问题呢?也许你知道更好的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;
}
答案 0 :(得分:3)
幻像回调不会以这种方式工作,您作为回调函数发送的函数将被编译并在您的依赖项未知的幻像上下文中重新编译。
是一个迟到的答案,但我没有在野外找到这样的东西。所以也许会帮助别人。
您必须在定义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;
}