Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While rendering webpage to pdf using phantomjs, how can I auto adjust my viewportSize to take full page width?

I am able to specify the page size correctly using the params as below:

var page = require('webpage').create();
page.paperSize = { format: 'Letter,  orientation: 'Portrait'};

The challenge that I am facing is that, I cannot get my web page to take the full width of the paper.

This is how I can set the viewport size:

page.viewportSize = { width: mybestfitwidth, height: mybestfitheight };

The challenge here is that I cannot figure out what mybestfitwidth should be. I can tell the width of my pdf page in inches, but I can't figure out what number of pixels would that be, because that depends on the dpi settings. I don't know what dpi settings phantomjs would use or how to modify it.

In conclusion, I just need my page to print nicely and take full width of my pdf page. Is there any way I can achieve this?

like image 480
dreamerkumar Avatar asked Feb 25 '14 14:02

dreamerkumar


1 Answers

Here is a well tested solution that I came up with today:

var pageSize = "A4",
    pageOrientation = "portrait",
    dpi = 150, //from experimenting with different combinations of viewportSize and paperSize the pixels per inch comes out to be 150
    pdfViewportWidth = 1024,
    pdfViewportHeight = 768,
    cmToInchFactor = 0.393701,
    widthInInches,
    heightInInches,
    temp;

    switch(pageSize){
        case 'Letter':
        default:
            widthInInches = 8.5;
            heightInInches = 11;
            break;
        case 'Legal':
            widthInInches = 8.5;
            heightInInches = 14;
            break;
        case 'A3':
            widthInInches = 11.69
            heightInInches = 16.54;
            break;
        case 'A4':
            widthInInches = 8.27;
            heightInInches = 11.69;
            break;
        case 'A5':
            widthInInches = 5.83;
            heightInInches = 8.27;
            break;
        case 'Tabloid':
            widthInInches = 11;
            heightInInches = 17;
            break;
    }

    //reduce by the margin (assuming 1cm margin on each side)
    widthInInches-= 2*cmToInchFactor;
    heightInInches-= 2*cmToInchFactor;

    //interchange if width is equal to height
    if(pageOrientation === 'Landscape'){
        temp = widthInInches;
        widthInInches = heightInInches;
        heightInInches = temp;
    }

    //calculate corresponding viewport dimension in pixels
    pdfViewportWidth = dpi*widthInInches;
    pdfViewportHeight = dpi*heightInInches;

    page = require('webpage').create();
    page.paperSize = {  format: pageSize,  orientation: pageOrientation, margin: '1cm' };
    page.viewportSize = { width: pdfViewportWidth, height: pdfViewportHeight }; 
like image 116
dreamerkumar Avatar answered Oct 21 '22 21:10

dreamerkumar