【问题标题】:Puppeteer: how to generate PDF that only has one page and the page contains all content of webpagePuppeteer:如何生成只有一页并且页面包含网页所有内容的PDF
【发布时间】:2022-01-17 12:52:49
【问题描述】:

我正在尝试使用 Puppeteer 生成 pdf。我想要的是生成的pdf文件应该只有一页。而这个单页包含了网页的所有内容。

以下是我的代码,抄自https://github.com/puppeteer/puppeteer/issues/5590#issuecomment-747638812

但它并没有按预期工作。

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({
    headless: true,
    defaultViewport: {
      width: 1024,
      height: 800,
    },
    args: [
      '--no-sandbox',
      '--disable-gpu',
      '--hide-scrollbars',
      '--start-fullscreen',
    ]
  });
  const page = await browser.newPage();
  await page.goto('https://www.w3schools.com/', {
    waitUntil: 'networkidle0',
  });
  await page.emulateMediaType('screen');

  const totalPage = await page.$('html');
  const boundingBox = await totalPage.boundingBox();
  console.log(boundingBox);

  await page.pdf({
    path: 'w3schools.pdf', 
    printBackground: true,
    width: '1024px',
    height: `${boundingBox.height + 20}px`,
  });

  await browser.close();
})();

【问题讨论】:

    标签: pdf pdf-generation puppeteer


    【解决方案1】:

    根据我的经验,更简洁的方法是使用 page.eval() 获取文档的高度并将其作为选项传递给 page.pdf()

    const puppeteer = require('puppeteer');
    
    const docHeight = () => {
      const body = document.body
      const html = document.documentElement;
      return Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
    }
    
    (async () => {
        const browser = await puppeteer.launch();
        const page = await browser.newPage();
        await page.goto("https://en.wikipedia.org/wiki/JavaScript");
        const height = await page.evaluate(docHeight);
    
        await page.pdf({path: `js.pdf`, height: `${height}px`})
        
    })();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-11
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-15
      • 2023-03-28
      相关资源
      最近更新 更多