I'm making a HTML report that is going to be printable, and it has "sections" that should start in a new page.
Is there any way to put something in the HTML/CSS that will signal to the browser that it needs to force a page break (start a new page) at that point?
I don't need this to work in every browser out there, I think I can tell people to use a specific set of browsers in order to print this.
Add a CSS class called "pagebreak" (or "pb"), like so:
@media print {
.pagebreak { page-break-before: always; } /* page-break-after works, as well */
}
Then add an empty DIV tag (or any block element that generates a box) where you want the page break.
<div class="pagebreak"> </div>
It won't show up on the page, but will break up the page when printing.
P.S. Perhaps this only applies when using -after
(and also what else you might be doing with other <div>
s on the page), but I found that I had to augment the CSS class as follows:
@media print {
.pagebreak {
clear: both;
page-break-after: always;
}
}
But like all good things in CSS, this doesn't always work consistently across the board, so test the living daylights out of it, lest you have angry users wondering why your site prints piles of extra blank pages!
According to MDN,
page-break-after
"applies to block elements that generate a box," so using an empty<span>
element won't work. It's a better idea to apply it to a piece of your content. See developer.mozilla.org/en-US/docs/Web/CSS/page-break-after@nullability: Good catch. I had mainly used this at my old job in a WebBrowser control in WinForms which used IE, the gold standard of following standards.
This did not work for me in Chrome... I'm trying to do a pagebreak inside after a <tr> inside a <table>, will it work in this case ?
For some reason, when using this trick in Chrome, 1 row of pixels of next page was leaking into previous one (noticeable when using background-color). I fixed it by using
.pagebreak { min-height: 1px; page-break-before: always; }