【问题标题】:Fit content width-wise in pdf在 pdf 中按宽度调整内容
【发布时间】:2014-01-13 08:02:08
【问题描述】:

渲染为 pdf 时,我需要 html 页面为打印宽度的 100%。否则内容会被截断。有没有简单的方法可以做到这一点?

我想出了一个解决方法,它在渲染后获取 html 宽度,然后设置缩放因子以强制正确宽度。

var page = require('webpage').create(),
    system = require('system'),
    dpi = 89.9, // strange, but that's what I get on Mac
    pageWidth = 210; // in mm

var getWidth = function() {
    return page.evaluate(function() {
        // get width manually
        // ...
        return width;
    });
};

page.paperSize = {format: 'A4', orientation: 'portrait'};

page.open(system.args[1], function (status) {
    window.setTimeout(function () {
        page.zoomFactor = (pageWidth / 25.4) * dpi / getWidth();
        page.render(system.args[2]);
        phantom.exit();
    }, 200);
});

寻找一个直截了当的解决方案,因为由于我使用的框架,获得宽度需要我做一些技巧。

【问题讨论】:

  • 我使用了相同的解决方案,但无法找到替代方案。我正在使用 Windows,不得不将 dpi 硬编码为 120。我尝试了各种方法来获取 DPI,但是它们返回的 DPI 不起作用,例如GetDeviceCaps(IntPtr hDC, int nIndex) 返回 96。
  • 是的,有同样的事情。我实际上在 Linux 上使用 89.9 的 dpi 来填充页面而没有边距。

标签: pdf phantomjs


【解决方案1】:

如下编辑rasterize.js

备份 rasterize.js

删除此块(大约第 18-31 行)

if (system.args.length > 4) {
    page.zoomFactor = system.args[4];
}
page.open(address, function (status) {
    if (status !== 'success') {
        console.log('Unable to load the address!');
        phantom.exit();
    } else {
        window.setTimeout(function () {
            page.render(output);
            phantom.exit();
        }, 200);
    }
});

用这个代码块替换它

 if (system.args.length > 4) {
        page.zoomFactor = parseFloat(system.args[4].split("=")[1]);
 }
 page.open(address, function (status) {
        if (status !== 'success') {
            console.log('Unable to load the address!');
            phantom.exit(1);
        } else {
            window.setTimeout(function () {
console.log("zoomFactor: " + page.zoomFactor);
      page.evaluate(function(zoom) {
        return document.querySelector('body').style.zoom = zoom;
    }, page.zoomFactor); // <-- your zoom here
                page.render(output);
                phantom.exit();
            }, 200);
        }
    });

然后您可以像这样即时将 html 导出为 pdf:

~/bin/phantomjs ~/bin/phantomjs/examples/rasterize.js \ 
'http://example.com/index.html' \ 
mysite.pdf paperformat=A4 zoom=0.4

【讨论】:

    【解决方案2】:

    通过添加以下 CSS 规则来解决这个问题,该规则将缩小页面并使其适合:

     html {
        zoom: 0.60; 
      }
    

    【讨论】:

    • 这适用于除 css 边框之外的所有其他内容。
    猜你喜欢
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 2014-09-29
    • 2012-10-13
    • 2011-09-06
    • 2016-11-06
    • 1970-01-01
    相关资源
    最近更新 更多