I'm using handlebars with puppeteer to generate a pdf server side and storing it into my db. This is all working but I can't seem to get the images that I have stored in an assets directory to load through my img tag.
I have a helper in my index.js called img_picker which takes in the name of the image and should return the path of the image. below is my pdfGenerator function that takes in the template.hbs file and generates the pdf with puppeteer.
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`)
})
// use puppeteer to take in compiled hbs doc and create a pdf
// remember to set the contentType to application/pdf when sending response to client
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 trying to use it like this with wedge.name being a string with the name of the image that I am iterating over in the data.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img src="{{{img_picker wedge.name}}}" style="width: 70px;height:70px" />
</body>
</html>
I've seen the examples calling for using app.use(express.static()) but not sure how I would use it in this way since I'm not hard coding the image that I'll be using in my template.
package.json
"main": "index.js",
"dependencies": {
"express": "^4.17.1",
"fs-extra": "^8.1.0",
"handlebars": "^4.7.3",
"puppeteer": "^2.1.1",
}