-->

Node-phantom show number of generated pdf pages

2020-07-27 02:39发布

问题:

I am facing problem to get the number of generated pdf pages in phantomjs. Basically I am using phantomjs with nodejs and I want to show total number of pages in page 5.

function generatePdf() {

    // Load ejs template
    fs.readFile(__dirname + '/../pdf' + pdfpath, 'utf8', function (err, data) {
        var fileName = __dirname + '/pdfdata/' + f.formType + f.formId + '.pdf';
        // Render the page to variable.
        var html = ejs.render(data, pdfJSON);
        fs.writeFile(__dirname + '/pdfdata/test.html', html, function (err) {
            if (err) throw err;
        });
        // Set this html as the content for the pdf file.
        page.set('content', html);
        //page.set( 'paperSize', { width: 1200, height: 1500} );
        page.set('paperSize', {
            //format: 'A4',
            width: 1200,
            height: 1600,
            header: {
                height: "1cm",
                contents: "function(pageNum, numPages) { return '<h6 style=text-align:right></h6>'; }"
            },
            footer: {
                height: "1cm",

                contents: "function(pageNum, numPages) { return '<h6 style=text-align:right;margin-right:60px;postion:absolute;margin-bottom:-20px>' + pageNum + '</h6>'; }"
            }
        }, function () {
            page.open(__dirname + '/pdfdata/test.html', function () {
                page.render(fileName, cb);
                ph.exit();
                // Response to client.
                function cb() {
                    res.jsonp(200, responseJSON);
                }
            })
        });
    });
} // end of function

For showing of pages I have add in generatePdf function

contents: "function(pageNum, numPages) { return '<h6 style=text-align:right;margin-right:60px;postion:absolute;margin-bottom:-20px>' + pageNum + '</h6>'; }" 

and also add this to bridge.js

case 'pageSet':
    eval('request[4].header.contents = phantom.callback(' + request[4].header.contents + ')');
    eval('request[4].footer.contents = phantom.callback(' + request[4].footer.contents + ')');
    page[request[3]] = request[4];
    respond([id, cmdId, 'pageSetDone']);
    break;

How can I show the number of generated pages inside a specific page.

回答1:

Why not checkin in the footer content which page you are, and then display NumPages. Something like this:

contents: "function(pageNum, numPages) { 
              if(pageNum === numPages)
                return '<h6>' + numPages + '</h6>'; 
              else
                return '<h6>' + pageNum + '</h6>'; 
}"