How to handle PDF pagination in PhantomJS

27,997

Solution 1

PhantomJS takes care of webkit’s css implementation. To implement manual page breaks you can use these properties :

  • page-break-before : auto/always/avoid/...
  • page-break-inside : auto/always/avoid/...
  • page-break-after : auto/always/avoid/...

For example, a div can be :

 <div style="page-break-before:always;"><!-- content --></div>

or

<div style="page-break-after:always;"> <!-- content --></div>

Controlling page breaks when printing in Webkit is sometimes not easy, in particular with long html tables.

Solution 2

Very late, but I had issues with "break-inside:avoid" using JsReport that were fixed by changing the element's display type to inline-block. More info here: https://github.com/ariya/phantomjs/issues/10638

Solution 3

You should see this issue with different tips.

Try to use display:inline-block in the element that you don't want to breaks because the page break. The reasoning behind is that webkit already tries to preserve images from breaking. And images are inline-blocks.

Solution 4

Pagination works fine with :

 var page = webPage.create();

 page.paperSize = {
  format: 'A4',
  orientation: 'portrait',
  margin: '1cm'
 }

Check documentation here http://phantomjs.org/api/webpage/property/paper-size.html

Share:
27,997
Rayjax
Author by

Rayjax

Updated on June 11, 2020

Comments

  • Rayjax
    Rayjax almost 4 years

    I am using PhantomJS to create PDFs from html.

    It works fine, but I can't find out how to work with pagination; I want to create a page for each div in my document, but I can't find anything in the doc. about pagination.

    If my document is short, it makes only one page, and if it is bigger, it creates one second empty page and my contents are in the first page which becomes very long.

    Any idea ? (I am using phantomJS-node module for nodeJS)