简体   繁体   中英

Print PDF from HTML with complex CSS using html-pdf

I'm trying to print a PDF from an HTML markup using the html-pdf package and for some reason, the CSS is not being applied to the final document.

I'm trying to use a local CSS file and I use absolute path for it but it doesn't seem to show up.

Here is how I set the absolute css path in config.ts:

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",
    },
  },
}

And this is how I build the final markup that I'm trying print:


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

where joinedBodyContents is the main body markup.

Then I try to print it like this:

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

However, styling is not shown on the final PDF. If I open up the HTML file that I also generate that contains the finalBody as well, it does show the CSS styling so the path to the CSS file seems to be correct. Any ideas why this doesn't work on the final PDF?

use this maybe works

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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