Generate PDFs from a Word Template Using JavaScript

PSPDFKit for Web offers the ability to populate DOCX templates with data. PSPDFKit for Web can be run headlessly for automated generation, or with the document viewer user interface (UI).

Launch Demo

Setting the Data Configuration to Populate a Document

To set this mechanism into motion, you’ll need two primary components:

  1. The MS Office DOCX template.

  2. The specific data you wish to input.

Perform the dynamic population using the PSPDFKit#populateDocumentTemplate() API method. Here’s an example:

PSPDFKit.populateDocumentTemplate(
  {
    document: "/path-to-your-MS-Office-template.docx",
    licenseKey: "YOUR_LICENSE_KEY"
  },
  {
    config: {
      delimiter: {
        start: "{{",
        end: "}}"
      }
    },
    model: {
      ...YourDynamicDataHere
    }
  }
);

PSPDFKit.populateDocumentTemplate() takes two arguments:

  1. An object containing the path to the MS Office DOCX template, along with your PSPDFKit license key, or no license key if you’re testing in trial mode.

  2. An object containing the configuration and the data to populate the template.

The configuration object contains the delimiter that will be used to identify the dynamic data in the template. The delimiter configuration allows PSPDFKit to identify placeholders within the MS Office DOCX template. In this instance, placeholders are text segments encapsulated between {{ and }}.

The model object contains the data that will be used to populate the template, and its keys must match the placeholders in the template.

For example, if you have a placeholder in the template that looks like {{customerName}}, then the model object must include a key named customerName.

Advanced Template Features

Currently, PSPDFKit offers two fundamental template features — placeholders and loops.

  1. Placeholders are markers to be replaced with text. For instance, a placeholder like {{name}} in your DOCX can be dynamically filled with an individual’s name.

  2. Loops are useful for generating repetitive sections, especially for elements like lists or tables. Consider this DOCX segment:

"model": {
   "items": [{"name": "Product A", "price": "$10"},
             {"name": "Product B", "price": "$15"}]
}

The generated document would automatically list both products with their respective prices.