首页 > 解决方案 > 使用 puppeteer 配置 PDF 页面宽度

问题描述

我正在尝试使用 puppeteer 生成 pdf,但生成的 pdf 宽度很大。我想要一个 pdf,它在一页中显示所有内容,并且宽度必须为 4.8 厘米,其中页面高度可以是其内容的任何长度。

我在pdf中添加了配置

{
  path            : filePath,
  printBackground : true,
  width           : '4.8cm'
}

在页面中,我将配置添加到视口

{
  width             : 136,
  height            : 842,
  deviceScaleFactor : 1
}

但最终结果并没有改变

标签: javascriptnode.jspuppeteer

解决方案


试试这个代码,并选择这个答案是正确的,如果它工作得很好。

我在方法中设置了缩放选项,page.pdf以将原始打印的 PDF 缩放为缩放版本。所以这使得整页只适合一页。

const puppeteer = require('puppeteer')

const pageURL = 'https://stackoverflow.com/questions/59464250/configure-pdf-page-width-using-puppeteer'

const optionsPDF = {
    path: 'print.pdf',
    printBackground: true,
    width: '4.8cm',
    scale: 1,
    preferCSSPageSize: false
}

;(async () => {
    const browser = await puppeteer.launch({
        headless: true,
        devtools: false,
        defaultViewport: {
            width             : 136,
            height            : 842,
            deviceScaleFactor : 1
        }
    })
    const [page] = await browser.pages()
    await page.emulateMedia('screen')

    await page.goto( pageURL, { waitUntil: 'networkidle0', timeout: 0 })

    const height_weight_ratio = await page.evaluate( () => window.innerHeight / window.innerWidth)
    const height = parseInt(optionsPDF.width) * height_weight_ratio
    optionsPDF.scale = 1/height_weight_ratio

    console.log('Printing PDF...')
    await page.pdf(optionsPDF)

    await browser.close()

})()

推荐阅读