Type Here to Get Search Results !

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…

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:

  • docxtemplater
  • pizzip
  • moment
  • fs

You can install these packages using the following command:

npm install docxtemplater pizzip moment fs

Step-by-Step Guide

1. Setting Up Your Project

Create a new directory for your project and navigate into it:

mkdir docx-editor
cd docx-editor

Initialize a new Node.js project:

npm init -y

2. Installing Dependencies

Install the necessary packages:

npm install docxtemplater pizzip moment fs

3. 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.readFileSync method loads the content of the .docx file into memory.
  • Parsing the File: PizZip parses the binary content of the file, and Docxtemplater allows us to modify it.
  • Defining Replacements: We create a replacements object containing key-value pairs where keys are placeholders in the .docx template, 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 using fs.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!

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Top Post Ad

Below Post Ad