简体   繁体   中英

Configure PDF page width using puppeteer

I am trying to generate a pdf using puppeteer but the pdf generated is of large width. I want to have pdf which shows all content in one page and must be of width 4.8cm where page height can be of any length its content has.

I added configuration to pdf

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

And To page I added configuration to viewport

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

But the end result is not changing

Try this code, and select this answer as correct, if it works perfectly.

I set the scale options inside the page.pdf method to scale the original printed PDF to the scaled version. So this make the full page fit in one page only.

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()

})()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM