使用Express html-pdf包时图像不是从动态图像路径渲染的 [英] Image is not rendering from dynamic image path while using express html-pdf package
问题描述
我正在使用Html-pdf软件包在Express-MongoDB应用程序中生成和下载pdf。这是我使用Html-pdf软件包的路线。
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')
}
});
}
});
});
我使用过ejs模板引擎。这是 pdf.ejs的代码。
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>
在这里,我还提供了示例JSON数据的屏幕截图,其中包含了图像的路径
推荐答案
Image src需要绝对路径,以便从要生成为pdf文件的ejs文件中呈现动态图像路径。
Image src needs absolute path for rendering dynamic image path from the ejs file that you want to generate as a pdf file.
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}
而不是在ejs文件中:
and inside the ejs file instead of doing this :
<img class="img-fluid" id="test" src="<%= output.image %>" alt="">
执行以下操作:添加变量 dirname 并返回上一步,以获取保存图像的公共路径
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 !!
这篇关于使用Express html-pdf包时图像不是从动态图像路径渲染的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!