I have successfully implemented handlebars with puppeteer to generate a PDF server-side and save it in my database. However, I am facing an issue with loading images stored in an assets directory through the img tag.
In my index.js file, I have a helper called img_picker which should return the path of the image based on the image name input. Below is my pdfGenerator function that takes a template.hbs file and utilizes puppeteer to generate the PDF:
const puppeteer = require("puppeteer");
const hbs = require("handlebars");
const fs = require("fs-extra");
const path = require("path");
// Compiles the Handlebars docs
const compile = async (templateName, data) => {
const filePath = path.join(
process.cwd(),
`${templateName}.hbs`
);
const html = await fs.readFile(filePath, "utf-8");
return hbs.compile(html)(data);
};
hbs.registerHelper('img_picker', context => {
console.log('IMAGE PATH: ', path.join(__dirname, 'server', 'reports', 'assets', `${context}@3x.png`))
return path.join(__dirname, 'server', 'reports', 'assets', `${context}@3x.png`)
})
// Uses Puppeteer to take compiled HBS doc and create a PDF
const generatePDF = async (fileName, data) => {
const browser = await puppeteer.launch({ args: ["--no-sandbox"], headless: true });
const page = await browser.newPage();
const content = await compile(fileName, data);
await page.setContent(content);
await page.emulateMedia("screen");
const pdf = await page.pdf({
format: "A4",
printBackground: true
});
return pdf;
};
// Runs generator function generatePDF('template', {wedge: "Delivery"});
In my HBS file, I am attempting to use the image by referencing wedge.name as a string with the image name that is being iterated over in the data:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img src="{{{img_picker wedge.name}}}" style="width: 70px;height:70px" />
</body>
</html>
I have seen examples using app.use(express.static()) for serving static files, but I'm unsure how to implement it in this scenario since the image path is dynamic based on the template.
package.json
"main": "index.js",
"dependencies": {
"express": "^4.17.1",
"fs-extra": "^8.1.0",
"handlebars": "^4.7.3",
"puppeteer": "^2.1.1",
}