Javascript – Paginating HTML document for printing with WebKit-based browsers

htmljavascriptphantomjsprintingwebkit

Internet Explorer has Print Template engine, where I can use DEVICERECT element to represent a physical page, then use LAYOUTRECT element as a rectangular view to flow the HTML document through into the page and drive the pagination. That prevents lines from being cut-off in the middle between adjacent pages. This mechanism is described in details here.

Does WebKit provide a similar feature? Specifically, does PhantomJS do? I'm looking for anything that would allow to paginate an existing HTML document which doesn't have predefined page-breaks, and view it paginated as a new transformed HTML or PDF document, without lines being cut-off in middle.

Best Answer

The browser engine should take care of everything and you can aid it using a stylesheet for media="print".

For example to force page breaks such that every heading of level 1 or 2 (<h1> or <h2>) is placed at the beginning of a new page use page-break-before:

h1, h2 { page-break-before:always; }

In Chrome, IE & Opera you can control widows and orphans, but it hasn't landed in WebKit yet, so for now you could use

p { page-break-inside: avoid;  } 

to avoid page breaks inside paragraphs.

You can even control margins for first, left and right pages separately.

Phantom's render() uses stylesheets for print media if the output is a pdf file. rasterize.js example looks like a ready to use printing solution.