我正在尝试生成网页的 pdf 文件,并希望保存到本地磁盘以便稍后通过电子邮件发送。
我尝试过this方法,但问题是,它不适用于像this这样的页面。我能够生成 pdf,但它与网页内容不匹配。
很明显,pdf 是在
document.ready
之前生成的,或者可能是其他东西。我无法弄清楚确切的问题。我只是在寻找一种可以将网页输出保存为 pdf 的方法。
我希望在 Node 中生成网页的 pdf 比在 PHP 中更合适?如果 PHP 中有任何解决方案可用,那么这将是一个很大的帮助,甚至节点实现也可以。
很明显,pdf是在文档准备好之前生成的
非常正确,所以需要等到脚本加载并执行之后。
此后该模块进行了升级,现在支持异步/等待功能,使脚本更具可读性。
如果我可以建议使用 async/await 版本的解决方案(版本 4.x,需要节点 8+)。
const phantom = require('phantom');
const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));
(async function() {
const instance = await phantom.create();
const page = await instance.createPage();
await page.property('viewportSize', { width: 1920, height: 1024 });
const status = await page.open('http://www.chartjs.org/samples/latest/charts/pie.html');
// If a page has no set background color, it will have gray bg in PhantomJS
// so we'll set white background ourselves
await page.evaluate(function(){
document.querySelector('body').style.background = '#fff';
});
// Let's benchmark
console.time('wait');
// Wait until the script creates the canvas with the charts
while (0 == await page.evaluate(function(){ return document.querySelectorAll("canvas").length }) ) {
await timeout(250);
}
// Make sure animation of the chart has played
await timeout(500);
console.timeEnd('wait');
await page.render('screen.pdf');
await instance.exit();
})();
在我的开发机器上,等待图表准备好需要 600 毫秒。比
await timeout(3000)
或任何其他任意秒数要好得多。
我使用
html-pdf package
做了类似的事情。
代码很简单,你可以这样使用:
pdf.create(html, options).toFile('./YourPDFName.pdf', function(err, res) {
if (err) {
console.log(err);
}
});
在包装页面此处查看更多相关信息。
希望对您有帮助。
将 HTML 保存为 PDF 时,如果页面在一段时间内编写脚本,我们只需添加适当的延迟,因此这里的结果为 1/2 秒(500 毫秒)和 1 秒(1000 毫秒),您可以简单地增加更多延迟如果页面更复杂或者您的通信/PC 速度较慢。
使用Chrome或Edge调用浏览器有更多的时间裕度。
"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" --headless --print-to-pdf=C:/data/output2.pdf --no-pdf-header-footer --virtual-time-budget=1000 "https://www.chartjs.org/docs/latest/samples/other-charts/pie.html" && timeout 3 && C:/data/output2.pdf