Manuel Rivera Manuel Rivera - 1 year ago 99
Node.js Question

node express how to render handlebars html page to file

I want to convert some html page to pdf via wkhtmltopdf. However, the html page I want to convert to pdf is dynamically generated using handlebars.

So I think one solution maybe to generate the html page via handlebars but to a file (html file). Then, convert that file to pdf using hkhtmltopdf, then allow the user to, somehow, download the pdf.

So, my question is: how can I render the (handlebars) dynamically generated html page to a file?

Thanks and bye ...

Answer Source

Simple example for create file.

var Handlebars = require('handlebars');

var source = "<p>Hello, my name is {{name}}. I am from {{hometown}}. I have " +
    "{{kids.length}} kids:</p>" +
    "<ul>{{#kids}}<li>{{name}} is {{age}}</li>{{/kids}}</ul>";
var template = Handlebars.compile(source);

var data = { "name": "Alan", "hometown": "Somewhere, TX",
    "kids": [{"name": "Jimmy", "age": "12"}, {"name": "Sally", "age": "4"}]};
var result = template(data);

var fs = require('fs');
    fs.writeFile("test.html", result, function(err) {
    if(err) {
        return console.log(err);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download