This User's route with Puppeteer code:
Router.get('/generate_invoice', (req, res) => {
const userData = req.session.user;
res.render("./patientpanel/invoice", { user: userData });
(async () => {
// launch a new chrome instance
const browser = await puppeteer.launch({
headless: true
});
const page = await browser.newPage();
const filePathName = path.resolve(__dirname, '../views/patientpanel/invoice.ejs');
const html = fs.readFileSync(filePathName, 'utf8')
await page.goto("http://localhost:5000/generate_invoice" + html);
await page.setContent(html, {
waitUntil: 'domcontentloaded'
});
const pdfBuffer = await page.pdf({
format: 'A4'
});
// or a .pdf file
await page.pdf({ path: "./user.pdf", format: pdfBuffer });
await browser.close()
})();
});
The PDF file generated successfully but it shows the EJS template as it is without any proper format and data which I rendered through the above router.
The EJS template code:
<tr class="information">
<td colspan="2">
<table>
<tr>
<td>
Name: <%- user.firstname %>
<%- user.lastname %><br />
Email: <%- user.email %><br />
Mobile No. : <%- user.mob %>
</td>
</tr>
</table>
</td>
</tr>
setContent
, literally. If you want to process that text as EJS, run EJS on it and pass in the user data. Hint:const rendered = require("ejs").render(html)
, thensetContent(rendered)
. BTW,readFileSync
is not a good thing to put into a request handler--it'll slow your app down, preventing the main thread from handling other requests as it waits for the kernel. It's already anasync
func so useawait fs.promises.readFile
. β Sucyrender
call in your code.const rendered = require("ejs").render(html, {user: userData})
should work. You're confusingres.render
which renders EJS as the body of a HTTP response with running EJS to process HTML for PDF purposes without sending a response. Probably remove yourres.render("./patientpanel/invoice", { user: userData });
line, because that sends a response right away rather than waiting for the PDF to render. You probably want to run Puppeteer to make the PDF, screenshot it, then send that as the response withres.sendFile()
. β Sucy