Templates allow you to generate dynamic documents from pre-designed .docx layouts by replacing placeholder tags with content using patchDocument.
Workflow
- Create a Template: Open a Word processor and create a
.docx file using double curly braces {{placeholder_name}} for your tags. - Define Patches: Use the
patchDocument function to map your placeholder names to new content. - Export: Run the patcher to produce the modified document.
Basic Usage Example
import * as fs from "fs";
import { patchDocument, PatchType, TextRun } from "docx";
patchDocument({
outputType: "nodebuffer",
data: fs.readFileSync("template.docx"),
patches: {
customer_name: {
type: PatchType.PARAGRAPH,
children: [new TextRun("John Smith")],
},
order_number: {
type: PatchType.PARAGRAPH,
children: [new TextRun("12345")],
},
},
}).then((doc) => {
fs.writeFileSync("output.docx", doc);
});
import * as fs from "fs";
import { patchDocument, PatchType, TextRun } from "docx";
patchDocument({
outputType: "nodebuffer",
data: fs.readFileSync("template.docx"),
patches: {
customer_name: {
type: PatchType.PARAGRAPH,
children: [new TextRun("John Smith")],
},
order_number: {
type: PatchType.PARAGRAPH,
children: [new TextRun("12345")],
},
},
}).then((doc) => {
fs.writeFileSync("output.docx", doc);
});