A fast and lightweight Node.js library written in TypeScript for merging two Microsoft Word (.docx) documents into one. Easily insert content at specific positions or based on placeholder patterns.
Install via npm:
npm install @benedicte/docx-mergeOnly two lightweight dependencies:
adm-zip– for extracting and rebuilding .docx (ZIP) filesfast-xml-parser– for parsing and modifying the DOCX XML content
mergeDocx(
sourcePathOrBuffer: string | Buffer,
contentPathOrBuffer: string | Buffer,
options: {
outputPath?: string;
pattern?: string;
insertStart?: boolean;
insertEnd?: boolean;
}
): void | bufferParameters:
sourcePathOrBuffer(required) – Path to the base.docxfile or the BuffercontentPathOrBuffer(required) – Path to the.docxfile to insert into the base or the Bufferoptions:outputPath– If provided, writes the merged document to this path. If omitted, returns aBufferpattern– String pattern in the source file to replace with the inserted contentinsertStart– Insert the content at the beginning of the source fileinsertEnd– Insert the content at the end of the source file
🔔 Note: You can combine pattern, insertStart, and insertEnd and at least one is required.
import { mergeDocx } from "@benedicte/docx-merge";
mergeDocx("./source.docx", "./table.docx", {
outputPath: "./output.docx",
pattern: "{{table}}",
});import { mergeDocx } from "@benedicte/docx-merge";
const buffer = mergeDocx("./source.docx", "./table.docx", {
pattern: "{{table}}",
});
// Use buffer (e.g., send as a response in a server)import { mergeDocx } from "@benedicte/docx-merge";
const sourceBuffer = readFileSync('./source_file.docx');
const contentBuffer = readFileSync('./content_to_insert_in_source_file.docx');
const buffer = mergeDocx(sourceBuffer, contentBuffer, {
outputPath: "./output.docx",
pattern: "{{table}}",
});import { mergeDocx } from "@benedicte/docx-merge";
mergeDocx("./source.docx", "./table.docx", {
outputPath: "./output.docx",
insertStart: true,
});import { mergeDocx } from "@benedicte/docx-merge";
mergeDocx("./source.docx", "./table.docx", {
outputPath: "./output.docx",
insertEnd: true,
});This project uses Vitest for unit testing.
To run tests:
npm run testMIT
Contributions, bug reports, and feature requests are welcome! Feel free to open an issue or submit a pull request.