Make PhantomJS wait for full page load before rendering in PDF

We cron a phantomjs rasterize.js http://website.com filename.pdf

that stopped working (pure PDFs) when the website got more "fancy". If I change it to filename.png it works.

I tried changing this timeout to 9999 in rasterize and I still get an empty PDF. By default, rasterize.js worked before switching website.

Any ideas what needs to be changed / added to the rasterized to get it working again?

page.open(address, function (status) {
    if (status !== 'success') {
        console.log('Unable to load the address!');
        phantom.exit();
    } else {
        window.setTimeout(function () {
            page.render(output);
            phantom.exit();
        }, 9999);
});

      

+3


source to share


1 answer


I had problems with this about a year ago. For me (if I remember correctly) it has to do with @media tags. (Again, if I remember correctly) Pdfs are generated with media print css, while pngs are not. Try what happens when you remove all @media print css.

EDIT 23/9/2014

I don't know how problematic this is for you (how much effort you want to put into it), but if it were me, I would first try something like this:



var page = require('webpage').create();
var args = require('system').args;

var output_file = args[1], url =args[2];

page.viewportSize = { width: 1440, height: 900 };
page.paperSize = {
   format: "A4",
   orientation: "landscape",
   margin: { left: "1cm", right: "1cm", top: "1cm", bottom: "1cm" }
};

console.log(url);

page.onLoadFinished = function (status) {
    window.setTimeout(function () {
        try {
            page.evaluate(function () {
                jQuery("link").each(function (i, v) {
                    jQuery(v).attr("media", "all");
                });
            });
            page.render(output_file);
        }
        catch (e) {
            status = e.message;
        }
        console.log(status + ';;' + output_file);
        phantom.exit();
    }, 1000);
}

try {
    page.open(url);
    console.log('loading');
}
catch (ex) {
    console.log(ex.message);
    phantom.exit();
}

      

Offcourse, whatever you do in the evaluation function depends on the content of the HTML file.

A somewhat more drastic way of telling what goes wrong is to register the source of what is being loaded with console.log(page.content);

, and then use that to see what goes wrong. (just copy this source to test.html file and look in browser, remember links (offcourse) will be broken)

+2


source







All Articles