I'm generating a pdf from an html sample with puppeteer and handlebars. Everything works good except an image is shown in the browser (headless mode) but when pdf is generated the image disappear. I don't know why this happens.
It's weird because I'm not getting any error, the image (logo) just doesn't appear, just does in the browser view.
I'm calling the image through a external link in the img label in sample.html.
I leave you my code
file.json
const puppeteer = require("puppeteer");
const hbs = require("handlebars");
const path = require("path");
const fs = require("fs-extra");
const data = {
date: sale.transaction.createdAt,
time: sale.transaction.createdAt,
raffleDate: sale.transaction.createdAt,
description:
"Zapatos NikeZapatos NikeZapatos NikeZapatos NikeZapatos NikeZapatos NikeZapatos NikeZapatos NikeZapatos Nike",
"name-customer": sale.transaction.customer.firstName,
"lastname-customer": sale.transaction.customer.lastName,
"raffle-code": raffleId,
tickets: ticks,
quantity: tickets.length,
total: sale.transaction.amount,
};
const compile = async (templateName, data) => {
const filePath = path.join(
process.cwd(),
`./controllers/sample-email/${templateName}.html`
);
const html = await fs.readFileSync(filePath, "utf-8");
return hbs.compile(html)(data);
};
(async () => {
try {
const browser = await puppeteer.launch({
headless: false,
});
const page = await browser.newPage();
const content = await compile("sample", data);
await page.setContent(content, { waitUntil: "domcontentloaded" });
await page.addStyleTag({
path: "./controllers/sample-email/sample.css",
});
await page.emulateMediaType("screen");
await page.pdf({
path: "./controllers/sample-email/sample.pdf",
format: "A4",
printBackground: true,
});
} catch (error) {
console.log(error);
}
})();
sample.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="/controllers/sample-email/sample.css" />
<title>Invoice</title>
</head>
<body>
<header>
<section class="logo">
<img src="https://res.cloudinary.com/baltasar-montero-vidaurreta-175/image/upload/v1687201343/algira/thumbnails/ALGIRA.webp"
alt="algira"
/>
</section>
</header>
</body>
</html>
I think the problem is here:
{ waitUntil: "domcontentloaded" }
Per MDN:
The DOMContentLoaded event fires when the HTML document has been completely parsed, and all deferred scripts ( and ) have downloaded and executed. It doesn't wait for other things like images, subframes, and async scripts to finish loading.
It would be better to wait for load
or networkidle0
.