gpt4 book ai didi

node.js - 页脚的内容似乎不起作用

转载 作者:搜寻专家 更新时间:2023-10-31 23:33:23 24 4
gpt4 key购买 nike

我正在尝试创建自定义页脚,例如在 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 () {
})
})
})
});

但不幸的是我收到以下错误:

TypeError: Object #<Object> has no method 'callback';

ph没有暴露回调方法是不是bug?

最佳答案

你的脚本有两个问题:

  • ph 不是经典的幻象对象,而是一个代理对象。 node-phantom 使用网络套接字调用 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();
})
})
})
});

编辑 bridge.js 并添加 phantom.callback + eval。这允许我们重新插入页眉/页脚内容。

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;

如您所见,这是可行的! (法语谷歌)

enter image description here

关于node.js - 页脚的内容似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17102287/

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