CSS, Web Development

Inserting page breaks for printing or PDF via HTML

So we have a web invoice which is also converted into PDF. When line items section becomes too tall (so many items), the generated PDF from HTML (via wkhtmltopdf) breaks some of the lines in the summary section and is pushed to the next page. It would be nice if the whole summary section is automatically pushed to the next page when the section before it is too tall.


Our invoice layout is just the typical invoice design with header section, recipient section, line items and summary section which also includes the footer. Most of the sections are fixed except for the line items which can be one more more items and can grow tall that the whole invoice won’t fit one page.


My immediate reaction was to think of a way to count the line items and insert page break dynamically when the number of line items is enough to insert the page break before the summary section. However, that is too messy and is prone to error.

A quick search leads me to this forum post from SitePoint. From the post, I learned that I can use CSS to keep a certain section intact and prevent page break from within.

Therefore, I set the summary section to prevent page breaks within inside using this style:

.invoice-summary {
  page-break-inside: avoid;

To test, I used the browser’s print preview and as well as the generated PDF for the invoice, and indeed, it inserts the page break before the invoice summary, pushing the whole summary section to the next page.

That’s it!

Leave a reply

Your email address will not be published. Required fields are marked *