Last updated on November 8, 2019
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.
$ mkdir node-demo
$ cd node-demo
$ npm init --yes
Now install the Docxtemplater the module as shown below:
$ npm install docxtemplater pizzip
Now create a file called processWordDoc.js
and place the following 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();
doc.loadZip(zip);
//set the templateVariables
doc.setData({
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, ...)
doc.render()
}
catch (error) {
var e = {
message: error.message,
name: error.name,
stack: error.stack,
properties: error.properties,
}
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);
Now execute the code with node processWordDoc.js
command, it will generate a new word document called output.docx
in the project folder.