html-pdf with ejs template

7.4k views Asked by At

In my application, when a user passes a test, there will automatically be generated a diploma (pdf). This I accomplish by using the html-pdf node-module, which retrieves the html file and makes it into a pdf.

var fs = require('fs'),
    pdf = require('html-pdf'),
    path = require('path'),
    ejs = require('ejs');


var html = fs.readFileSync('./phantomScripts/certificate.html', 'utf8');
var options = { filename: 'businesscard.pdf', format: 'A4', orientation: 'portrait', directory: './phantomScripts/',type: "pdf" };

pdf.create(html, options).toFile(function(err, res) {
    if (err) return console.log(err);
         console.log(res);
    });

This conversion, from html to pdf, works perfectly and looks really good. Now what I want is to make the template a little bit more dynamic, meaning that depending on the user, their name appears in the pdf.

I have work once with ejs to generate an email template, so I was thinking that my problem could be solved with that, but as mentioned I'm haven't work that much with ejs and can't figure out how to send data into my ejs file?

1

There are 1 answers

3
Backer On
ejs.renderFile('./path/to/template-file.ejs', {data : {firstname: 'Tom', lastname: 'Hanks'}, function(err, result) {
    // render on success
    if (result) {
       html = result;
    }
    // render or error
    else {
       res.end('An error occurred');
       console.log(err);
    }
});

I replaced my var html = fs.readFileSync('./phantomScripts/certificate.html', 'utf8'); code with the above code, and it works as I want it to.