【问题标题】:pass HTML to phantom and render it to PDF将 HTML 传递给幻像并将其呈现为 PDF
【发布时间】:2015-08-17 08:14:36
【问题描述】:

通常情况下,您可以执行以下操作:

phantom = require('phantom')


phantom.create(function(ph){
  ph.createPage(function(page) {
    page.open("http://www.google.com", function(status) {
      page.render('google.pdf', function(){

        console.log('Page Rendered');
        ph.exit();

      });
    });
  });
});

但是,我没有加载网页,而是已经有一些 html 我想要传递并呈现为 PDF。

我如何才能将它传递给HTML 并将其转换为PDF 并且PhantomJs 是正确的方法,或者ffmpeg 是一种更好的方法,如果是这样,我该如何使用ffmpeg ?

【问题讨论】:

    标签: node.js pdf phantomjs


    【解决方案1】:

    您可以设置content property of the page

    phantom = require('phantom')
    phantom.create(function(ph){
        ph.createPage(function(page) {
            page.content = "Some html"//Set your html here
            page.render('google.pdf', function(){
                console.log('Page Rendered');
                ph.exit();
            });
        });
    });
    

    【讨论】:

    • 不适用于当前版本。 (只有一个空白页)
    【解决方案2】:

    Phantom 不再受支持。 我建议使用 Chrome DevTools 团队的 puppeteer。代码更加简洁易读:

    const puppeteer = require('puppeteer');
    (async () => {
      const browser = await puppeteer.launch();
      const page = await browser.newPage();
      await page.setContent(`<p>Hello world!</p>);
      // alternatively it can be fetched from web
      // await page.goto('https://news.ycombinator.com', {waitUntil: 'networkidle2'});
      await page.pdf({path: 'hn.pdf', format: 'A4'});
      await browser.close();
    })();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-02
      • 2023-03-21
      • 2019-10-19
      • 1970-01-01
      • 2020-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多