【问题标题】:While rendering webpage to pdf using phantomjs, how can I auto adjust my viewportSize to take full page width?使用 phantomjs 将网页呈现为 pdf 时,如何自动调整 viewportSize 以占据整个页面宽度?
【发布时间】:2014-02-25 14:52:30
【问题描述】:

我可以使用以下参数正确指定页面大小:

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

我面临的挑战是,我无法让我的网页占据纸张的整个宽度。

这就是我可以设置视口大小的方法:

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

这里的挑战是我无法弄清楚 mybestfitwidth 应该是什么。我可以以英寸为单位说出我的 pdf 页面的宽度,但我不知道那是多少像素,因为这取决于 dpi 设置。我不知道 phantomjs 会使用什么 dpi 设置或如何修改它。

总之,我只需要很好地打印我的页面并占据我的 pdf 页面的整个宽度。有什么办法可以实现吗?

【问题讨论】:

  • 我认为 dpi phantomjs 使用的这篇帖子的提示是 72 github.com/ariya/phantomjs/issues/10659
  • 这真的很有趣..当我使用最新的 phantomjs 构建运行一些测试时,我将 dpi 默认设置为 150

标签: javascript phantomjs


【解决方案1】:

这是我今天提出的一个经过良好测试的解决方案:

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 }; 

【讨论】:

  • 你在更高分辨率的屏幕上测试过这个吗?我的 3200x1800 以 pdf 大小的 1/4 创建内容...
  • 不要以为我做到了。但是,如果您还没有这样做,请在具有该分辨率的浏览器上测试您的应用程序。可能只是您的应用程序本身在该分辨率下呈现不正确。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-05
  • 1970-01-01
  • 2020-06-17
  • 2022-08-24
  • 1970-01-01
  • 2013-06-17
  • 1970-01-01
相关资源
最近更新 更多