【问题标题】:Node, phantomjs & converting html to pdf: element dimensions ignored?节点、phantomjs & 将 html 转换为 pdf:元素尺寸被忽略?
【发布时间】:2016-10-31 04:58:10
【问题描述】:

我想从 HTML 文档生成 PDF,其中 HTML 文档具有以厘米为单位指定尺寸的元素。这个想法是指定一个元素或图像以适应指定的页面。问题是我无法得到要尊重的维度。

这是我正在使用的测试 HTML:

<html>
<head>
   <title>test case</title>
</head>
<body>
     <div style="width: 21cm; height: 27cm; border: solid 1px black;">This should be within page bounds!?</div>
</body>
</html>

尝试使用 NodeJS 模块 'phantomjs-pdf' (0.1.2),我使用了以下代码:

var pdf = require('phantomjs-pdf');

var options = {
    "html" : "./test-data/document.html",
};

pdf.convert(options, function(result) {

    /* Using a buffer and callback */
    result.toBuffer(function(returnedBuffer) {});

    /* Using a readable stream */
    var stream = result.toStream();

    /* Using the temp file path */
    var tmpPath = result.getTmpPath();

    /* Using the file writer and callback */
    result.toFile("out.pdf", function() {});
});

输出文档为 21cm x 29.71.cm(美国信函)。

我尝试了另一个包 'html-pdf',它似乎也是基于 PhantomJS 并获得相同的行为,这表明问题可能与 PhantomJS 相关?

有什么建议吗?

在尊重元素尺寸的条件下,我愿意使用替代包从 HTML 转换为 PDF。这是因为我将使用图像作为背景(PNG 或 SVG,取决于支持),它表示预期的文档模板,然后将 HTML 元素放置在页面的给定部分中,基于在元素。

我使用的是 NodeJS 6.7.0、MacOS X 10.12,并且我通过 MacPorts 安装了 PhantomJS 2.0.0。

【问题讨论】:

  • div 不是像您的示例显示的那样在正文中吗?
  • @KevinBrown 只是问题中的复制/粘贴问题。修复了 HTML 示例。

标签: html node.js pdf phantomjs


【解决方案1】:

在发现https://github.com/fraserxu/electron-pdf 后,我放弃了 PhantomJS。到目前为止,它已经超出了预期。由于 Electron 运行 Chromium,printToPDF 功能的工作原理与您预期的差不多。您可以npm install electron-pdf 并使用 CLI 为您的应用程序评估它。由于您想要字母大小,请添加 -p Letter 并可能将边距设置为无。

在任何一种情况下,我都发现(浏览器)窗口大小(以像素为单位)需要与 PDF 大小相匹配。对于 Letter,这将是 (8.5" * 96) x (11" * 96) 96 是 HTML 的标准每英寸像素比率。如果您想以厘米为单位工作,请使用该比例。

【讨论】:

    猜你喜欢
    • 2014-06-17
    • 1970-01-01
    • 2021-12-31
    • 2020-10-25
    • 2011-07-15
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多