jsonnode.jspdf

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


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!


Solution

  • 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.