Some test text!

Search
Hamburger Icon

Web / Guides / Generate DOCX template

Generate DOCX/Word Template with JSON Data using JavaScript

WebViewer allows you to generate PDFs from DOCX, XLSX, or PPTX templates. Templates can be created in any application, and replaceable content is defined with {{ curly brackets. The data can be merged from any data source in JSON format. Conversion from MS Office template, data merging is happening client-side without any server-side dependencies.

You can watch the video below that walks you through it or check out this branch of our React sample for a full sample.

Load a DOCX template

Template can be DOCX, XLSX, or PPTX format with {{placeholders}} defined. Placeholders will preserve their original styling and can be replaced with text, images, or tabular data. The content will automatically reflow based on content length and paginate accordingly.

WebViewer(...)
  .then(instance => {
    instance.UI.loadDocument('/files/quote.docx');
  });

Prepare your JSON Data

The placeholders can be automatically detected with API to get the template keys.

WebViewer(...)
  .then(instance => {
    instance.UI.loadDocument('/files/quote.docx');

    const { documentViewer } = instance.Core;

    documentViewer.addEventListener('documentLoaded', async () => {
        const doc = documentViewer.getDocument();

        const keys = await doc.getTemplateKeys();
        console.log(keys);
    });
  });

Here is a sample of the JSON data complete with table data to insert rows.

const jsonData = {
    CompanyName: 'Apryse',
    CustomerName: 'Andrey Safonov',
    CompanyAddressLine1: '838 W Hastings St 5th floor',
    CompanyAddressLine2: 'Vancouver, BC V6C 0A6',
    CustomerAddressLine1: '123 Main Street',
    CustomerAddressLine2: 'Vancouver, BC V6A 2S5',
    Date: 'Nov 5th, 2021',
    ExpiryDate: 'Dec 5th, 2021',
    QuoteNumber: '134',
    Website: 'apryse.com',
    billed_items: {
      insert_rows: [
        ['Apples', '3', '$5.00', '$15.00'],
        ['Oranges', '2', '$5.00', '$10.00'],
      ],
    },
    days: '30',
    total: '$25.00',
  };

Merge JSON data into DOCX template

After the data is prepared, it is now ready to be merged.

WebViewer(...)
  .then(instance => {
    instance.UI.loadDocument('/files/quote.docx');

    const { documentViewer } = instance.Core;

    documentViewer.addEventListener('documentLoaded', async () => {
        const doc = documentViewer.getDocument();
        await doc.applyTemplateValues(jsonData);
    });
  });

Trial setup questions? Ask experts on Discord
Need other help? Contact Support
Pricing or product questions? Contact Sales