How to export json data to pdf file with format using Nodejs?

I start with nodejs. And I am writing a program that converts text data from a json file to a 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 file (report.pdf) with the following style.

  • Information

    1.1 Company

    Abc

    1.2 Team

    Jsonnode

  • Number of participants 4
  • Completion time 1 day

My problems:

1: How to change the style from input.json file to report.pdf style.

2: How to convert from .json to .pdf format.

Can anyone help me out.

Thanks in advance!

+7
source share
3 answers

I think you need to create an html template and then make your json in an 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 in your js file you need to specify the path to your template, as well as create a folder for storing your file in pdf format.

  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 the hope that this will work.

+6
source

You need to create a 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 need to save this html in a variable, for example "layout". Then create 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 the file.

+2
source

There are many solutions that say that you first need to convert to html and then to pdf, but instead, you can directly generate pdf using the pdfmake or pdfkit library. I used it and its a very good library. pdfkit is the parent library over which pdfmake was created. pdfmake is a very simple library compared to pdfkit (this is what I feel). Pdfmake lacks some features, such as bookmarks and toc (content table header) for the corresponding page.

pdfmake : https://pdfmake.imtqy.com/docs/

pdfkit : http://pdfkit.org/docs/getting_started.html

0
source

Source: https://habr.com/ru/post/1232927/


All Articles