Reputation: 291
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
Upvotes: 5
Views: 17619
Reputation: 2499
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()
})()
Upvotes: 4