Creating page breaks in wkhtmltopdf


We're using wkhtmltopdf to convert some of our HTML pages to PDFs. wkhtmltopdf doesn't give much control over where the pages break resulting in some rather nasty-looking page breaks like in the image:

I had hoped to fix it with something like this:

@media print
#manualContent h2 {page-break-before:always;}

However, that's not doing a thing. Does anyone know how to do this? We're doing a 200+ page manual that will be updated fairly frequently so to try to catch the bad page breaks and change the HTML by hand before creating the PDF each time isn't really feasible.


Assuming that you've got the selectors right, that should be doing the trick. Although a better plan might be to have
#manualContent .keeptogether {page-break-inside:avoid;}
as well, and you can then put class="keeptogether" on any element that you don't want to be split over two pages, rather than relying on the h2s falling in the right place.

As far as I can tell, wkhtmltopdf is based on Webkit, which seems to obey page-break commands pretty well – it respects table {page-break-inside:avoid;}, which Firefox and IE don't. There's a thread on their help pages about page breaks: It looks as though if you have any floats going on then that could be what is stuffing it up, and I'm guessing from your attachment that you do.

As a general rule, floats and page breaks go together about as well as caviar and custard. Try to avoid having floats on the printed page if possible!


Ok, thanks for the tips. I'll clean up my HTML and try again.