如何在节点js中使用pdfkit将ejs文件数据打印到pdf文件?
How to print ejs file data to pdf file using pdfkit in node js?
这是我的 result.ejs 文件代码:
<div style="width: 50%; margin: auto;">
<table class="table">
<thead>
<tr>
<th>SUBJECT</th>
<th>MARKS OBTAINED</th>
</tr>
</thead>
<tbody>
<tr>
<th>pHYSICS</th>
<td>80</td>
</tr>
<tr>
<th>Chemistry</th>
<td>80</td>
</tr>
<tr>
<th>mathematics</th>
<td>80</td>
</tr>
<tr>
<th>computer</th>
<td>80</td>
</tr>
</tbody>
</table>
</div>
在我的 user.js 中,我正在渲染 ejs 文件:
router.get("/result",async(req,res)=>{
res.render("result");
})
我了解有关 pdfkit 的基础知识。但我只用它来打印 pdf 格式的文本,如下所示:
const PDFDocument = require('pdfkit');
const fs = require('fs');
const doc = new PDFDocument();
doc.pipe(fs.createWriteStream('output.pdf'));
doc
.fontSize(25)
.text('Some text with an embedded font!', 100, 100);
但现在我需要以 pdf 格式打印 ejs 文件 table 数据。请帮我找出答案。谢谢。
是的,你可以做到这一点。首先,您需要渲染文件,然后将其传递给 pdf。您只需要先将您的 ejs 模板化,然后将模板字符串传递给文件名 xyz.pdf
,您就可以在 pdf 中看到模板化的 ejs。
// render the ejs file
ejs.renderFile(path.join(__dirname, 'path-to-your-ejs'), data, {}, function(err, str) {
if (err) return res.send(err);
// str now contains your rendered html
//your pdf object should be used here
pdf.create(str).toFile("name of the file", function(err, data) {
if (err) return res.send(err);
res.send("File created successfully");
});
});
参考自 link,查看 link 了解更多信息。
这是我的 result.ejs 文件代码:
<div style="width: 50%; margin: auto;">
<table class="table">
<thead>
<tr>
<th>SUBJECT</th>
<th>MARKS OBTAINED</th>
</tr>
</thead>
<tbody>
<tr>
<th>pHYSICS</th>
<td>80</td>
</tr>
<tr>
<th>Chemistry</th>
<td>80</td>
</tr>
<tr>
<th>mathematics</th>
<td>80</td>
</tr>
<tr>
<th>computer</th>
<td>80</td>
</tr>
</tbody>
</table>
</div>
在我的 user.js 中,我正在渲染 ejs 文件:
router.get("/result",async(req,res)=>{
res.render("result");
})
我了解有关 pdfkit 的基础知识。但我只用它来打印 pdf 格式的文本,如下所示:
const PDFDocument = require('pdfkit');
const fs = require('fs');
const doc = new PDFDocument();
doc.pipe(fs.createWriteStream('output.pdf'));
doc
.fontSize(25)
.text('Some text with an embedded font!', 100, 100);
但现在我需要以 pdf 格式打印 ejs 文件 table 数据。请帮我找出答案。谢谢。
是的,你可以做到这一点。首先,您需要渲染文件,然后将其传递给 pdf。您只需要先将您的 ejs 模板化,然后将模板字符串传递给文件名 xyz.pdf
,您就可以在 pdf 中看到模板化的 ejs。
// render the ejs file
ejs.renderFile(path.join(__dirname, 'path-to-your-ejs'), data, {}, function(err, str) {
if (err) return res.send(err);
// str now contains your rendered html
//your pdf object should be used here
pdf.create(str).toFile("name of the file", function(err, data) {
if (err) return res.send(err);
res.send("File created successfully");
});
});
参考自