How to handle PDF pagination in PhantomJS

2019-03-12 00:40发布

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)

4条回答
乱世女痞
2楼-- · 2019-03-12 01:00

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.

查看更多
倾城 Initia
3楼-- · 2019-03-12 01:08

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

查看更多
Fickle 薄情
4楼-- · 2019-03-12 01:10

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

查看更多
孤傲高冷的网名
5楼-- · 2019-03-12 01:11

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.

查看更多
登录 后发表回答