How to insert a page break in HTML so wkhtmltopdf parses it?
To initialize a page break in PDFs rendered by wkhtmltopdf, use CSS's page-break-after
on an element:
This element can be hosted wherever the page split is needed. It signals wkhtmltopdf to commence a new page from that location in the output PDF.
The page-break trident: after, before, inside
To handle your page breaks like a pro, you need the entire page-break trident in your arsenal. It's not just page-break-after
doing the heavy lifting, you've got page-break-before
and page-break-inside
backing it up:
- Before elements:
- After elements:
- Inside elements:
For an extra layer of finesse, encase the element in a <div>
with the display: block;
and clear: both;
styles:
Score extra points with layout control
Mastering the layout with @page
, setting page margins, and controlling orphans and widows are all part of the game:
- Set margins:
- Orphans & Widows:
Fine-tuning page breaks
Let's step up the game by introducing box-decoration-break
which assists in managing elements that cross over page breaks:
To deal with page sizing, use the size
property within @page
. Measurements like mm, cm, in, and even px for screen-based sizes are fair play:
Tackle common nuisances
page-break
properties might sometimes play hard to get. It's important to remember that nested elements with certain display properties could ignore breaks:
-
Inline-block items: Elements set to
display: inline-block;
may wave off page breaks. -
Flexbox & Grid players: Container elements with Flexbox or Grid layouts can also hinder proper page breaks.
-
Floating elements: Make sure no floating elements (
float: left;
orfloat: right;
) block page breaks.
Put to test
Before you rest on your laurels, it's a good idea to test across different content bounds. Fine-tune using @media print
query to alter styles specifically for print:
It's crucial to remember that @media print
could sometimes upset the wagon. So, it's better to stick with assigned CSS page-break properties.
Know thy wkhtmltopdf
Wkhtmltopdf comes with its bag of tricks. So remember to:
- Ensure appropriate content scaling to prevent clipping.
- Consider using viewport units for optimal sizing.
Being a wkhtmltopdf wizard, you'll want to keep these up your sleeve for an unrivaled PDF pagination experience.
Was this article helpful?