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?
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 };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With