繁体   English   中英

使用 html-pdf 从带有复杂 CSS 的 HTML 打印 PDF

[英]Print PDF from HTML with complex CSS using html-pdf

我正在尝试使用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?

使用这个可能有效

 <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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM