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.
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
That
href
shouldn't work in a browser either; either use a relative path or prependfile:///
– user5734311 Commented Jul 14, 2020 at 7:56
3 Answers
Reset to default 3I'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.
Waiting for css/js dependencies to load first seem to solve it.
await page.setContent(html, { waitUntil: 'load' });
If you are adding style using page.addStyleTag make sure to add it after page.setContent. Since setContent writes the whole html instead of just body the styling gets overwritten. Use like this:
await page.setContent(htmlToSend, { waitUntil: 'domcontentloaded' });
await page.addStyleTag({ path: 'templates/report.css' })