Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to export json data to pdf file with specify format with Nodejs?

Tags:

json

node.js

pdf

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.

  1. Info

    1.1 Company

    ABC

    1.2 Team

    JsonNode

  2. Number of members 4
  3. 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!

like image 285
Toandd Avatar asked Oct 05 '15 04:10

Toandd


People also ask

How do I export JSON data from node JS?

nodejs-write-json-object-to-file.jsparse(jsonData); console. log(jsonObj); // stringify JSON Object var jsonContent = JSON. stringify(jsonObj); console. log(jsonContent); fs.


2 Answers

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.

like image 71
Mariya James Avatar answered Nov 03 '22 14:11

Mariya James


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.

like image 34
Akshay Kumar Avatar answered Nov 03 '22 15:11

Akshay Kumar