问题
I am a beginner with nodejs. And I am writing a program, which convert text data from json file to pdf file: This is my input file (input.json)
{
"Info":
{
"Company": "ABC",
"Team": "JsonNode"
},
"Number of members": 4,
"Time to finish": "1 day"
}
And I want to convert it to a .pdf (report.pdf) file with following style.
Info
1.1 Company
ABC
1.2 Team
JsonNode
- Number of members 4
- Time to finish 1 day
My problems are:
1: How to change style from input.json file to style of report.pdf.
2: How to convert from .json format to .pdf format.
Could anyone help me.
Thanks in advance!
回答1:
I think you have to make html template and then render your json into html template.
<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>
Now On your js file you have to give path of your template and also create a folder in order to store your pdf file.
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)
});
}
})
})
}
Try with this hope it works.
回答2:
You have to create the layout using 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>
Now you have to store this html in a variable say "layout". Then create the pdf as,
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"
});
}
Where file is the path where you want to save your file.
回答3:
There are many solutions saying first convert into html and then to pdf but instead one can directly generate pdf using "pdfmake" or "pdfkit" library. I've used it and its very good library. pdfkit is the parent library over which pdfmake has been made. pdfmake is very simple library compared to pdfkit (this is what I feel). pdfmake lacks some features like bookmarks and toc(table of content header) linkage to respective page.
pdfmake: https://pdfmake.github.io/docs/
pdfkit: http://pdfkit.org/docs/getting_started.html
来源:https://stackoverflow.com/questions/32941366/how-to-export-json-data-to-pdf-file-with-specify-format-with-nodejs