css, page breaks

Similarly like in word editors, there are also page breaks in CSS that allows you to break your content across pages. With these properties you can control page breaks when printing and converting to PDF.

How to control page breaks in CSS

There are three different css properties for page break control:

  • page-break-before
    • The page-break-before property control a page-break that occur immediately before the element to which it is applied.
  • page-break-after
    • The page-break-after property control a page-break that occur immediately after the element to which it is applied.
  • page-break-inside
    • The page-break-inside property control a page-break inside the element to which it is applied.

These properties can be applied to block-level elements in the normal flow of the root element.

Empty, zero-height or absolutely positioned elements are not applicable.

Syntax for css page break property

page-break-after: auto | always | avoid | left | right
page-break-before: auto | always | avoid | left | right
page-break-inside: auto | avoid

Detailed descriptions of each css page break possible value:

auto: Initial value. Automatic page breaks.
always: Always force page breaks before/after the element.
avoid: Avoid page breaks before/after/inside the element.
left: Force page breaks before/after the element so that the next page is formatted as a left page.
right: Force page breaks before/after the element so that the next page is formatted as a right page.

/* avoid splitting element across pages */
.no-break {
  page-break-inside: avoid;
}
/* force h2 title to display on new page */
h2 {
  page-break-before: always;
}
<h2>Title</h2>
<div>
  ... content ...
</div>
<div class=”no-break”>
  ... content inside this element will not break from page to page ...
</div>
<h2>New page title</h2>

How to control page breaks inside tables

HTML PDF API controls page breaks in tables and table rows automatically, but however, in some specific situations with advance layout, you can get all kinds of incompatibility. If you're building the table in such situations, we'd suggest cutting it up into smaller tables, and put page breaks between them. The other solution is to convert table to block elements structure.

Also HTML PDF API is trying to keep image elements from being split in half automatically, but in tables they may hang over the page break a bit. The best way to deal with this problem is to wrap img with block-element.

.no-break {
  page-break-inside: avoid;
}
<td>
  <div class="no-break">
    <img src="http://placehold.it/350x700">
    <img src="http://placehold.it/350x600">
  </div>
</td>

Page break examples

Here are examples of using css page breaks with HTML PDF API.

page_breaks.zip
page_breaks_tables.zip

For more information of how you can send zip file to HTML PDF API service please visit documentation page.