Generate word documents(.docx) from a template using Node.js

  1. Install Dependencies
  2. Create a template DOCX file
  3. Write the Node.js code

To generate a .docx file based on a template docx file using Node.js, I would recommend the docxtemplater library, which allows you to fill in placeholders in a DOCX template.

Install Dependencies

We need to install docxtemplater and pizzip packages. docxtemplater is used to handle the DOCX tempalte, pizzip is used to handle ZIP archives(which DOCX files are).

1
npm install docxtemplater pizzip

Create a template DOCX file

Create a DOCX template with placeholders. For example, create a file named template.docx with placeholders like {name} and {date}. You can use Microsoft Word or Google Docs to create this template.

Write the Node.js code

Here is an example of how to generate a DOCX file based on the template:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
const fs = require("fs");
const path = require("path");
const PizZip = require("pizzip");
const Docxtemplater = require("docxtemplater");

// Function to generate DOCX file based on the template
function generateDocx(data, templatePath, outputPath) {
// Read the template file
const templateContent = fs.readFileSync(templatePath, "binary");

// Load the template content into PizZip
const zip = new PizZip(templateContent);

// Create a Docxtemplater instance
const doc = new Docxtemplater(zip, { paragraphLoop: true, linebreaks: true });

// Set the data for placeholders
doc.setData(data);

try {
// Render the document with the data
doc.render();

// Get the generated document as a buffer
const buf = doc.getZip().generate({ type: "nodebuffer" });

// Write the buffer to a file
fs.writeFileSync(outputPath, buf);
console.log(`Document generated: ${outputPath}`);
} catch (error) {
console.error("Error generating document:", error);
}
}

// Example data to replace in the template
const data = {
name: "John Doe",
date: "August 8, 2024",
};

// Paths to the template and output files
const templatePath = path.join(__dirname, "template.docx");
const outputPath = path.join(__dirname, "generated.docx");

// Generate the DOCX file
generateDocx(data, templatePath, outputPath);