Posted by Arjun on Wednesday 28th August 2019

Word document placeholder replacement with Node js

How to Node.js Word Document

In this post, we gonna see how we can use Docxtemplater library to replace placeholders in the Word Document in Node js based projects. 

Let's initialize the project with npm init --yes command.

<code>$ mkdir node-demo
$ cd node-demo
$ npm init --yes</code>

Now install the Docxtemplater the module as shown below:

<code>$ npm install docxtemplater pizzip</code>

Now create a file called processWordDoc.js and place the following code.

<code>var PizZip = require('pizzip');
var Docxtemplater = require('docxtemplater');

var fs = require('fs');
var path = require('path');

//Load the docx file as a binary
var content = fs
    .readFileSync(path.resolve(__dirname, 'AGREEMENT.DOCX'), 'binary');

var zip = new PizZip(content);

var doc = new Docxtemplater();

//set the templateVariables
    first_name: 'John',
    last_name: 'Doe',
    phone: '0652455478',
    description: 'New Website'

try {
    // render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
catch (error) {
    var e = {
        message: error.message,
        stack: error.stack,
    console.log(JSON.stringify({error: e}));
    // The error thrown here contains additional information when logged with JSON.stringify (it contains a property object).
    throw error;

var buf = doc.getZip()
             .generate({type: 'nodebuffer'});

// buf is a nodejs buffer, you can either write it to a file or do anything else with it.
fs.writeFileSync(path.resolve(__dirname, 'output.docx'), buf);</code>

Now execute the code with node processWordDoc.js command, it will generate a new word document called output.docx in the project folder.