Issue
I'm trying to generate a PDF using Puppeteer and Handlebars inside a Electron app. But the images are not showing in the .PDF file, I tried to debug using headless mode, but did not find nothing usefull.
My folder structure is:
+-- pdf_template
| +-- generatePDF.js
| +-- template.html
| +-- template.css
| +-- logo.png
| +-- bg.png
generatePDF.js :
try {
(async () => {
var dataBinding = {
total: 123456,
};
var templateHtml = fs.readFileSync(
path.join(
process.cwd(),
'/app/pages/pdf_template/template.html'
),
'utf-8'
);
var template = handlebars.compile(templateHtml);
var finalHtml = template(dataBinding);
var options = {
path: 'report.pdf',
printBackground: true,
format: 'A4',
};
const browser = await puppeteer.launch({
args: ['--no-sandbox'],
headless: true,
});
const page = await browser.newPage();
await page.goto(
`data:text/html;charset=UTF-8,${encodeURIComponent(finalHtml)}`,
{
waitUntil: ['domcontentloaded', 'networkidle0', 'load', 'networkidle2'],
}
);
await page.addStyleTag({
path: __dirname + '/node_modules/bootstrap/dist/css/bootstrap.min.css',
});
await page.addStyleTag({
path: __dirname + '/app/pages/pdf_template/template.css',
});
await page.emulateMedia('screen');
await page.pdf(options);
await browser.close();
console.log('Done: PDF is created!');
})();
} catch (err) {
console.log('ERROR:', err);
}
template.html:
<!DOCTYPE html>
<html>
<head>
<mate charest="utf-8" />
<title>Report</title>
</head>
<body>
<div class="row" id="header">
<div class="col" id="logo-box">
<img
src="logo.png"
id="logo"
/>
</div>
<div class="col-8">
...
</div>
...
</body>
</html>
template.css
body {
background-image: url('bg.png');
background-size: cover;
width: 21cm;
height: 29.7cm;
padding: 15mm;
margin: 0;
}
Both images from HTML and CSS are not showing. Am I missing something?
Solution
An answer can be found here : How to point Puppeteer to local images/fonts?
It seems as the generated page URL is about:blank
chromium does not allow local resources to be loaded for safety reasons. I managed to bypass this problem by including the binaries of the images in my HTML template as :
//In CSS
background-image: url("data:image/png;base64,BINARY_CHUNKS");
//In HTML
<img src="data:image/png;base64,BINARY_CHUNKS" class="logo">
As for getting a local file in binary I would suggest fs
:
fs.readFileSync(`${process.cwd()}\\your_image_path.png`).toString('base64')
Hope someone found that usefull !
Answered By - Chalibou
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.