Plasmic
Plasmic

Reputation: 65

Render HTML to PDF with PhantomJS on DOMContentLoaded/Document Ready

I'm new to phantomjs and am having problems with rendering my website as PDF. I can get a simple render of the page however when loading multiple images/(web)fonts the DOM is not done loading when phantomjs renders the page.

Code:

page.open(address, function(status) {
    if(status !== 'success') {
        console.log('open page: '+address+' failed..');
        phantom.exit(0);
    }
});

page.onLoadFinished = function(status){
    if(status !== 'success'){
        console.log('load did not finish correctly');
        phantom.exit(0);
    } else {
        setTimeout(function() {
            page.render("../path", {format: 'pdf', quality: '100'});
            console.log('pdf generated successfully');
            phantom.exit(0);
        }, 5000);
    }
};

the code is working, i just want to wait for the DOMContentLoaded.

What i tried without success

based on a solution to wait for the dom to load found here

page.onInitialized = function() {
  page.evaluate(function(domContentLoadedMsg) {
    document.addEventListener('DOMContentLoaded', function() {
      window.callPhantom('DOMContentLoaded');
    }, false);
  });
};

page.onCallback = function(data) {
    page.render("../path", {format: 'pdf', quality: '100'});
    phantom.exit(0);
};

page.open(address, function(status) {
     if(status !== 'success') {
         console.log('open page: '+address+' failed..');
         phantom.exit(0);
     }
 });

This will render a black 1kb pdf so for some reason i'm unable to call the page.render function within an page.evaluate callback.

Cause i would like to include webfonts i'm running a custom build of phantomjs

any suggestions are welcome!

Thanks

Upvotes: 0

Views: 1797

Answers (1)

Artjom B.
Artjom B.

Reputation: 61892

Don't wait for DOMContentLoaded because WebFonts are not part of the DOM and are loaded later. Instead use window.onload = function(){ ... };.

page.evaluate(function() {
    window.onload = function() {
        window.callPhantom('window loaded');
    };
});

Also phantomjs 1.9.7 has support for WebFonts. You don't need to patch and compile anymore.

Upvotes: 0

Related Questions