Puppeteer HTML to PDF is not applying external css files

Viewed 2405

I am using Puppeteer in node.js to convert an html string to a pdf file. Styles inside the head are working but those linked from local .css files with absolute path are not. Here is the code:

createPDF: async (html, file) => {
     const browser = await puppeteer.launch({
          headless: true
     })
     const page = await browser.newPage()
     await page.setContent(html, {
          waitUntil: 'domcontentloaded'
     })
     await page.pdf({
          format: 'A4',
          path: file,
          printBackground: true
     })
     await browser.close()
}

The head of the html looks like this:

<link href="C:\dev\project\src\views\tailwind.min.css" rel="stylesheet">
<style>
     .maindiv{
          padding-top:15pt;
     }
</style>

I also tried using a url instead but nothing changed.

1 Answers

I'm not sure you've already solved the above issue. I had the same issue when including a JS file into the HTML template. I solved the issue by adding await page.addScriptTag({path: './ej2.min.js'}) before page.setContent(). No need to add the script tag to the HTML page. To include style file following method addStyleTag('file-name-goes-here') can be use. For the file path use the relative path from the base project directory.

Related