我正在尝试生成一个pdf
网页文件,并希望保存到本地磁盘以便稍后发送电子邮件。
我曾尝试过这种方法,但这里的问题是,它不适用于这样的页面。我能够生成pdf
但它与网页内容不匹配。
很明显,它pdf
是在之前生成的,document ready
或者可能是其他东西。我无法弄清楚确切的问题。我只是在寻找一种可以将网页输出保存为pdf
.
我希望pdf
网页的生成更适合node
呢php
?如果有任何解决方案php
可用,那么这将是一个很大的帮助,甚至节点实现也很好。
很清楚 pdf 是在文档准备好之前生成的
非常正确,因此需要等到脚本加载并执行之后。
从那时起该模块进行了升级,现在支持使脚本更具可读性的 async/await 函数。
如果我可以建议使用 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 毫秒。比 toawait timeout(3000)
或任何其他任意秒数要好得多。
我用html-pdf package
.
代码很简单,你可以这样使用:
pdf.create(html, options).toFile('./YourPDFName.pdf', function(err, res) {
if (err) {
console.log(err);
}
});
在此处的包页面中查看有关它的更多信息。
希望对您有所帮助。