Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 712
Err Avatar asked Feb 11 '26 12:02

Err


1 Answers

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>

like image 107
Natsathorn Avatar answered Feb 17 '26 09:02

Natsathorn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!