Most HTML-to-PDF problems are print-CSS problems. A table row cut in half, a heading stranded at the bottom of a page, a missing background or a fallback font all come from how a Chromium-based renderer paginates your document. You fix them with print CSS, not with retries.
This guide covers the print CSS that matters for generated documents like invoices, statements and reports: page size, page breaks, tables and pagination across many pages, web fonts and how they are embedded, and the layout patterns that break in print. Every claim about behaviour comes from a fixture we printed with local headless Chrome 158 (page.pdf() through playwright-core, with preferCSSPageSize: true and printBackground: true unless noted). We then checked each PDF automatically with pdfjs-dist and pdf-lib. The HTML and PDF for each fixture are in /samples/fixtures/css-guide/, and the full result list is at the end.
Page size and margins with @page
Set the paper size and margins in the document. That keeps the template and its layout in one place:
@page {
size: A4; /* or Letter, A5 landscape, 100mm 150mm */
margin: 18mm 16mm 20mm; /* top, left/right, bottom */
}
@page :first {
margin-top: 40mm; /* room for a letterhead on page 1 only */
}What the fixtures showed:
size: A5 landscapeproduced a 595 x 420 pt page, and a customsize: 100mm 150mmproduced 99.8 x 149.9 mm.- An
@pagemargin of 25 mm put the text 24.9 mm from the left edge. WithpreferCSSPageSizeon, it also beat a 5 mm margin passed in the print options. @page :firstworked. Page 1 text began 64.3 mm from the top, and page 2 text began 24.3 mm from the top.- Named pages work, so you can mix orientations in one PDF. An element with
page: wide, matched by@page wide { size: A4 landscape; }, printed as a landscape page between two portrait pages.
The SublimePDF API takes options.format ("A4" by default, "Letter" or "Legal"), options.landscape and options.margin. CSS @page size takes precedence when present, so pick one source of truth per template. Our local test of the opposite mode shows why: with preferCSSPageSize: false and format: "Letter", Chrome used Letter paper but still applied the landscape keyword from the CSS. That gave a 792 x 612 pt page that neither setting asked for on its own.
Controlling page breaks
The CSS Fragmentation spec defines break-before, break-after and break-inside. The older page-break-* properties are aliases for them. Both forms worked in our fixtures:
.chapter { break-before: page; } /* always start on a new page */
.cover { break-after: page; }
.totals,
.signature,
.card { break-inside: avoid; } /* move the whole block if it does not fit */
h2, h3 { break-after: avoid; } /* keep headings with the next paragraph */
p { orphans: 3; widows: 3; }
/* legacy aliases, also honoured */
.legacy-next { page-break-before: always; }
.legacy-keep { page-break-inside: avoid; }Results:
| Rule | Without it | With it |
|---|---|---|
break-inside: avoid on a 100 mm card near the page end | Card split across pages 1 and 2 | Whole card moved to page 2 |
break-after: avoid on an h2 at the page end | Heading on page 1, paragraph on page 2 | Both on page 2 |
widows: 4 | 1 line carried to page 2 | 4 lines on page 2 |
orphans: 4 | Lone lines left behind | No lines left on page 1; paragraph moved |
orphans and widows are a Chromium strength. MDN marks widows as limited availability because Firefox does not support it, so test in the engine you deploy on.
Two limits matter. First, break-inside: avoid is a preference. A block taller than one page still splits, as our 11c fixture shows. Second, break-before: right (and left, recto, verso) produced an ordinary page break in Chrome. No blank page was added to land a chapter on a right-hand page. If you need that for print-ready books, insert the blank page yourself.
Tables that span pages
Long tables cause the most layout bugs in invoices and statements. Chrome handles them well once the CSS stays out of its way:
thead { display: table-header-group; } /* the default; repeats on every page */
tfoot { display: table-footer-group; } /* repeats too; use it for "continued" notes, not totals */
tr { break-inside: avoid; } /* keep each row whole */- A 90-row table over four pages repeated its
theadon all four pages. It still repeated when the table sat inside a flex container. - A
tfootalso repeated on every page. That is a problem if you put the grand total in it. Put totals in a block after the table instead, as the invoice template does. - A CSS reset that sets
thead { display: table-row-group; }turns repetition off. The header printed on page 1 only. - Tall rows split by default (rows 8, 23 and 38 broke across pages in the control). With
tr { break-inside: avoid; }, no row split across six pages.
You can see this in practice in the long sample invoice. It has 60 line items over four pages, with a repeated header, rendered from the same template as the one-page invoice:
Invoice sample files
Rendered from this template and data with headless Chromium for documentation.
Multi-page templates: a pagination checklist
Invoices, statements and reports usually fit on one page in testing and run to several in production. The rules above combine into a short checklist. The sample invoice template applies every item, and the same template prints one page from data.json and four pages from the 60-line data-long.json:
| Concern | CSS in the template | Why |
|---|---|---|
| Page size and margins | @page { size: A4; margin: 18mm 16mm 20mm; } | One source of truth, kept with the layout |
| Page numbers | @page { @bottom-right { content: "Page " counter(page) " of " counter(pages); } } | The Paged Media spec creates the page counter automatically, and pages holds the total |
| Column headings on every page | thead { display: table-header-group; } | Repeats the header row after each break |
| Rows never split | tr { break-inside: avoid; } | A line item stays on one page |
| Totals and notes stay whole | .totals, .notes { break-inside: avoid; } | The total is never separated from its label |
| Headings stay with their text | h2, h3 { break-after: avoid; } | No heading alone at the foot of a page |
| Paragraphs keep enough lines | p { orphans: 3; widows: 3; } | The spec's initial value for both is 2 |
| New sections start a page | .section { break-before: page; } | Predictable starts for appendices and statements |
| Different first page | @page :first { margin-top: 40mm; } | Room for a letterhead on page 1 only |
Running headers, first-page differences in page furniture and header templates are covered in the headers and footers guide.
To see the checklist work, render the long sample yourself. Download template.html and data-long.json into one folder, set SUBLIMEPDF_API_KEY, and run this with Node.js 18 or later (save it as render-long-invoice.mjs). It sends the HTML with the data. If SUBLIMEPDF_TEMPLATE_ID is set, it sends the same data to your saved copy of the template instead:
import { readFile, writeFile } from "node:fs/promises";
const apiBase = process.env.SUBLIMEPDF_API_BASE_URL ?? "https://api.sublimepdf.com/v1";
const apiKey = process.env.SUBLIMEPDF_API_KEY;
if (!apiKey) throw new Error("Set SUBLIMEPDF_API_KEY");
const data = JSON.parse(await readFile("data-long.json", "utf8")); // { seller, customer, invoice, items, ... }
const templateId = process.env.SUBLIMEPDF_TEMPLATE_ID;
const [path, body] = templateId
? [`/templates/${encodeURIComponent(templateId)}/generate`, { data }]
: ["/html-to-pdf", { html: await readFile("template.html", "utf8"), data }];
const res = await fetch(apiBase + path, {
method: "POST",
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
body: JSON.stringify({ ...body, options: { format: "A4", printBackground: true } }),
});
if (!res.ok) throw new Error(`SublimePDF ${res.status}: ${await res.text()}`);
await writeFile("invoice-long.pdf", Buffer.from(await res.arrayBuffer()));
console.log("Saved invoice-long.pdf");Compare the result with the published four-page sample PDF, which was rendered locally from the same files with headless Chromium. In that sample the column header repeats on every page the table continues onto (pages 1 to 3), no row is split, the totals block stays in one piece, the payment notes move whole to page 4, and each footer reads "Page n of 4". Check the same points in your own output.
Backgrounds, colour and print media
Chrome leaves out backgrounds when printing unless you ask for them. The API's options.printBackground defaults to true, which prints backgrounds everywhere. With it set to false, our green test box lost its fill. One element can opt back in, though, and it worked even with printBackground: false:
.badge, .table-stripe {
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}page.pdf() renders with print media. Rules inside @media print applied, and elements hidden there were left out. Keep screen-only UI such as buttons, navigation and cookie banners out of the PDF with an @media print block, not by editing the template for each render.
Fonts: load, wait, embed
Fonts cause two kinds of PDF bug. The wrong font appears because the web font had not loaded when the page printed, or the right font appears but is embedded in a way a later tool objects to. Both are fixable in the template.
Declare fonts with @font-face
MDN describes @font-face as the rule that "specifies a custom font with which to display text", loaded from a server or from the user's computer. For documents, serve the font files yourself and declare every weight and style you use:
@font-face {
font-family: "Brand Sans";
src: url("https://assets.example.com/fonts/brand-sans-regular.woff2") format("woff2");
font-weight: 400;
font-style: normal;
font-display: block;
}
@font-face {
font-family: "Brand Sans";
src: url("https://assets.example.com/fonts/brand-sans-bold.woff2") format("woff2");
font-weight: 700;
font-style: normal;
font-display: block;
}
body { font-family: "Brand Sans", Arial, sans-serif; }- Use absolute HTTPS URLs or
data:URIs. HTML sent to an API has no base URL of yours, so a relativesrcsuch as/fonts/brand.woff2has nothing to resolve against. - Declare a real bold face. If only the regular file is declared, Chrome fakes bold. In our test, bold text with no bold face was drawn as a separate unnamed Type3 font while the regular text stayed a normal embedded TrueType font. The output looks heavier, but it is not the designer's bold, and it adds a font that some checks dislike.
- Prefer
font-display: block. MDN definesblockas "a short block period and an infinite swap period", so text waits for the font instead of printing in the fallback straight away, which is whatswap,fallbackandoptionalfavour. - List a fallback that is close in width. If the web font ever fails, a similar fallback keeps line breaks and page breaks close to the design.
Wait for fonts before printing
A web font that has not finished loading when the page prints is replaced by the fallback font. We measured this race with a font server delayed by 2 seconds and eight runs per strategy (font-race.mjs):
| When the PDF was printed | Web font embedded | Fallback embedded |
|---|---|---|
Right after DOMContentLoaded | 6 of 8 | 2 of 8 |
After document.fonts.ready | 8 of 8 | 0 of 8 |
After the load event | 8 of 8 | 0 of 8 |
The failure is intermittent. That is why it slips through testing and then shows up in production. To avoid it:
- Self-host fonts or inline them as
data:URIs in@font-face, so loading does not depend on a third-party CDN. - Keep font files small. A Latin-only WOFF2 file is a fraction of a full multilingual font, and it loads sooner.
- With the API,
options.waitFortakes a CSS selector or a number of milliseconds. A selector that appears once rendering is ready is more reliable than a fixed delay.
How Chromium embeds and subsets fonts
We printed four fixtures with a static TrueType font (179,492 bytes) served through @font-face under a custom family name, and read the font dictionaries of each PDF with pdf-lib (font-embedding.mjs):
| Fixture | Embedded as | Font stream in the PDF |
|---|---|---|
| "Invoice 42" in the web font | CIDFontType2 named AAAAAA+ArialNarrow | 7,584 bytes |
| Full alphabet, digits and punctuation | Same font, same subset name | 20,512 bytes |
A second @font-face declared but never used | Not downloaded, not embedded | — |
| Bold text with only a regular face declared | The TrueType subset plus an unnamed Type3 font | 7,076 bytes plus the Type3 glyphs |
What this means for your documents:
- Chrome subsets fonts. Only the glyphs the document uses are embedded, and the
AAAAAA+prefix is the standard marker for a subset. A short invoice carried about 4% of the font file. That keeps PDFs small, but it means the PDF cannot be edited later with characters that were not in it. - The PDF uses the font's own PostScript name, here
ArialNarrow, not the CSS family name. Search for that name when you check which fonts a PDF contains. - Unused faces cost nothing. A face is only downloaded and embedded when some text uses it, so a shared stylesheet with spare weights is harmless.
- Variable fonts behave differently. Our variable WOFF2 test font was embedded as a Type3 font with no font name. The text could still be extracted, but PDF/A and some accessibility checkers are strict about Type3 fonts. If that applies to you, use static font files and see the PDF/A guide.
- Check the licence. Embedding puts the font data (or a subset of it) inside every PDF you send. Make sure your font licence allows embedding in documents.
Images
loading="lazy"images far below the first screen were not printed. Chrome requested the file, but the PDF had no image. Useloading="eager"(the default) in templates.- A normal image printed correctly. A deliberately slow image (2 seconds) also appeared when we printed at
DOMContentLoaded, but treat that as luck, not a guarantee. Wait forloador use awaitForselector. - Small logos inline well as
data:URIs. Large photos make the request body bigger. The API answers413when a request is too large, so host big images and reference them by absolute HTTPS URL.
Layout pitfalls: flex, grid, vh, fixed and overflow
| Pattern | Local Chrome 158 result | Advice |
|---|---|---|
| Flex column longer than a page | Continued over 5 pages, nothing clipped | Safe |
| Flex row with two tall columns | Both columns continued onto page 2 | Safe, but the columns break independently |
| Grid of cards | Cards 15 and 16 split across a page | Add break-inside: avoid to the items |
column-count: 2 | Continued over 3 pages | Safe |
position: fixed element | Painted on every page | Good for watermarks, bad for a floating button |
html, body { height: 100%; overflow: hidden; } | Output cut to 1 page | Remove app-shell rules from print |
Three height: 100vh sections | Exactly 3 pages | Do not depend on it; use break-before: page |
The overflow: hidden trap is the most common cause of a "PDF only has one page" bug report. It appears when an app layout with a fixed-height shell is printed as-is. Reset it in print:
@media print {
html, body, #app { height: auto !important; overflow: visible !important; }
}What Chromium does not support
The paged-media specs go further than Chromium does. These fixtures failed in Chrome 158:
| Feature | Spec | Result | Alternative |
|---|---|---|---|
string-set with content: string() | GCPM | Value printed on 1 page of 3 | Named pages with fixed margin-box text, or a header template |
position: running() with element() | GCPM | Element not moved into the margin | Header and footer templates |
target-counter() for table-of-contents page numbers | GCPM | No page number generated | Two passes: render, read page numbers, render again |
bleed and marks: crop | Paged Media | Page size unchanged, no marks | Add bleed in a print-production tool |
break-before: right blank pages | Fragmentation | Plain page break | Insert blank pages yourself |
Margin boxes themselves do work. @page { @bottom-right { content: counter(page) " of " counter(pages); } } printed "PG 4 OF 4" on the last page of our fixture. The headers and footers guide covers margin boxes, header templates and first-page differences in depth.
Supported and unsupported matrix
| Area | Works in local Chrome 158 | Does not work |
|---|---|---|
| Page box | size (keywords, landscape, custom), margin, :first, named pages | bleed, marks |
| Breaks | break-before/after: page, break-inside: avoid, page-break-* aliases, orphans, widows | break-before: left/right/recto/verso blank pages |
| Tables | Repeating thead and tfoot, tr { break-inside: avoid } | Repetition after display: table-row-group |
| Colour and media | printBackground, print-color-adjust: exact, @media print | None found |
| Generated content | Margin boxes with counter(page) and counter(pages) | string-set, running elements, target-counter() |
| Loading | Web fonts after document.fonts.ready, eager images | Lazy images below the fold; fonts printed too early (intermittent) |
| Font embedding | Static TrueType faces embedded as named subsets | Variable fonts and synthetic bold embedded as unnamed Type3 fonts |
Run the fixtures yourself
Each fixture is a small, self-contained HTML file. Download the HTML from /samples/fixtures/css-guide/, for example the repeating table header fixture and its PDF. Send it to your renderer and compare the result. To repeat the whole suite locally with Chrome installed:
node scripts/research/css-guide/run.mjs # prints 51 fixtures, writes the evidence JSON
node scripts/research/css-guide/font-race.mjs # repeats the slow web-font test
node scripts/research/css-guide/font-embedding.mjs /path/to/static-font.ttf # font embedding and subsettingTo check your own layout through the API, send the HTML to POST /html-to-pdf, or send data to a template you saved in the app with POST /templates/{id}/generate. The end-to-end tutorial walks through it, and the API reference lists every render option.
Sources
- CSS Paged Media Module Level 3 (W3C Working Draft, 14 September 2023) · accessed 23 November 2026
- CSS Fragmentation Module Level 3 (W3C Candidate Recommendation, 4 December 2018) · accessed 23 November 2026
- CSS Generated Content for Paged Media Module (W3C Working Draft, 25 January 2024) · accessed 23 November 2026
- MDN: @page · accessed 23 November 2026
- MDN: @font-face · accessed 23 November 2026
- MDN: font-display · accessed 23 November 2026
- MDN: break-inside · accessed 23 November 2026
- MDN: widows · accessed 23 November 2026
- MDN: print-color-adjust · accessed 23 November 2026
- Chrome DevTools Protocol: Page.printToPDF (parameter definitions as bundled in playwright-core types/protocol.d.ts) · accessed 23 November 2026
- Playwright: page.pdf() · accessed 23 November 2026