CSS Print Stylesheet for PDF: @media print, Breaks & Fonts
Generating PDF from HTML with CSS sounds straightforward — until backgrounds disappear, page breaks land in wrong places, table headers vanish, and @page margins seem to be ignored. This guide collects every Chromium print CSS technique you need, with copy-paste snippets for each problem.
Puppeteer, Playwright, and FUNBREW PDF's quality engine use Chromium's print pipeline. FUNBREW PDF's fast engine uses wkhtmltopdf instead, so modern CSS support differs. Check each rule against your target engine.
For CSS problems specific to @page layout and page breaks, see HTML to PDF CSS Fixes. If you are embedding Japanese or CJK fonts, see the Japanese Font Guide. For troubleshooting blank pages and broken layouts, see the HTML to PDF Troubleshooting guide.
The Two CSS Contexts: @media print vs @page
Understanding which CSS rule applies where is the first step.
@media print |
@page |
|
|---|---|---|
| Purpose | Scopes styles to print/PDF context | Configures the physical page |
| What it controls | Fonts, colors, visibility, layout | Size, orientation, margins |
| Supports CSS vars | Yes | Engine/version dependent |
| Nested in the other | Can contain @page |
Standalone or inside @media print |
| Example | @media print { .nav { display: none } } |
@page { size: A4; margin: 20mm } |
Always structure your print stylesheet in this order:
/* 1. Scope everything in @media print */
@media print {
/* 2. Configure the physical page inside @page */
@page {
size: A4 portrait;
margin: 20mm 15mm 25mm 15mm; /* top right bottom left */
}
/* 3. Override screen styles for print */
body {
font-size: 11pt;
color: #000;
}
/* 4. Hide elements not needed in print */
.no-print,
nav,
.sidebar {
display: none !important;
}
}
@page: Size, Orientation, and Margins
Named page sizes
@page { size: A4 portrait; } /* 210mm × 297mm */
@page { size: A4 landscape; } /* 297mm × 210mm */
@page { size: Letter portrait; } /* 8.5in × 11in */
@page { size: Legal; } /* 8.5in × 14in */
@page { size: A3 landscape; } /* 420mm × 297mm */
Custom dimensions
@page {
size: 210mm 297mm; /* explicit width height */
margin: 20mm;
}
Per-page margin control
@page { margin: 20mm 15mm; } /* all pages */
@page :first { margin-top: 40mm; } /* cover page */
@page :left { margin-left: 25mm; } /* even pages (binding) */
@page :right { margin-right: 25mm; } /* odd pages (binding) */
Note: Handling of CSS custom properties (
var()) inside@pagedepends on the engine and version. Use literal values if you need consistent output across target environments.
Page Breaks: break-before, break-after, break-inside
Use the modern break-* properties, adding legacy page-break-* declarations when older engines must also be supported. Chromium treats the legacy properties as aliases of their modern counterparts.
Force a page break before a section
.chapter,
.report-section,
h1 {
break-before: page;
page-break-before: always; /* legacy fallback */
}
Prevent a break inside a block
.card,
.figure,
.keep-together {
break-inside: avoid;
page-break-inside: avoid; /* legacy fallback */
}
Force a break after a cover page
.cover {
break-after: page;
page-break-after: always;
height: 100vh; /* fills the first page */
}
Flex and grid layout gotcha
If break-inside: avoid does not behave as expected inside flex or grid layout, try wrapping the target in a block <div> and inspect the output:
<!-- Works -->
<div class="grid-wrapper">
<div class="card-wrapper"> <!-- break-inside: avoid here -->
<div class="card">...</div>
</div>
</div>
.card-wrapper {
break-inside: avoid;
page-break-inside: avoid;
}
Background Colors and Images
Global fix for all elements
@media print {
* {
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
}
Per-element fix
.colored-header,
.status-badge,
.chart-background {
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
Background images
.banner {
background-image: url('/img/logo.png');
background-size: cover;
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
FUNBREW PDF's generation API has no printBackground option. Include the CSS above in your HTML. exact requests the specified appearance; it does not guarantee that user settings cannot override it.
Tables: Repeating Headers, Avoiding Orphan Rows
Repeat table header on every page
thead {
display: table-header-group;
}
tfoot {
display: table-footer-group;
}
tbody {
display: table-row-group;
}
<table>
<thead>
<tr>
<th>Name</th><th>Amount</th><th>Date</th>
</tr>
</thead>
<tbody>
<!-- rows repeat across pages -->
</tbody>
</table>
Prevent row orphans (rows split across pages)
tr {
break-inside: avoid;
page-break-inside: avoid;
}
Fixed table layout for consistent column widths
table {
table-layout: fixed;
width: 100%;
border-collapse: collapse;
}
th, td {
word-wrap: break-word;
overflow-wrap: break-word;
}
Fonts: Loading and Embedding
System font stack (no external requests)
body {
font-family: -apple-system, 'Segoe UI', Arial, sans-serif;
}
Web font with @font-face (self-hosted, no CDN)
@font-face {
font-family: 'Inter';
src: url('/fonts/Inter-Regular.woff2') format('woff2');
font-weight: 400;
font-style: normal;
font-display: block; /* short block period, then show the fallback */
}
body {
font-family: 'Inter', sans-serif;
}
Base64-embedded font (no HTTP requests at render time)
@font-face {
font-family: 'MyFont';
src: url('data:font/woff2;base64,AAABAA...') format('woff2');
}
Embedding fonts as Base64 removes the font CDN dependency at render time, at the cost of a larger HTML payload. See the Japanese Font Guide for embedding CJK fonts.
Google Fonts via CDN (requires network at render time)
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=block" rel="stylesheet">
FUNBREW PDF's generation API has no waitForNetworkIdle option. To avoid depending on external font-loading timing, consider self-hosting or data URIs and inspect the glyphs in the target engine's output.
Page Numbers and Running Headers/Footers
CSS margin boxes (Chromium 131+)
@page {
margin: 25mm 15mm 20mm;
@top-center {
content: "Monthly report";
font-size: 9pt;
color: #888;
}
@bottom-center {
content: "Page " counter(page) " of " counter(pages);
font-size: 9pt;
color: #888;
}
}
Chrome 131 added @page margin boxes and the page / pages counters for printing and PDF export. FUNBREW PDF's generation API has no displayHeaderFooter, headerTemplate, or footerTemplate options, so include this CSS in the HTML. Select the quality engine and verify page numbers and margins in your environment; the fast wkhtmltopdf engine cannot be assumed to support this modern CSS.
Hiding Elements in Print
Common elements to hide
@media print {
/* Navigation and chrome */
nav,
header.site-header,
footer.site-footer,
.sidebar,
.breadcrumb,
.pagination,
/* Interactive elements */
button,
input,
select,
textarea,
form,
/* Utility classes */
.no-print,
.screen-only {
display: none !important;
}
}
Show print-only elements
.print-only {
display: none;
}
@media print {
.print-only {
display: block;
}
}
Example: show full URL after links
@media print {
a[href]::after {
content: " (" attr(href) ")";
font-size: 9pt;
color: #555;
}
/* Exclude internal anchors */
a[href^="#"]::after {
content: "";
}
}
Layout Patterns for PDF
Full-bleed cover page
@page :first {
margin: 0;
}
.cover-page {
width: 210mm;
height: 297mm;
padding: 40mm 30mm;
background: #1e3a5f;
color: #fff;
display: flex;
flex-direction: column;
justify-content: flex-end;
break-after: page;
}
Two-column layout with print-safe CSS
.two-column {
column-count: 2;
column-gap: 10mm;
column-rule: 1px solid #e2e8f0;
}
/* Prevent headings from splitting across columns */
h2, h3 {
break-after: avoid;
column-span: none;
}
Invoice / data table layout
.invoice-table {
width: 100%;
border-collapse: collapse;
font-size: 10pt;
}
.invoice-table th {
background: #1e3a5f;
color: #fff;
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
padding: 3mm 4mm;
text-align: left;
}
.invoice-table td {
padding: 2.5mm 4mm;
border-bottom: 0.5px solid #e2e8f0;
}
.invoice-table tr:nth-child(even) td {
background: #f8fafc;
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
Using the CSS with FUNBREW PDF API
Combine all the techniques above and send the final HTML to the API. This example requires a plan that includes the quality (Chromium) engine:
import fs from 'fs';
const html = fs.readFileSync('report.html', 'utf-8');
const authorization = `Bearer ${process.env.FUNBREW_PDF_API_KEY}`;
const response = await fetch('https://pdf.funbrew.cloud/api/pdf/generate-from-html', {
method: 'POST',
headers: {
'Authorization': authorization,
'Content-Type': 'application/json',
},
body: JSON.stringify({
html,
options: {
'page-size': 'A4',
'margin-top': 25,
'margin-right': 15,
'margin-bottom': 20,
'margin-left': 15,
engine: 'quality',
},
}),
});
if (!response.ok) throw new Error(`Generation failed: ${response.status}`);
const { data } = await response.json();
const pdfResponse = await fetch(data.download_url, {
headers: { 'Authorization': authorization },
});
if (!pdfResponse.ok) throw new Error(`Download failed: ${pdfResponse.status}`);
const pdf = Buffer.from(await pdfResponse.arrayBuffer());
fs.writeFileSync('output.pdf', pdf);
import requests, os
with open('report.html', 'r') as f:
html = f.read()
headers = {'Authorization': f'Bearer {os.environ["FUNBREW_PDF_API_KEY"]}'}
response = requests.post(
'https://pdf.funbrew.cloud/api/pdf/generate-from-html',
headers=headers,
json={
'html': html,
'options': {
'page-size': 'A4',
'margin-top': 25,
'margin-right': 15,
'margin-bottom': 20,
'margin-left': 15,
'engine': 'quality',
},
},
timeout=30,
)
response.raise_for_status()
download_url = response.json()['data']['download_url']
pdf_response = requests.get(download_url, headers=headers, timeout=30)
pdf_response.raise_for_status()
with open('output.pdf', 'wb') as f:
f.write(pdf_response.content)
Test your CSS in the FUNBREW PDF Playground before integrating into your codebase.
Quick-Reference: 25 CSS Print Snippets
| Problem | Fix |
|---|---|
| Background color missing | print-color-adjust: exact |
| Background image missing | print-color-adjust: exact on element |
| Page break before section | break-before: page; page-break-before: always |
| Prevent break inside block | break-inside: avoid; page-break-inside: avoid |
| Page break after cover | break-after: page; page-break-after: always |
| Table header every page | thead { display: table-header-group } |
| Table footer every page | tfoot { display: table-footer-group } |
| Row not split | tr { break-inside: avoid } |
| Fixed column widths | table { table-layout: fixed } |
| Custom page size | @page { size: A4 landscape } |
| Custom margins | @page { margin: 20mm 15mm } |
| First-page margin | @page :first { margin-top: 40mm } |
| Hide nav in PDF | @media print { nav { display: none } } |
| Include a font in HTML | @font-face with local WOFF2 |
| Font via CDN | Consider self-hosting or data URIs and inspect the output |
| Page number | counter(page) in @bottom-center in Chromium 131+ |
| Total pages | counter(pages) in Chromium 131+ |
| Full-bleed cover | @page :first { margin: 0 } |
| Two-column layout | column-count: 2; column-gap: 10mm |
| Links print URL | a[href]::after { content: attr(href) } |
| Flex break fix | Try wrapping the target in a block div |
| Request backgrounds globally | print-color-adjust: exact in CSS (user settings win) |
| Wait for fonts | No API wait option; reduce external dependencies and inspect output |
| Header | @top-center inside @page in Chromium 131+ |
| Footer | @bottom-center inside @page in Chromium 131+ |
Related Guides
- HTML to PDF CSS Fixes — Deep dive into specific CSS rendering bugs in Chromium PDF
- HTML to PDF Troubleshooting — Blank pages, broken layouts, and missing elements
- Japanese Font Guide — Embed Noto Sans JP and other CJK fonts
- PDF Report Generation Guide — Reports with Chart.js, headers, and cron scheduling
- HTML to PDF Complete Guide — End-to-end overview for developers new to the API
- API Documentation — Full FUNBREW PDF API reference with all options
- Playground — Test CSS and HTML in the browser before integrating