我可以使用params正确指定页面大小,如下所示:
var page = require('webpage').create();
page.paperSize = { format: 'Letter, orientation: 'Portrait'};
我面临的挑战是,我无法让我的网页占据论文的全部宽度。
这是我设置视口大小的方法:
page.viewportSize = { width: mybestfitwidth, height: mybestfitheight };
这里的挑战是我无法弄清楚mybestfitwidth应该是什么。我可以用英寸来表示我的pdf页面的宽度,但我无法确定它的像素数,因为这取决于dpi设置。我不知道phantomjs将使用什么dpi设置或如何修改它。
总之,我只需要我的页面打印得很好并占据我的pdf页面的全部宽度。有什么方法可以实现这个目标吗?
答案 0 :(得分:5)
这是我今天提出的经过良好测试的解决方案:
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 };