Why does page.setViewport not accurately set the width and height of the page?

876 views Asked by At

I'm trying to generate a pdf from a webpage. Now as you can see in the image I added, I would like to generate a pdf from the element that is surrounded by a red border.

I thought I could make this work by setting the elements' width and height to 595px and 842px on the frontend and the viewport to await page.setViewport({ width: 595, height: 842, deviceScaleFactor: 1 });.

Why does the generated pdf contain all that unnecessary whitespace? And how can I generate a pdf that fits the entire element?

Just for clarification, I cannot use page.setContent as a lot of the data will be dynamic and I also have to preserve the CSS.

My full code:

async function generatePDF() {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.setViewport({ width: 595, height: 842, deviceScaleFactor: 1 });
    await page.goto("http://localhost:8080", { waitUntil: 'networkidle2' });

    const options = {
        path: "invoice.pdf",
        pageRanges: '1',
        format: "a4",
        printBackground: true,
    }
    await page.pdf(options);
    await browser.close();
}

example pdf

1

There are 1 answers

1
hardkoded On

pdf doesn't rely on the viewport. It doesn't work like the screenshot function, it works more like a print action, which depends on the paper size.

You could try passing the height and width to the pdf function:

const options = {
    path: "invoice.pdf",
    pageRanges: '1',
    width: "595px",
    height: "842px",
    printBackground: true,
}