CSS Media and PDF Rendering in Headless Chrome
In this article
CSS media types directly control how styles are applied when generating PDFs with Headless Chrome via Puppeteer, with the print and screen media types being the most influential. By default, Headless Chrome uses print media rules during PDF export, meaning only CSS intended for printing or compatible with print contexts affects the final document layout.
Background: CSS Media Types and Print Styling
CSS defines several media types—such as all, screen, print, and speech—to apply different styles based on the output device. When a web page is converted to PDF using Headless Chrome, the rendering engine treats the output as a printed document, defaulting to the print media type unless explicitly overridden. This behavior follows standard web rendering practices where print stylesheets (declared with @media print) take precedence during physical or digital printing.
For example:
@media print {
.navbar, .sidebar { display: none; }
body { font-size: 12pt; }
}
@media screen {
body { font-size: 16px; }
.print-only { display: none; }
}
In this case, during PDF generation, the print rules hide navigation elements and increase readability with larger, print-optimized text. The screen styles are ignored unless forced otherwise.
How Headless Chrome Renders PDFs
Headless Chrome, controlled through Puppeteer, renders pages in a browser environment without a visible UI. When the page.pdf() method is called, Chrome internally initiates a print simulation. This process triggers the same rendering path used when a user selects "Print to PDF" from the browser menu.
The rendering sequence includes:
- Loading the page and executing JavaScript
- Applying CSS rules that match the current media context (default:
print) - Generating a paginated layout based on paper size, margins, and CSS page breaks
- Converting the rendered content into a PDF document
Because this mimics a print operation, any element hidden via @media print will not appear in the output, and styles optimized for screens (like background images or hover effects) may be suppressed unless explicitly allowed.
Controlling Media Type in Puppeteer
Puppeteer allows developers to override the default media type used during PDF generation. This is done using the emulateMedia method before calling page.pdf().
Example:
await page.emulateMedia({ media: 'screen' });
await page.pdf({ path: 'output.pdf', format: 'A4' });
Setting media: 'screen' forces Chrome to apply screen-specific CSS during PDF rendering. This is useful when:
- Background colors and images need to appear (often disabled in print by default)
- Interactive components (like buttons or menus) should remain visible
- The design relies on screen-only layout techniques (e.g., flexbox or grid behaviors that differ in print)
Conversely, using media: 'print' ensures compatibility with traditional print styling, which often removes decorative elements and adjusts typography for readability on paper.
Common Rendering Issues and Fixes
Several layout problems arise from media type mismatches during PDF generation:
- Missing background colors/images: By default, Chrome disables background graphics in print mode. Fix: Use
-webkit-print-color-adjust: exact;in CSS or setprintBackground: trueinpage.pdf(). - Incorrect layout or broken columns: Print media may force page breaks or alter box models. Fix: Use
page-break-inside: avoid;orbreak-inside: avoid;on critical elements. - Fonts not loading: Some web fonts fail to render if not fully loaded before PDF generation. Fix: Use
await page.waitForFunction()to confirm font availability. - Content cut off at page edges: Default margins in
page.pdf()may interfere. Fix: Adjust margin settings or use CSS@pagerules.
A frequent misconception is that all CSS will render identically in PDFs as in the browser. However, print contexts often disable certain properties (like shadows or transforms) or adjust them for clarity, leading to visual discrepancies.
CSS Pagination and Page Control
When generating multi-page PDFs, CSS provides tools to control page breaks and layout flow. These are especially relevant in print media:
page-break-beforeandpage-break-after: Force a page break before or after an elementpage-break-inside: avoid: Prevents a break inside a block (e.g., within a table row)break-inside: avoid: Modern alternative topage-break-inside@page { margin: 1cm; }: Sets global margins for all pages in the PDF
Example:
@page {
margin: 1cm;
}
.chapter {
page-break-before: always;
}
table.row {
break-inside: avoid;
}
These rules help ensure clean, professional-looking documents with logical section breaks and consistent spacing.
Alternatives to Puppeteer for PDF Generation
While Puppeteer with Headless Chrome is widely used, other tools exist:
- Playwright: Supports multiple browsers (Chromium, Firefox, WebKit) and offers similar PDF export capabilities with media type control.
- WeasyPrint: A Python-based tool that directly converts HTML and CSS to PDF using
printmedia by default. Good for server-side batch processing. - Prince: A commercial tool with excellent CSS paged media support, ideal for complex publications.
- jsPDF + HTML2Canvas: Client-side option that rasterizes HTML to images, then embeds in PDF. Less accurate for text and layout.
Each has trade-offs in fidelity, performance, and CSS support. Puppeteer remains popular due to its active development, Chrome’s rendering accuracy, and integration with modern web features.
Frequently Asked Questions
Why are my background colors missing in the PDF?
By default, Chrome suppresses background graphics in print mode to save ink. To include them, set printBackground: true in the page.pdf() options and use -webkit-print-color-adjust: exact; in your CSS to ensure colors render as intended.
Can I use screen-only CSS when generating a PDF?
Yes. Use await page.emulateMedia({ media: 'screen' }) before generating the PDF. This tells Chrome to apply screen-specific styles instead of print styles, preserving layout, colors, and background images.
How do I ensure fonts render correctly in the PDF?
Fonts must be fully loaded before PDF generation. Use await page.waitForFunction(() => getComputedStyle(element).fontFamily === 'DesiredFont') or ensure web fonts are preloaded. Local fonts may not be available in headless environments.
Do CSS animations appear in the generated PDF?
No. PDFs are static documents. Only the final rendered state of the page is captured. Animations, transitions, and hover effects are not preserved unless they alter the layout or style at the time of export.
Why does my layout look different in the PDF than in the browser?
Differences arise because PDF rendering uses a print context by default, which may disable backgrounds, adjust font sizes, or apply different box models. Emulating screen media or refining print-specific CSS can help align the output with screen expectations.
Can I control page breaks in the PDF?
Yes. Use CSS properties like page-break-before, page-break-after, and break-inside: avoid to manage where content splits across pages. The @page rule also allows margin control for consistent spacing.