Generate a PDF Containing Variable Data in JavaScript

When generating a PDF, it may not be possible to foresee all of its contents ahead of time. For that reason, we advise using a templating language such as Mustache.

Templating languages allow for the injection of data at runtime. In regard to the PDF Generation feature, this means it gives you the possibility to customize HTML before sending it along for generation. Injecting data can be useful in situations such as name and date replacement, or when generating dynamic lists in invoices.

In this guide, you’ll take the letter example from the Creating a PDF from Scratch guide and implement date and name replacement with the use of Mustache in JavaScript. (Note {{name}} and {{date}} in the following HTML):

<!DOCTYPE html>
<head>
  ...
</head>
<html>
  <body>
    <div class="address">
      John Smith<br/>
      123 Smith Street<br/>
      90568 TA<br/>
      <br/>
      {{date}}
    </div>
    <div class="subject">Subject: PDF Generation FTW!</div>
    <div>
      <p>
        ...
      </p>
    </div>
    <div>{{name}}<br/></div>
  </body>
</html>

Next, the data for {{name}} and {{date}} needs to be defined. In practice, this data may come from an external source or database, but for this example, you’ll define the data in a JSON file:

{
  "name": "John Smith Jr.",
  "date": "29 February, 2020"
}

Now, run the mustache command to produce a final HTML document with the template arguments replaced:

const mustache = require("mustache");
const fs = require("fs");

const page = fs.readFileSync("page.mustache").toString();
const data = JSON.parse(fs.readFileSync("data.json").toString());

const outputHTML = mustache.render(page, data);

Run the JavaScript with Node.js:

node mustache-example.js

This example shows how you can use Mustache.js, although it’s worth noting that there are many other templating language alternatives that may better suit your environment.