【问题标题】:What CSS should I write in html template to generate a pdf of a particular height & width我应该在 html 模板中编写什么 CSS 来生成特定高度和宽度的 pdf
【发布时间】:2021-08-24 14:58:31
【问题描述】:

我正在使用带有 pdf-creator-node 的 nodejs 生成 PDF,并且成功了。 我的要求是我需要生成一个高度 X 宽度 = 926px X 1296px 的 PDF。 我不知道我应该写什么 css 来生成这个维度 pdf。 现在,如果我使用上述尺寸设置 div 或 body 高度和 widht,我将获得 3 页

这是我尝试过的

@page {
        width: 1296px;
        height: 926px;
      }
 <div
      class="parent-div"
      style="
        width: 1296px;
        height: 926px;
        background-color: #faf0e6;
        border: 1px solid red;
      "
    ></div>

【问题讨论】:

    标签: css node.js pdf height width


    【解决方案1】:

    jsPDF 可以使用插件。为了使它能够打印 HTML,您必须包含某些插件,因此必须执行以下操作:

    1. 转到https://github.com/MrRio/jsPDF 并下载最新的 版本。

    2. 在您的项目中包含以下脚本:

      jspdf.js jspdf.plugin.from_html.js jspdf.plugin.split_text_to_size.js jspdf.plugin.standard_fonts_metrics.js

    如果你想忽略某些元素,你必须用一个 ID 标记它们,然后你可以在 jsPDF 的特殊元素处理程序中忽略它。因此,您的 HTML 应如下所示:

    <!DOCTYPE html>
    <html>
    <body>
    <p id="ignorePDF">don't print this to pdf</p>
    <div>
      <p><font size="3" color="red">print this to pdf</font></p>
    </div>
    </body>
    </html>
    

    然后您使用以下 JavaScript 代码在弹出窗口中打开创建的 PDF:

    var doc = new jsPDF();          
    var elementHandler = {
    #ignorePDF': function (element, renderer) {
    return true;
    }
    };
    var source = window.document.getElementsByTagName("body")[0];
    doc.fromHTML(
    source,
    15,
    15,
    {
      'width': 180,'elementHandlers': elementHandler
    });
    
    doc.output("dataurlnewwindow");
    

    **对我来说,这创建了一个漂亮而整洁的 PDF,其中仅包含“将其打印为 pdf”这一行。

    请注意,特殊元素处理程序仅处理当前版本中的 ID,这也在 GitHub 问题中说明。它指出:**

    因为匹配是针对节点树中的每个元素完成的,所以我的愿望是让它尽可能快。在这种情况下,它意味着“仅匹配元素 ID”。元素 ID 仍然以 jQuery 样式“#id”完成,但并不意味着支持所有 jQuery 选择器。

    因此,用“.ignorePDF”之类的类选择器替换“#ignorePDF”对我来说不起作用。相反,您必须为每个要忽略的元素添加相同的处理程序,例如:

    var elementHandler = {
    #ignoreElement': function (element, renderer) {
    return true;
    },
    #anotherIdToBeIgnored': function (element, renderer) {
    return true;
    }
    };
    

    从示例中还指出,可以选择“a”或“li”等标签。不过,对于大多数用例来说,这可能有点过于无限制:

    我们支持特殊的元素处理程序。使用 jQuery 样式的 ID 选择器为 ID 或节点名称注册它们。 (“#iAmID”、“div”、“span”等)目前不支持任何其他类型的选择器(复合的类)。

    要添加的一件非常重要的事情是您丢失了所有样式信息 (CSS)。幸运的是,jsPDF 能够很好地格式化 h1、h2、h3 等,这对我的目的来说已经足够了。此外,它只会打印文本节点内的文本,这意味着它不会打印 textareas 等的值。示例:

    <body>
    <ul>
    <!-- This is printed as the element contains a textnode -->        
    <li>Print me!</li>
    </ul>
    <div>
    <!-- This is not printed because jsPDF doesn't deal with the value attribute -->
    <input type="textarea" value="Please print me, too!">
    </div>
    </body>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-17
      • 2018-04-25
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      相关资源
      最近更新 更多