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.

JavaScript (v8.0+)

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

Prepare your JSON Data

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

JavaScript (v8.0+)

1WebViewer(...)
2 .then(instance => {
3 instance.UI.loadDocument('/files/quote.docx');
4
5 const { documentViewer } = instance.Core;
6
7 documentViewer.addEventListener('documentLoaded', async () => {
8 const doc = documentViewer.getDocument();
9
10 const keys = await doc.getTemplateKeys();
11 console.log(keys);
12 });
13 });

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

JavaScript (v8.0+)

1const jsonData = {
2 CompanyName: 'Apryse',
3 CustomerName: 'Andrey Safonov',
4 CompanyAddressLine1: '838 W Hastings St 5th floor',
5 CompanyAddressLine2: 'Vancouver, BC V6C 0A6',
6 CustomerAddressLine1: '123 Main Street',
7 CustomerAddressLine2: 'Vancouver, BC V6A 2S5',
8 Date: 'Nov 5th, 2021',
9 ExpiryDate: 'Dec 5th, 2021',
10 QuoteNumber: '134',
11 Website: 'apryse.com',
12 billed_items: {
13 insert_rows: [
14 ['Apples', '3', '$5.00', '$15.00'],
15 ['Oranges', '2', '$5.00', '$10.00'],
16 ],
17 },
18 days: '30',
19 total: '$25.00',
20 };

Merge JSON data into DOCX template

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

JavaScript (v8.0+)

1WebViewer(...)
2 .then(instance => {
3 instance.UI.loadDocument('/files/quote.docx');
4
5 const { documentViewer } = instance.Core;
6
7 documentViewer.addEventListener('documentLoaded', async () => {
8 const doc = documentViewer.getDocument();
9 await doc.applyTemplateValues(jsonData);
10 });
11 });

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales