我正在尝试在phantomjs示例中创建自定义页脚:https://github.com/ariya/phantomjs/blob/master/examples/printheaderfooter.js
这是我的代码:
var phantom = require('node-phantom');
phantom.create(function (err, ph) {
ph.createPage(function (err, page) {
page.set('paperSize', {
format: 'A4',
orientation: 'portrait',
footer: {
contents: ph.callback(function (pageNum, numPages) {
if (pageNum == 1) {
return "";
}
return "<h1>Header <span style='float:right'>" + pageNum + " / " + numPages + "</span></h1>";
})
}
}, function () {
page.open('http://www.google.com', function () {
})
})
})
});
Run Code Online (Sandbox Code Playgroud)
但不幸的是我收到以下错误:
TypeError: Object #<Object> has no method 'callback';
Run Code Online (Sandbox Code Playgroud)
是不是ph不暴露回调方法的错误?
您的脚本中存在两个问题:
ph不是经典的幻像对象,而是代理对象.node-phantom使用Web套接字来调用phantomjs.当然,使用此实现会丢失一些功能.page.set打印自定义页眉/页脚还需要调用phantom.callback.此方法未记录,因此未公开node-phantom(也不能公开).我们需要找到一种方法在这个包中应用这个方法.
有很多解决方案.这是我可能的解决方案:
在脚本中以字符串序列化函数
var phantom = require('node-phantom');
phantom.create(function (err, ph) {
ph.createPage(function (err, page) {
page.set('paperSize', {
format: 'A4',
orientation: 'portrait',
header: {
height: "1cm",
contents: 'function(pageNum, numPages) { return pageNum + "/" + numPages; }'
},
footer: {
height: "1cm",
contents: 'function(pageNum, numPages) { return pageNum + "/" + numPages; }'
}
}, function () {
page.open('http://www.google.fr', function () {
page.render('google.pdf');
ph.exit();
})
})
})
});
Run Code Online (Sandbox Code Playgroud)
编辑bridge.js并添加phantom.callback + eval.这允许我们重新插入页眉/页脚.contents.
case 'pageSet':
eval('request[4].header.contents = phantom.callback('+request[4].header.contents+')');
eval('request[4].footer.contents = phantom.callback('+request[4].footer.contents+')');
page[request[3]]=request[4];
respond([id,cmdId,'pageSetDone']);
break;
Run Code Online (Sandbox Code Playgroud)
正如你所看到的那样有效!(谷歌法语)

| 归档时间: |
|
| 查看次数: |
3006 次 |
| 最近记录: |