【问题标题】:Eliminate margins while rendering a pdf with phantomJS使用 phantomJS 渲染 pdf 时消除边距
【发布时间】:2016-07-25 07:08:30
【问题描述】:

我正在使用 PhantomJS 将带有 D3 图表的 html 网页呈现为 PDF 报告。在对 rasterize.js 进行一些更改后,该报告看起来几乎完美。但是,无论我进行什么更改,我都无法完全消除左右边距。有人可以建议对 raterize.js 进行任何修改以完全删除这些边距。我对文件的更改如下:-

page.viewportSize = { width: 595, height: 842 };   //**A4**
    if (system.args.length > 3 && system.args[2].substr(-4) === ".pdf") {
    size = system.args[3].split('*');
    page.paperSize = size.length === 2 ? { width: size[0], height: size[1], margin: '-150px' }
                                       : { format: system.args[3], orientation: 'portrait', margin: '-4cm' }; //**Swapnil:- added a negative margin to utilize the entire width of the canvas. (Reduces the margins but does not eliminate them completely)**
} else if (system.args.length > 3 && system.args[3].substr(-2) === "px") {
    size = system.args[3].split('*');
    if (size.length === 2) {
        pageWidth = parseInt(size[0], 10);
        pageHeight = parseInt(size[1], 10);
        page.viewportSize = { width: pageWidth, height: pageHeight };
        page.clipRect = { top: 0, left: 0, width: pageWidth, height: pageHeight };
    } else {
        console.log("size:", system.args[3]);
        pageWidth = parseInt(system.args[3], 10);
        pageHeight = parseInt(pageWidth * 3/4, 10); // it's as good an assumption as any
        console.log ("pageHeight:",pageHeight);
        page.viewportSize = { width: pageWidth, height: pageHeight };
    }
}
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(1);
    } else {
        window.setTimeout(function () {
            page.render(output);
            phantom.exit();
        }, 20000);  // **Swapnil:- increased time out to ensure all the charts load perfectly**
    }
});

谢谢!

【问题讨论】:

    标签: javascript html pdf d3.js phantomjs


    【解决方案1】:

    首先将边距设置为0:

    page.paperSize = {
        // ...
        margin: { top: 0, right: 0, bottom: 0, left: 0 }
    };
    

    接下来,您需要确保 pdf 页面大小与您的内容的大小完全一致。你可以这样做......

    ...通过根据渲染页面的宽度(以像素为单位)设置宽度(手动计算您使用的任何格式的高度)并根据 dpi 的潜在差异进行调整

    ...通过调整缩放直到页面完全适合。

    这两种方式都有很多摆弄。 Phantomjs 可以完美渲染页面,但并不容易。

    【讨论】:

    • 请您解释一下如何设置宽度或调整缩放比例。因为我非常努力地动态找到页面的宽度,因为内容宽度每次都会变化
    猜你喜欢
    • 2014-11-17
    • 2016-11-21
    • 2023-04-03
    • 2018-02-16
    • 2014-01-31
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    相关资源
    最近更新 更多