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
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!
nodejs-write-json-object-to-file.jsparse(jsonData); console. log(jsonObj); // stringify JSON Object var jsonContent = JSON. stringify(jsonObj); console. log(jsonContent); fs.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With