Print CSS for HTML to PDF: Page Size, Page Breaks, Tables and Fonts in Headless Chrome
Summary. Most HTML-to-PDF bugs are print CSS bugs, not API bugs. Typical ones: the landscape option does nothing, a heading sits alone at the bottom of page 3, a table loses its header after the first page, the brand font falls back to the system font, and the footer covers the last line of text. Headless Chrome is a full print engine, and once you know how it decides page size, margins and breaks, the PDF stops surprising you. This guide is a print stylesheet you can copy, the Api2Pdf options that work with it (and which of them your CSS overrides), a full Python and Node.js example that renders a multi-page report with a full-bleed cover, repeating table headers, a landscape section, page numbers, web fonts and PDF bookmarks, and a local preview loop so you can iterate without spending API calls.
How it was checked: every CSS rule and option interaction below was rendered locally with Chrome 156 through the DevTools Page.printToPDF call, which is the same call Puppeteer makes for the Api2Pdf /chrome endpoints, and the results were inspected with pdfinfo and pdftotext. The request bodies were checked against the live OpenAPI spec and captured from a local mock server. They were not sent to the live API. If you are coming from wkhtmltopdf, read the migration guide first. Its print engine is much older than Chrome's, and several rules here behave differently there.
Who decides the page: API options or your CSS
POST /chrome/pdf/html (and /chrome/pdf/url) takes an options object. These are the fields that interact with print CSS, with their defaults from the spec:
| Option | Default | What it does |
|---|---|---|
width, height | "8.27in", "11.69in" | Paper size (A4) used when your CSS does not set one, or when preferCSSPageSize is false |
marginTop / Right / Bottom / Left | ".4in" | Page margins. An @page { margin } rule in your CSS takes precedence |
preferCSSPageSize | false | Use the @page { size } from your CSS instead of width/height. Required for named pages with different sizes |
landscape | false | Swaps the paper dimensions. Ignored as soon as your CSS declares @page { size } |
usePrintCss | true | Render with the print media type, so @media print rules apply |
printBackground | true in the spec | Print background colors and images. The older options page says false, so set it explicitly |
scale | 1 | Zoom factor for the content. Leave it at 1 and size things in CSS |
displayHeaderFooter, headerTemplate, footerTemplate | false | Chrome-drawn header and footer in the page margin, with page numbers |
tagged, outline | true, false | Tagged (accessible) PDF structure, and PDF bookmarks generated from your headings |
delay, puppeteerWaitForMethod, puppeteerWaitForValue | 0, empty | Wait before printing, for a fixed time or until a condition is met (fonts, charts) |
The rules that cause most of the confusion, each confirmed in the local renders:
- With
preferCSSPageSize: false(the default), your@page sizeis ignored. Chrome uses the option's paper size and scales your page to fit, so a stylesheet written for A5 comes out on A4 paper with shrunken content. If you write@page { size }, sendpreferCSSPageSize: true. landscape: trueloses to any@page sizedeclaration. A stylesheet withsize: A4stays portrait even withlandscape: true, whateverpreferCSSPageSizeis set to. This is the cause of our most-read troubleshooting post. Put the orientation in CSS:size: A4 landscape.- CSS margins beat option margins. If
@pagesetsmargin, themargin*options have no effect. Choose one place to set margins. With CSS you can also give a cover pagemargin: 0. - An invalid size makes Chrome drop the whole declaration, with no error. The size keywords are
A5 A4 A3 B5 B4 JIS-B5 JIS-B4 letter legal ledger.size: A6is not one of them, so Chrome quietly falls back to the option's paper size. For anything else, give dimensions:size: 105mm 148mmorsize: 4in 6in.
A print stylesheet you can start from
This is the full stylesheet for the example report. Each numbered block is explained below:
/* print.css - a baseline print stylesheet for HTML to PDF in Headless Chrome */
/* 1. Page box: size, margins, named pages */
@page {
size: A4; /* keywords: A3 A4 A5 B4 B5 letter legal ledger, or "8.5in 11in" */
margin: 22mm 16mm 20mm 16mm; /* top right bottom left; leave room for header/footer templates */
}
@page cover { margin: 0; } /* full-bleed first page */
@page wide { size: A4 landscape; } /* any element with page: wide gets landscape pages */
/* 2. Colors and backgrounds print exactly as on screen */
html { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
/* 3. Type */
body { margin: 0; color: #111827; font: 10.5pt/1.45 "Inter", system-ui, sans-serif; }
h1, h2, h3 { line-height: 1.2; break-after: avoid; } /* never strand a heading at the bottom of a page */
p, li { orphans: 3; widows: 3; }
a { color: inherit; text-decoration: none; }
img, svg, canvas { max-width: 100%; }
/* 4. Explicit breaks */
.cover { page: cover; height: 297mm; box-sizing: border-box; padding: 60mm 20mm;
background: #0b1220; color: #fff; break-after: page; }
.cover h1 { font-size: 30pt; margin: 0 0 8mm; }
.chapter { break-before: page; }
.landscape { page: wide; }
/* 5. Keep blocks in one piece */
figure, .card, .signature { break-inside: avoid; }
.card { border: 1px solid #d1d5db; border-radius: 6px; padding: 10px 12px; margin: 0 0 10px; }
/* 6. Tables that span pages */
table { width: 100%; border-collapse: collapse; font-size: 9pt; }
thead { display: table-header-group; } /* repeats on every page */
tfoot { display: table-footer-group; } /* also repeats on every page */
tr { break-inside: avoid; }
th { background: #e5edff; text-align: left; }
th, td { padding: 4px 6px; border-bottom: 1px solid #e5e7eb; }
tbody tr:nth-child(even) td { background: #f9fafb; }
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
/* 7. Screen-only UI */
@media print { .no-print { display: none !important; } }
Page size, margins and named pages
@page sets the paper and the margin box for every page. Named pages let parts of one document use different page styles. Give an element page: wide and Chrome starts a new page that uses the @page wide rule. In the example, the cover is a zero-margin full-bleed page, the body is portrait A4, and a 14-column table at the end gets a landscape A4 page, all in one PDF. In the local render, pdfinfo reports pages 1 to 4 as 595x842 pt and page 5 as 842x595 pt. Named pages only work with preferCSSPageSize: true.
Size the cover in physical units (height: 297mm for A4) rather than 100vh. The viewport height is not the paper height, and a cover one pixel too tall pushes a blank page into the PDF.
Page breaks: force, avoid, and keep together
Use the modern properties. Chrome still accepts page-break-before and friends as aliases, but break-before, break-after and break-inside are the current ones:
break-before: pageon each chapter starts it on a new page.break-after: pageon the cover does the same for whatever follows.break-after: avoidon headings stops a heading from being stranded at the bottom of a page. In a test page with a heading on the last line, Chrome left the heading alone on page 1 without the rule and moved it to page 2 with its paragraph once the rule was added.break-inside: avoidkeeps a card, figure, signature block or table row in one piece. Use it on small blocks only. A block taller than a page breaks anyway, and too many unbreakable blocks leave large gaps.orphansandwidows(minimum lines left at the bottom or carried to the top of a page) stop single lines of a paragraph from being left behind. 3 is a good default for reports.
Tables that span pages
Chrome repeats <thead> at the top of every page a table crosses, and it also repeats <tfoot> at the bottom of every page, which is useful for a short note like units or currency. In the example, the 92-row table spans three pages and the header row appears on each one. Two details make the difference:
- Use real
<thead>/<tbody>markup. A header row made of styled<td>cells inside<tbody>is not repeated. Some data-grid components render header rows that way. tr { break-inside: avoid; }keeps a row from being split across two pages. For rows with long text, it is often better to let them break.
Wide tables are the other problem. Put the table in a page: wide section, as above, instead of shrinking it with scale or zoom. Use font-variant-numeric: tabular-nums so the digits in numeric columns line up.
Backgrounds and colors
Browsers drop backgrounds when printing unless you opt in. Api2Pdf exposes this as printBackground. The CSS side is print-color-adjust: exact (plus the -webkit- prefix for older engines), which makes Chrome keep zebra stripes, colored table headers and brand blocks instead of adjusting them for ink. Older posts on Bootstrap striped tables and header and footer backgrounds cover the same issue in more detail.
Screen-only elements
Navigation, buttons, cookie banners and chat widgets should not appear in a document. With usePrintCss on (the default), a @media print { .no-print { display: none } } rule removes them. The report template has a "Back to dashboard" link marked no-print, and pdftotext confirms it is not in the PDF. This matters most for /chrome/pdf/url, where you are printing a page that was designed for the screen.
Fonts: embed them, then wait for them
A PDF made from HTML embeds the fonts that were actually used to lay out the page. If the web font has not loaded when Chrome prints, the PDF gets the fallback font, and the line breaks differ from what you saw in the browser. There are three ways to avoid this, from most to least robust:
- Inline the font. Put
@font-face { src: url(data:font/woff2;base64,...) }in the stylesheet. Nothing is fetched, so nothing has to finish loading. Subset the font first to keep the payload small. - Load it from an absolute URL and signal when it is ready. The template below loads Inter from Google Fonts. A small script waits for
document.fonts.load()and then adds aprint-readyclass to<html>. The request setspuppeteerWaitForMethod: "WaitForSelector"andpuppeteerWaitForValue: "html.print-ready", so Chrome prints as soon as the fonts are in, not after a guessed delay. The same pattern works for charts: add the class in the chart library's render callback. In the local render,pdffontslists Inter as the embedded font. delay(milliseconds) is the blunt option. It is fine for a quick fix, but it makes every request slower, and you pay per second of compute.
Call document.fonts.load() explicitly instead of only awaiting document.fonts.ready. When the script runs, layout may not have requested the font yet, and ready can resolve before the download starts.
The same rule applies to images and stylesheets: use absolute URLs. HTML sent to /chrome/pdf/html has no page origin, so src="/img/logo.png" has nothing to resolve against. Use full https:// URLs, a <base href> tag, or data: URIs.
Headers, footers and page numbers
Chrome draws headerTemplate and footerTemplate in the top and bottom page margins, outside your document. Chrome fills in five classes: pageNumber, totalPages, title (your <title>), url and date. Most broken footers come from three things:
- No room. The template draws inside the margin. A 4mm bottom margin clips a 10px footer. The stylesheet above uses 20 to 22mm top and bottom.
- No styles. The template does not see your page CSS, and the default font size is tiny. Put inline styles on the template markup, set a
font-size, and usedata:URIs for logos. - Every page gets it. The template is drawn on every page, including a zero-margin cover, where it lands on top of the artwork. If the cover has to be clean, render it in a separate request without
displayHeaderFooterand join the two files withPOST /pdfsharp/merge(a list of PDF URLs inurls). The Node.js guide has a merge example.
For a deeper look at the template syntax, see header, footer and page numbers with Headless Chrome.
The complete example: a multi-page report
The template uses Jinja2, but nothing in it is Jinja-specific. The CSS is inlined into a <style> tag, so the HTML is self-contained apart from the web font:
{# templates/report.html.j2 #}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{ title }}</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=block">
<style>{{ css | safe }}</style>
</head>
<body>
<section class="cover">
<h1>{{ title }}</h1>
<p>{{ customer }} · {{ period }}</p>
</section>
<nav class="no-print"><a href="/dashboard">Back to dashboard</a></nav>
<section class="chapter">
<h2>1. Summary</h2>
{% for k, v in summary %}<div class="card"><strong>{{ k }}:</strong> {{ v }}</div>{% endfor %}
<h2>2. Usage by day</h2>
<table>
<thead><tr><th>Date</th><th>Endpoint</th><th class="num">Requests</th><th class="num">MB out</th></tr></thead>
<tbody>
{% for r in rows %}
<tr><td>{{ r.date }}</td><td>{{ r.endpoint }}</td><td class="num">{{ "{:,}".format(r.requests) }}</td><td class="num">{{ "%.1f"|format(r.mb) }}</td></tr>
{% endfor %}
</tbody>
<tfoot><tr><td colspan="4">All dates in UTC.</td></tr></tfoot>
</table>
</section>
<section class="chapter landscape">
<h2>3. Requests by endpoint and week</h2>
<table>
<thead><tr><th>Endpoint</th>{% for w in weeks %}<th class="num">{{ w }}</th>{% endfor %}</tr></thead>
<tbody>
{% for name, cells in matrix %}
<tr><td>{{ name }}</td>{% for c in cells %}<td class="num">{{ c }}</td>{% endfor %}</tr>
{% endfor %}
</tbody>
</table>
</section>
<script>
// Tell Api2Pdf (WaitForSelector "html.print-ready") when the web fonts are actually loaded.
Promise.all([
document.fonts.load('400 1em Inter'),
document.fonts.load('700 1em Inter'),
]).then(() => document.fonts.ready)
.finally(() => document.documentElement.classList.add('print-ready'));
</script>
</body>
</html>
The Python renderer uses plain requests, so the exact JSON body is visible. ?outputBinary=true returns the PDF bytes directly instead of the usual JSON response with a 24-hour FileUrl. Errors still come back as JSON, so the script checks for the %PDF- magic bytes before writing the file:
# render_report.py
"""Render templates/report.html.j2 to a PDF with Api2Pdf (Headless Chrome).
pip install requests jinja2
API2PDF_KEY=your-key python render_report.py # writes report.pdf
python render_report.py --html-only # writes report.html for local preview
"""
import datetime as dt
import os
import pathlib
import random
import sys
import requests
from jinja2 import Environment, FileSystemLoader, select_autoescape
API_URL = "https://v2.api2pdf.com/chrome/pdf/html"
HERE = pathlib.Path(__file__).resolve().parent
# Header/footer templates render in the page margin, outside your document:
# inline styles only, and set a font-size (the default is tiny).
HEADER = ('<div style="font-size:8px;width:100%;padding:0 16mm;color:#6b7280;">'
'<span class="title"></span></div>')
FOOTER = ('<div style="font-size:8px;width:100%;padding:0 16mm;color:#6b7280;text-align:right;">'
'Page <span class="pageNumber"></span> of <span class="totalPages"></span></div>')
CHROME_OPTIONS = {
"preferCSSPageSize": True, # @page decides size and orientation (needed for named landscape pages)
"printBackground": True, # print backgrounds and colors
"usePrintCss": True, # render with @media print rules
"displayHeaderFooter": True,
"headerTemplate": HEADER,
"footerTemplate": FOOTER,
"tagged": True, # accessible, tagged PDF
"outline": True, # PDF bookmarks generated from h1-h6
"puppeteerWaitForMethod": "WaitForSelector",
"puppeteerWaitForValue": "html.print-ready", # set by the template once fonts are loaded
}
def sample_context():
rnd = random.Random(7)
start = dt.date(2026, 10, 1)
rows = [{"date": (start + dt.timedelta(days=i)).isoformat(), "endpoint": "/chrome/pdf/html",
"requests": rnd.randint(800, 3000), "mb": rnd.uniform(40, 200)} for i in range(92)]
weeks = [f"W{n}" for n in range(40, 53)]
endpoints = ["/chrome/pdf/html", "/chrome/pdf/url", "/libreoffice/any-to-pdf", "/pdfsharp/merge",
"/pdfsharp/watermark", "/zip", "/zebra", "/markitdown"]
matrix = [(e, [f"{rnd.randint(100, 9999):,}" for _ in weeks]) for e in endpoints]
summary = [("Documents generated", "182,340 (+12% QoQ)"), ("Median render time", "1.8 s")]
return {"title": "Quarterly usage report", "customer": "Acme Corp", "period": "Q4 2026",
"summary": summary, "rows": rows, "weeks": weeks, "matrix": matrix}
def render_html(ctx):
env = Environment(loader=FileSystemLoader(HERE / "templates"), autoescape=select_autoescape())
return env.get_template("report.html.j2").render(css=(HERE / "print.css").read_text(), **ctx)
def html_to_pdf(html, file_name):
resp = requests.post(
API_URL,
params={"outputBinary": "true"}, # return the PDF bytes instead of a JSON body with FileUrl
headers={"Authorization": os.environ["API2PDF_KEY"]},
json={"html": html, "fileName": file_name, "inline": False, "options": CHROME_OPTIONS},
timeout=(5, 120),
)
if resp.status_code != 200 or not resp.content.startswith(b"%PDF-"):
raise RuntimeError(f"Api2Pdf returned {resp.status_code}: {resp.text[:500]}")
return resp.content
if __name__ == "__main__":
html = render_html(sample_context())
if "--html-only" in sys.argv:
(HERE / "report.html").write_text(html)
print("wrote report.html")
else:
(HERE / "report.pdf").write_bytes(html_to_pdf(html, "q4-usage-report.pdf"))
print("wrote report.pdf")
The same request with the official Node.js SDK. The SDK sends filename as fileName, and with outputBinary: true it resolves to a Buffer. Both scripts were run against a local mock server, and they sent identical request bodies:
// render_report.mjs
// Same render with the official Node.js SDK.
// npm install api2pdf
// API2PDF_KEY=your-key node render_report.mjs report.html report.pdf
import Api2Pdf from "api2pdf";
import { readFile, writeFile } from "node:fs/promises";
const [, , input = "report.html", output = "report.pdf"] = process.argv;
const client = new Api2Pdf(process.env.API2PDF_KEY);
const header = `<div style="font-size:8px;width:100%;padding:0 16mm;color:#6b7280;">
<span class="title"></span></div>`;
const footer = `<div style="font-size:8px;width:100%;padding:0 16mm;color:#6b7280;text-align:right;">
Page <span class="pageNumber"></span> of <span class="totalPages"></span></div>`;
const html = await readFile(input, "utf8");
const pdf = await client.chromeHtmlToPdf(html, {
filename: "q4-usage-report.pdf",
inline: false,
outputBinary: true, // resolve to a Buffer instead of { FileUrl, ... }
options: {
preferCSSPageSize: true,
printBackground: true,
usePrintCss: true,
displayHeaderFooter: true,
headerTemplate: header,
footerTemplate: footer,
tagged: true,
outline: true,
puppeteerWaitForMethod: "WaitForSelector",
puppeteerWaitForValue: "html.print-ready",
},
});
await writeFile(output, pdf);
console.log(`wrote ${output} (${pdf.length} bytes)`);
Or with curl and jq, sending the rendered report.html. jq --rawfile takes care of escaping the HTML into JSON:
#!/usr/bin/env bash
# render_report.sh
# curl + jq version: sends report.html (from: python render_report.py --html-only)
set -euo pipefail
FOOTER='<div style="font-size:8px;width:100%;text-align:center;"><span class="pageNumber"></span> / <span class="totalPages"></span></div>'
jq -n --rawfile html report.html --arg footer "$FOOTER" '{
html: $html, fileName: "q4-usage-report.pdf", inline: false,
options: {
preferCSSPageSize: true, printBackground: true, outline: true,
displayHeaderFooter: true, headerTemplate: "<span></span>", footerTemplate: $footer,
puppeteerWaitForMethod: "WaitForSelector", puppeteerWaitForValue: "html.print-ready"
}
}' | curl -sS --fail-with-body -o report.pdf \
-H "Authorization: $API2PDF_KEY" -H "Content-Type: application/json" \
--data-binary @- "${API2PDF_BASE:-https://v2.api2pdf.com}/chrome/pdf/html?outputBinary=true"
head -c 5 report.pdf | grep -q '%PDF-' || { cat report.pdf; exit 1; }
echo "wrote report.pdf"
The local render of this template is five pages: the full-bleed cover, a summary followed by the daily table across three portrait pages with the header row repeated on each, and the weekly matrix on a landscape page. The PDF is tagged, has a bookmark for each heading, and embeds Inter.
Iterate locally, then render with Api2Pdf
You do not need an API call to check a print layout. Chrome's own print engine shows you the same page boxes, breaks and fonts. Two options (see also Test your HTML locally first):
- DevTools. Open the rendered HTML, press Cmd/Ctrl+Shift+P, run "Emulate CSS print media type" to see
@media printrules applied, then open print preview (Cmd/Ctrl+P) to see real page breaks. - Headless CLI. The script below re-renders the template and prints it with the local Chrome. The CLI honors
@pagesizes and named pages. It does not draw your header and footer templates, so check those against the API once the layout is right.
#!/usr/bin/env bash
# preview.sh
# Local preview loop: same rendering engine family as the Api2Pdf /chrome endpoints, no API calls.
# The Chrome CLI honors @page size; it does not draw headerTemplate/footerTemplate.
set -euo pipefail
python render_report.py --html-only
google-chrome --headless --no-pdf-header-footer --print-to-pdf=preview.pdf "file://$PWD/report.html"
pdfinfo preview.pdf | grep -E "^Pages|size"
When the local PDF looks right, run the real render once and compare the two. Fonts and anything fetched over the network are the most likely differences between your machine and the API.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Landscape option is ignored | The stylesheet declares @page { size } | Put the orientation in CSS: size: A4 landscape (and send preferCSSPageSize: true) |
| PDF is A4 or Letter instead of the size in your CSS | preferCSSPageSize is false, or the size keyword is invalid (for example A6) | Send preferCSSPageSize: true. Use dimensions such as 105mm 148mm for sizes that are not keywords |
| Content is shrunk to fit the page | CSS page size differs from the paper size and preferCSSPageSize is false | Same fix. Leave scale at 1 |
| Blank page after the cover or at the end | A block is taller than the page (often 100vh or padding on top of a fixed height), or there is a forced break after the last element | Use physical units with box-sizing: border-box. Only put break-after: page on elements that are followed by content |
| Table header appears only on page 1 | The header row is not inside <thead> | Use real <thead> markup. display: table-header-group is the default for it |
| Heading alone at the bottom of a page | No break control on headings | h1, h2, h3 { break-after: avoid; } |
| Backgrounds or zebra stripes are missing | Backgrounds are off for print | printBackground: true plus print-color-adjust: exact |
| Wrong font in the PDF | The web font had not loaded when Chrome printed | Inline the font, or use the print-ready class with WaitForSelector |
Images or CSS missing with /chrome/pdf/html | Relative URLs with no origin to resolve against | Use absolute URLs, a <base href> tag, or data: URIs |
| Footer missing, clipped, or tiny | Margin too small, displayHeaderFooter not set, or no font-size | Use 15mm or more of margin, set displayHeaderFooter: true, and put inline styles with an explicit font size on the template |
| Footer printed on the cover | Templates are drawn on every page | Render the cover separately and join the files with /pdfsharp/merge |
Wrap-up
Print CSS for Chrome comes down to a few rules. Let @page own the size and orientation and send preferCSSPageSize: true. Force breaks before chapters and avoid them after headings. Use real <thead> markup. Load fonts from absolute URLs and wait for them before printing. Leave room in the margins for the footer. Copy the stylesheet above into your project, iterate with local Chrome, and send the finished HTML to /chrome/pdf/html. For framework integration, see the FastAPI, Next.js, Laravel and Rails guides. For running it at volume, see Api2Pdf in production. Create a free account to get an API key. Every option is listed in the interactive API docs.



