Puppeteer page.pdf() viewport and pagination limits when generating multi-page documents
0 reputation · 18 Dec 2020, 16:24 UTC
0 reputation · 18 Dec 2020, 16:24 UTC
I'm using Puppeteer to generate PDFs from rendered HTML pages via page.pdf(), and I need to understand the documented limits of this API before committing to it for a reporting feature.
My understanding is that page.pdf() captures the page as Chrome's print pipeline sees it, with options like format, margin, printBackground, and scale. What is unclear to me is how much control I actually have over pagination. Content that flows beyond a single page seems to break according to Chrome's print layout rather than anything I configure directly, and CSS like page-break-before appears to be the only lever.
I'm also unsure how viewport size and headless rendering interact with the output: whether the viewport at goto() time affects which content is laid out for the PDF, and whether font rendering differences between headless Chrome and a visible browser can shift line breaks and therefore page breaks.
Specific questions:
page.pdf() always capture the full document height, or can content outside the current viewport be omitted?@page, break properties) the only supported way to control page breaks?page.pdf() to get deterministic output?32775 reputation · 18 Dec 2020, 18:41 UTC
page.pdf() always renders the entire DOM that has finished loading. Elements outside the current viewport are not clipped; they appear in the PDF as long as they are part of the rendered tree and are not hidden by CSS overflow or display:none. If content is loaded lazily or injected after the PDF call, it will be missing unless you wait for it.
The only way to influence where a page ends is through CSS that is evaluated by Chrome’s print pipeline. Supported directives are:
Puppeteer itself provides no API to insert page breaks programmatically.
Yes. The viewport you set with page.setViewport before navigating determines the layout of the page when CSS uses viewport units (vw/vh), media queries, or responsive breakpoints. The print engine ignores the viewport for page size, but the rendered DOM that it prints depends on that layout. Setting a stable viewport that matches the intended print size (e.g., 8.5×11 in at 96 dpi ≈ 816×1128 px) ensures repeatable PDFs.
await page.setViewport({ width: 816, height: 1128, deviceScaleFactor: 1 });
/* Example: force a new page before each section */
section::before {
content: "";
page-break-before: always;
}
await page.pdf({ path: 'report.pdf', format: 'A4', printBackground: true });
If you observe page breaks that do not match your CSS, confirm whether the page uses viewport‑relative units or media queries that could be affected by the viewport you set. Also check for asynchronous content that might not yet be present when page.pdf() runs.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.