Err
Err

Reputation: 920

Render HTML with variable data and convert to PDF

I have a html template page that I want to fill in data with via EJS, after which I want to pass this completed page to a PDF creator; the end result being a nice PDF version of my page filled with my data.

For the PDF creator, I'm using the NPM html-pdf do the conversion. Problem is, I don't know of any way I can render the page with my data, save it automatically, then pass the finished page to the PDF creator, since the PDF creator only accepts server paths to saved webpages.

Maybe I'm approaching this the wrong way, but below is what I currently have which admittedly isn't a lot. Any help in the right direction would be appreciated.

var renderPDF = function() {
  var pdf = require('html-pdf');
  // pulls html page
  var html = fs.readFileSync('views/assets/html/render.ejs', 'utf8');
  var options = {};
  // creates views/test.pdf
  pdf.create(html, options).toFile('views/test.pdf', function(err, res) {
    if (err) return console.log(err);
    console.log(res);
  });
};
// this is how I usually render ejs files with data
response.render('assets/html/render.ejs', {myDataOject});
// start the conversion
renderPDF();

Upvotes: 3

Views: 4194

Answers (1)

Natsathorn
Natsathorn

Reputation: 1528

Here is the solution. We read EJS's template file then compile it to PDF format.

index.js

var fs = require('fs');
var ejs = require('ejs');
var pdf = require('html-pdf')
var compiled = ejs.compile(fs.readFileSync(__dirname + '/template.html', 'utf8'));
var html = compiled({ title : 'EJS', text : 'Hello, World!' });

pdf.create(html).toFile('./result.pdf',() => {
    console.log('pdf done')
})

template.html

<html>
<head>
    <title><%= title %></title>
</head>
<body>
    <p><%= text %></p>
</body>

Upvotes: 5

Related Questions