我是nodejs的初学者。我正在编写一个程序,它将文本数据从json文件转换为pdf文件: 这是我的输入文件(input.json)
{
"Info":
{
"Company": "ABC",
"Team": "JsonNode"
},
"Number of members": 4,
"Time to finish": "1 day"
}
我想将其转换为具有以下样式的.pdf(report.pdf)文件。
信息
1.1公司
ABC
1.2团队
JsonNode
我的问题是:
1:如何将input.json文件的样式更改为report.pdf样式。
2:如何将.json格式转换为.pdf格式。
任何人都可以帮助我。
提前致谢!
答案 0 :(得分:6)
我认为你必须制作html模板,然后将你的json渲染成html模板。
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<table>
<tr>Company</tr>
{{info.Company}}
<tr>Team</tr>
{{info.Team}}
</table>
</body>
</html>
现在在您的js文件中,您必须提供模板的路径,并创建一个文件夹以存储您的pdf文件。
var pdf = require('html-pdf');
var options = {format: 'Letter'};
exports.Topdf = function (req, res) {
var info = {
"Company": "ABC",
"Team": "JsonNode",
"Number of members": 4,
"Time to finish": "1 day"
}
res.render('path to your tempalate', {
info: info,
}, function (err, HTML) {
pdf.create(HTML, options).toFile('./downloads/employee.pdf', function (err, result) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
}
})
})
}
尝试这个希望它有效。
答案 1 :(得分:2)
您必须使用html as
创建布局<ul>
<li>Info: </li>
<ul>
<li>Company: {{info.Company}}</li>
<li>Team: {{info.Team}}</li>
</ul>
<li>Number of members: {{info.numberofmembers}}</li>
<li>Time to finish: {{info.timetofinish}}</li>
<ul>
现在你必须将这个html存储在一个变量中,说“布局”。 然后创建pdf,
function generatePdf(layout, file) {
console.log('generating pdf');
var wkhtmltopdf = require('wkhtmltopdf');
wkhtmltopdf(html, {
output: file,
"viewport-size": "1280x1024",
"page-width": "400",
"page-height": "600"
});
}
其中file是您要保存文件的路径。
答案 2 :(得分:0)
有许多解决方案,它们说先转换为html,然后转换为pdf,但是可以使用“ pdfmake”或“ pdfkit”库直接生成pdf。我已经使用了它及其非常好的库。 pdfkit是制作pdfmake的父库。 与pdfkit相比,pdfmake是一个非常简单的库(这就是我的感觉)。 pdfmake 缺少一些功能,例如书签和与各自页面的toc(内容标题表)链接。
pdfmake :https://pdfmake.github.io/docs/