I stopped trying to make HTML paginate for printing (and it finally worked)
Source: Dev.to
The underlying problem
For several months, I struggled with a problem many developers are familiar with: printing HTML content correctly across multiple pages without breaking the layout. Like many others, I tried the usual approaches:
- CSS
page-break-* @printmedia queries- headless browsers
- HTML → PDF generators
They work… up to a point. As soon as the content becomes even slightly complex, dynamic, or editable, everything starts to break down: unpredictable page breaks, truncated elements, inconsistent margins, widows and orphans everywhere.
The turning point
At some point, I stopped trying to “convince” HTML to paginate properly. Instead of cutting the content, I inverted the reasoning: what if each page were simply a window onto a larger, continuous piece of content? That’s when I separated two responsibilities that are often tightly coupled:
- content rendering
- pagination
A different approach
Concretely, the idea is to create a logical A4 page in CSS that acts as a window onto a larger HTML document, and then clone that page as many times as needed. Each page dynamically displays a different portion of the same content using vertical offsets, creating the illusion of a unified multipage document. The content is never “broken” or arbitrarily split: it is simply observed through successive windows, whose size and surrounding metadata can be fully controlled. What you see on screen is not exactly what gets printed — and that is intentional.
What this changes
This separation enables:
- stable and predictable multipage output
- documents that remain fully editable before printing
- deterministic pagination, even with complex content
The implementation is intentionally simple from a technology standpoint (plain vanilla JavaScript), but it relies on a fundamentally different way of approaching the problem.
PS: Please note that this approach is covered by a patent. I prefer to clarify this upfront to avoid any confusion regarding its exploitation.