Edit Word Documents using a REST API in Node js

Edit Word Documents using a REST API in Node js
Editing or modifying .docx files programmatically can be a crucial part of automating workflows in Node.js applications. Whether you're generating dynamic reports, creating customized documents, or automating repetitive tasks, manipulating .docx files can save time and reduce errors. In this blog, we'll walk through how to edit a .docx file in Node.js using the docxtemplater library.
Prerequisites
Before we get started, make sure you have Node.js installed on your system. You’ll also need the following npm packages:
docxtemplaterpizzipmomentfs
You can install these packages using the following command:
npm install docxtemplater pizzip moment fsStep-by-Step Guide
1. Setting Up Your Project
Create a new directory for your project and navigate into it:
mkdir docx-editor
cd docx-editorInitialize a new Node.js project:
npm init -y2. Installing Dependencies
Install the necessary packages:
npm install docxtemplater pizzip moment fs3. Writing the Code
Create a new file, editDocx.js, and open it in your favorite code editor. Here's a complete script to edit a .docx file:
const fs = require('fs');
const PizZip = require('pizzip');
const Docxtemplater = require('docxtemplater');
const moment = require('moment');
// File paths
const inputFilePath = "./files/hrms/ConfirmationLetter.docx";
const outputFilePath = "./files/temp/DUMMY_ConfirmationLetter.docx";
// Load the content of the .docx file
const content = fs.readFileSync(inputFilePath, "binary");
const zip = new PizZip(content);
const doc = new Docxtemplater(zip);
// Dummy data for replacements
let replacements = {
DATE: moment().format("DD-MMM-YYYY"), // e.g., "25-Jul-2024"
NT: "Mr.", // Assuming male employee for the dummy data
EmployeeName: "John Doe",
Designation: "Software Engineer",
Department: "IT",
REF: "REF123456",
HNo: "123",
Village: "Sample Village",
City: "Sample City",
District: "Sample District",
State: "Sample State",
Pincode: "123456",
DOJ: moment(2024-01-25,"YYYY-MM-DD").format("DD-MMM-YYYY"), // Assuming the date of joining is 25-Jan-2024
};
// Set the template variables
doc.setData(replacements);
try {
// Render the document
doc.render();
// Generate the output file
const buffer = doc.getZip().generate({ type: "nodebuffer" });
// Save the modified document
fs.writeFileSync(outputFilePath, buffer);
console.log("Text replaced successfully. Output saved to", outputFilePath);
} catch (error) {
console.error("An error occurred:", error);
}Explanation
- Loading the File: The
fs.readFileSyncmethod loads the content of the.docxfile into memory. - Parsing the File:
PizZipparses the binary content of the file, andDocxtemplaterallows us to modify it. - Defining Replacements: We create a
replacementsobject containing key-value pairs where keys are placeholders in the.docxtemplate, and values are the dynamic content. - Setting Data: The
doc.setData(replacements)method sets the dynamic data in the template. - Rendering and Saving: The
doc.render()method generates the modified document, which is then saved usingfs.writeFileSync.
Conclusion
By following these steps, you can easily edit or modify .docx files in your Node.js applications. This method is especially useful for generating dynamic documents such as confirmation letters, invoices, and reports. Make sure to handle errors and edge cases appropriately to ensure your application runs smoothly.
If you have any questions or run into issues, feel free to leave a comment below. Happy coding!