rustedf.cloud
Menu

Page breaks in a PDF with CSS: keep blocks and tables together

Published 2 min read

A browser page scrolls, so nobody notices where a block ends. In a PDF, a page ends where the paper does, and the default is to cut wherever the content happens to be. That is how a signature lands alone on page three, or a total ends up apart from its table. CSS has properties for this, and the rustedf.cloud renderer supports them.

Start something on a new page

.terms { break-before: page; }
.cover { break-after: page; }

break-before and break-after force a break before or after an element. The older names, page-break-before: always and page-break-after: always, work too. Use them for a cover page, or for terms and conditions that should always open on a fresh page.

Keep a block in one piece

.signature,
.totals,
.card { break-inside: avoid; }

break-inside: avoid asks the renderer to move a block to the next page rather than split it. It is the right tool for a signature block, a totals box or a card.

To keep a heading with the paragraph under it, wrap both in one element and put break-inside: avoid on that wrapper, so a title is not left alone at the bottom of a page.

A small table can be kept whole the same way, by putting break-inside: avoid on the table.

Long tables

A long table has to be split. The renderer continues it on the next page and repeats the header row on every page the table spans, so the reader never has to flip back to remember what a column means. Put the column titles in a <thead>:

<table>
<thead>
<tr><th>Item</th><th>Qty</th><th>Amount</th></tr>
</thead>
<tbody>
{% for line in lines %}
<tr><td>{{ line.name }}</td><td>{{ line.qty }}</td><td>{{ line.amount }}</td></tr>
{% endfor %}
</tbody>
</table>

Lines at the edge of a page

Two more properties control single lines of a paragraph. orphans is the minimum number of lines left at the bottom of a page, and widows the minimum carried to the next one.

p { orphans: 3; widows: 3; }

The renderer applies widow and orphan control, so a paragraph does not leave one lonely line at the top or bottom of a page.

When a block cannot be split

break-inside: avoid cannot help a block taller than a page. A box with a fixed height larger than the paper, or content painted outside it, is reported as LayoutOverflow by validation. Let such a block grow with its content instead of fixing its height.

Check the result

The page count of a render is in the X-Pages response header, and POST /v1/validate returns it as pages without using a credit. Render a document with the longest realistic data, because that is where breaks appear.

See Supported HTML and CSS and Validating a document.

← All posts