生成网页的 PDF

Generating PDF of a Web Page

我正在尝试生成网页的 pdf 文件,并希望保存到本地磁盘以便稍后通过电子邮件发送。

我试过了this approach but the problem here is, its not working for pages like this。我能够生成 pdf 但它与网页内容不匹配。

很明显 pdf 是在 document ready 之前生成的,或者可能是其他东西。我无法弄清楚确切的问题。我只是在寻找一种可以将网页输出保存为 pdf.

的方法

我希望生成 pdf 网页更适合 node 然后 php?如果 php 中的任何解决方案可用,那将是一个很大的帮助,甚至节点实现也很好。

我使用 html-pdf package 做了类似的事情。

代码很简单,你可以这样使用:

pdf.create(html, options).toFile('./YourPDFName.pdf', function(err, res) {
        if (err) {
          console.log(err);
        }
});

在包页面中查看更多信息 here

希望对你有帮助。

Its very clear that pdf is generated before document ready

非常正确,因此需要等到脚本加载并执行之后。


您链接到使用 phantom 节点模块的答案。

此后模块进行了升级,现在支持 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 毫秒。比 await timeout(3000) 或任何其他任意秒数要好得多。