PhantomJs - How to render a multi page PDF

2019-03-26 14:44发布

问题:

I can create one-page PDFs with phantomJS; but I can't find on the doc how to create different pages (each page coming from an html view) and put them into one PDF ? I am using node-phantom module for NodeJS

回答1:

Just need to specify a paperSize.

Like this with module "phantom": "0.5.1"

function(next) {
    phantom.create(function(doc) {
        next(null, doc);
    }, "phantomjs", Math.floor(Math.random()*(65535-49152+1)+49152));
},
function(ph, next) {
    ph.createPage(function(doc) {
        next(null, doc);
    });
},
function(page, next) {
    page.set('paperSize', {format: 'A4', orientation: 'portrait'});
    page.set('zoomFactor', 1);
}

Then, simply use page-break-before: always; in your HTML content each time you want to open a new page.

PS: I use async.waterfall in this example

PPS: Math.random on port number is used to avoid module crash if concurrent calls to phantom binary are triggered. Works fine - if someone wants to post something better even if a bit off-topic, feel free to do it