【问题标题】:Print PDF from HTML with complex CSS using html-pdf使用 html-pdf 从具有复杂 CSS 的 HTML 打印 PDF
【发布时间】:2021-12-14 11:21:01
【问题描述】:

我正在尝试使用 html-pdf 包从 HTML 标记打印 PDF,但由于某种原因,CSS 未应用于最终文档。

我正在尝试使用本地 CSS 文件,并且我使用了绝对路径,但它似乎没有显示出来。

这是我在 config.ts 中设置绝对 css 路径的方法:

export const config: any = {
  development: {
    css: {
     defaultDocumentStyle: "file:///home/user/work/printing/src/styles/defaultStyling.css",
    },
    templates: {
      defaultDocHeader: "file:///home/user/work/printing/src/templates/defaultDocHeader.html",
      defaultDocFooter: "file:///home/user/work/printing/src/templates/defaultDocFooter.html",
    },
  },
}

这就是我构建我正在尝试打印的最终标记的方式:


const cssFile = config.css.defaultDocumentStyle
const finalBody = `
<html>
<head>
<link rel="stylesheet" href="${cssFile}" type="text/css">
</head>
<body>${joinedBodyContents}</body>
</html>
        `

其中joinedBodyContents 是主体标记。

然后我尝试这样打印:

const options = {
    format: "A4",
    timeout: 30000,
    type: "pdf",
    orientation: "portrait",
    border: {
      right: "1in",
      left: "1in",
    },
    header: {
      height: "20mm",
      contents: header,
    },
    footer: {
      height: "20mm",
      contents: footer,
    },
  }

  pdf.create(finalBody, options).toFile("out/finalPDF.pdf", function (err: Error, res: any) {
    if (err) return console.log(err)
    console.log(res)
  })

但是,最终 PDF 中未显示样式。如果我打开我还生成的包含 finalBody 的 HTML 文件,它确实显示了 CSS 样式,因此 CSS 文件的路径似乎是正确的。任何想法为什么这不适用于最终的 PDF?

【问题讨论】:

    标签: javascript typescript pdf-generation html-pdf node-html-pdf


    【解决方案1】:

    使用这个可能有效

    <html>
    <body>
    <style>
    h2[c]{
    color:red;
    }
    </style>
    <h2 c>The window.print() Method</h2>
    
    <p>Click the button to print the current page.</p>
    
    <button onclick="window.print()">Print this page</button>
    
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 2021-03-19
      • 2015-07-05
      • 1970-01-01
      • 2011-05-26
      • 2023-03-09
      • 2015-01-30
      • 2013-02-16
      • 1970-01-01
      • 2014-04-04
      相关资源
      最近更新 更多