Converting JSON to HTML and using the html and convert it to PDF

Home / Uncategorized / Converting JSON to HTML and using the html and convert it to PDF

Question:
I have to convert JSON data into HTML and then convert that HTML to PDF. I know how to convert json to html and i know how to convert HTML to PDF. I want to know How can i integrate both of those into one. How do i send the var html into the fs.readfile ?

JSON to HTML :
var json2html = require(‘node-json2html’);

var data = [{‘male’:’Bob’,’female’:’Jane’},{‘male’:’Rick’,’female’:’Ann’}];

var transform = {"<>":"div","html":"${male} likes ${female}"};

var html = json2html.transform(data,transform);

HTML to PDF:’use strict’;
var http = require(‘http’);
var fs = require(‘fs’);
var pdf = require(‘html-pdf’);

http.createServer(function (req, res) {

fs.readFile(‘./PDF.html’, ‘utf8’, function (err, html) {
if (err) {
//error handling
}
pdf.create(html).toStream(function (err, stream) {
if (err) {
//error handling
}
res.writeHead(200, {
‘Content-Type’: ‘application/force-download’,
‘Content-disposition’: ‘attachment; filename=file.pdf’
});
stream.pipe(res);
});
});
}).listen(8080, ‘127.0.0.1’);
console.log(‘Server running at http://127.0.0.1:8080/’);

How do i combine both of these so that when i give json it downloads PDF file. When i give HTML in the fs.readFile(html) it throwing an error.
AssertionError: html-pdf: Can’t create a pdf without an html string
at new PDF (C:Usersvijaynode_moduleshtml-pdflibpdf.js:39:3)
at Object.createPdf [as create] (C:Usersvijaynode_moduleshtml-pdflibindex.js:6:14)
at ReadFileContext.callback (C:Usersvijayhtml-to-pdfTestapp.js:20:13)
at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:359:13)


Answer:

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *