问题描述
我正在尝试在phantomjs示例中创建自定义页脚: https: //github.com/ariya/phantomjs/blob/master/examples/printheaderfooter.js
I'm trying create custom footers such in phantomjs examples: 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 () {
})
})
})
});
但不幸的是,我收到以下错误消息:
But unfortunately I get the following error:
TypeError: Object #<Object> has no method 'callback';
ph不公开回调方法是错误的吗?
Is it bug that ph does not expose callback method?
推荐答案
脚本中存在两个问题:
-
ph
不是经典的幻像对象,而是代理对象.node-phantom
使用Web套接字调用phantomjs.当然,使用此实现会丢失某些功能. 调用 - 函数未序列化
page.set
时ph
is not the classic phantom object, but a proxy object.node-phantom
use web sockets to invoke phantomjs. Of course, some features are lost using this implementation.- functions are not serialized when calling
page.set
打印自定义页眉/页脚还需要调用phantom.callback.此方法没有记录,因此没有被node-phantom
公开(并且不能公开).我们需要找到一种在此程序包中应用此方法的方法.
Printing custom header/footer also requires to call phantom.callback. This method is not documented and so not exposed by node-phantom
(and can't be). We need to find a way to apply this method in this package.
有很多解决方案.这是我可能的解决方法:
There are many solutions. Here is my possible solution :
在脚本中的字符串中序列化您的函数
Serialize your functions in a string in your script
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();
})
})
})
});
编辑bridge.js并添加phantom.callback + eval.这样我们就可以重新插入header/footer .contents.
edit bridge.js and add phantom.callback + eval. This allow us to re-plug the header/footer .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;
如您所见,这行得通! (法语的Google)
As you can see this works ! (Google in French)
这篇关于页脚的内容似乎无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!