Tutorial June 5, 2026 · 7 min read

Print-Grade PDFs from HTML and CSS

HTML is the most productive document-authoring format there is — once you teach it about paper. Here's how page rules, physical units, and WeasyPrint get you pixel-perfect PDFs.

Generating a PDF by printing a webpage through a headless browser works until it doesn't: fonts shift, margins drift, page breaks land mid-table, and the output depends on the browser version on the machine that rendered it. The problem is that screen CSS and print CSS are different disciplines. To produce documents that look identical every time, you author for paper from the start.

Start with the page box

Print layout begins with the @page rule, which defines the physical sheet and its margins. Use real-world units — millimeters or inches — not pixels:

@page {
  size: A4;
  margin: 20mm 18mm;
}

body { font-size: 11pt; line-height: 1.5; }
h1   { font-size: 18pt; }

Points and millimeters mean something physical on paper; pixels don't. An 11pt body renders at the same size whether the PDF prints in Mumbai or Berlin.

Control pagination deliberately

The thing that separates a print-grade document from a printed webpage is that you decide where pages break, not chance:

  • break-inside: avoid on a table row, a signature block, or a totals box keeps it from being split across two pages.
  • break-before: page forces a new page — useful for a terms-and-conditions section or a certificate page.
  • orphans and widows stop a paragraph from leaving one lonely line stranded at a page boundary.

For multi-page documents, running headers and footers with the page number live in @page margin boxes, so every sheet carries the invoice number or the company name without you repeating it in the body.

Why WeasyPrint instead of a browser

DocForge renders templates with WeasyPrint, a dedicated HTML/CSS-to-PDF engine, rather than driving a headless browser. The difference matters for documents:

  • Deterministic output. The same template and data produce a byte-stable PDF — no dependence on a browser version or GPU.
  • Real print CSS. First-class support for @page, margin boxes, and the fragmentation properties that browsers treat as second-class.
  • Embedded fonts. Fonts are embedded in the PDF, so the document looks right on a machine that's never heard of your brand typeface.
  • No browser to operate. No headless Chrome to install, sandbox, and keep patched.

Templating on top

DocForge's Studio pairs this with Jinja templating and a live split preview: you author the HTML/CSS, see it render as you type, and bind fields to your data. The environment is sandboxed — authors get templating, never arbitrary code — so a template is safe to share across a team without it becoming an execution risk.

Author for paper, render with a real print engine, and a PDF stops being a lucky screenshot of a webpage and becomes a document you can put your company's name on.