I'm using the Html-pdf package to generate and download pdf in an express-MongoDB application. Here is the route, where I've used the Html-pdf package.
//@route - GET /generate PDF
router.get("/generateReport/:id", async (req, res) => {
const tableDataById = await newsModel.findById(req.params.id);
ejs.renderFile(path.join(__dirname, '../views/pages/', "pdf.ejs"), {output:tableDataById}, (err, data) => {
if (err) {
res.send(err);
} else {
var assesPath = path.join('file://',__dirname,'../public/');
assesPath = assesPath.replace(new RegExp(/\\/g), '/');
var options = {
"height": "11.25in",
"width": "8.5in",
"header": {
"height": "20mm",
},
"footer": {
"height": "20mm",
},
"base": "file:///" + assesPath
};
pdf.create(data, options).toBuffer(function (err, buffer) {
if (err) {
res.send(err);
} else {
res.type('pdf');
res.end(buffer,'binary')
}
});
}
});
});
I've used ejs template engine. Here is the code of the "pdf.ejs" file which I rendered in the before mentioned route.
<div class="container">
<div class="row">
<div class="col-md-4">
<img class="card-img-top" src="<%= output.newspapers[0].logo %>">
<h1><%= output.newspapers[0].newsPaperName %></h1>
</div>
<div class="text-center">
<img class="img-fluid" id="test" src="<%= output.image %>" alt="">
</div>
</div>
</div>
Here is the screenshot of my application, which failed to render the dynamic image path
Image src needs absolute path for rendering dynamic image path from the ejs file that you want to generate as a pdf file.
inside your controller, instead of doing this:
ejs.renderFile(path.join(__dirname, '../views/pages/', "pdf.ejs"), {output:tableDataById}
Do this: send a variable that contains the absolute path
ejs.renderFile(path.join(__dirname, '../views/pages/', "pdf.ejs"), {output:tableDataById,dirname: __dirname}
and inside the ejs file instead of doing this :
<img class="img-fluid" id="test" src="<%= output.image %>" alt="">
Do this : add the variable dirname and go one step back to get the public path where you are saving your image
<img class="img-fluid" id="test" src="<%= dirname %>/../public/<%= output.image %>" alt="">
Hope this will help solving your problem. Happy coding !!