Search code examples
javascriptnode.jspdfphantomjs

Phanomjs not properly capturing screenshot of a web page


I am testing phantom.js for creating screenshots from a web page at my local end.

This is how HTML is rendering in localhost - Output

But on creating PDF from code, width is not setting properly in PDF, i.e. some text gets cut as shown below.

Following is the code I tried -

var url = 'http://localhost:5656';
page.open(url);

page.onLoadFinished = function() {
    var pdfName = 'screen';
    page.render(pdfName + ".pdf");
    var height = page.evaluate(function() { return document.body.offsetHeight }),
        width = page.evaluate(function() { return document.body.offsetWidth });
    console.log(height,width);  
};

I also tried these two properties but getting same result -

page.clipRect = { top: 0, left: 0, right: 0, width: 1286};
page.viewportSize = { width: 1024, height: 768};

Let me know what I am doing wrong here.

Output I am getting - PDF image I am getting]2


Solution

  • Following is the working code:

    var url = 'http://localhost:5656';
    page.open(url);
    
    page.onLoadFinished = function() {
        //page.viewportSize = { width: 1400, height: 1200 };
        page.paperSize = {format: 'A4'};
        var pdfName = 'screen';
        page.render(pdfName + ".pdf");
        var height = page.evaluate(function() { return document.body.offsetHeight }),
            width = page.evaluate(function() { return document.body.offsetWidth });
        console.log(height,width);  
    };
    

    As you can see, following is the line that performed the magic for me -

    page.paperSize = {format: 'A4'};