* feat: live examples in the docs, which run, draw the document next to the code, and can be edited and downloaded The docs' code examples were plain snippets, often fragments that couldn't run. A code block marked ```ts live is now an example readers can see and change: the page runs it with docx, draws the document it makes next to the code with docx-preview, and offers the .docx to download. Clicking the code opens an editor (Monaco) that knows docx's types, the pages are drawn again as the code changes, and View closes the editor. Split, Code and Preview show the code and the pages side by side, or one of them. The demos a page includes are live too. Every example in the docs that builds or patches a document is now live: 443 of them, each a whole file with its imports, so it runs as written. Code about other things, such as installing, bundlers or servers, stays plain. Running them showed docs that were wrong, fixed here: - Landscape: docx swaps a landscape page's width and height itself, so the docs' swapped sizes made a tall page marked as landscape - Comments: `comments.children` takes plain objects, not `new Comment(...)` - Custom properties are text only - APIs that no longer exist: MathText, Row, `.then` on Packer.toStream, patchDocument(buffer, ...), createParagraph().heading1(), a border's `value`, TextRun's `.break()` - The templates and patcher examples read files that aren't in the repository. They now patch the templates in demo/assets, or make their own `npm run build.docs` copies docx's browser builds into docs/live-examples/lib, so the docs use the docx they describe, and the Pages workflow runs it. The folder is gitignored, and cspell and ESLint skip it. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TmyffPd5QMJYjXiMBQ3EnZ * docs: the bullet examples draw a bullet, and the patcher's usage writes the patched document "ὠ" is U+1F60, a Greek omega, since \u takes four hex digits, so the two live bullet examples on the numbering page drew it as each item's bullet. They use "•" now. The patcher's usage example now awaits patchDocument and writes the document it makes, as the example after it does. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TmyffPd5QMJYjXiMBQ3EnZ --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
11 KiB
Templates
Templates allow you to modify existing Word documents by replacing placeholder text with dynamic content. This is useful for generating documents from pre-designed layouts.
!> For detailed information on the patchDocument function, see the Patcher guide.
Overview
The template workflow consists of:
- Create a Word document (.docx) with placeholder tags like
{{placeholder}} - Use
patchDocumentto replace the placeholders with content - Export the modified document
Creating a Template
Open your Word processor and create a document with placeholders:
Dear {{customer_name}},
Thank you for your order #{{order_number}}.
Your items will ship on {{ship_date}}.
Best regards,
{{company_name}}
?> Use double curly braces {{}} for placeholders. These will be replaced at runtime.
Basic Usage
import * as fs from "fs";
import { Document, Packer, Paragraph, patchDocument, PatchType, TextRun } from "docx";
// The template, made here as it would be in Word
const template = new Document({
sections: [
{
children: [
new Paragraph("Dear {{customer_name}},"),
new Paragraph("Thank you for your order #{{order_number}}."),
new Paragraph("Your items will ship on {{ship_date}}."),
new Paragraph("Best regards,"),
new Paragraph("{{company_name}}"),
],
},
],
});
const doc = await patchDocument({
outputType: "nodebuffer",
data: await Packer.toBuffer(template), // or fs.readFileSync("template.docx")
patches: {
customer_name: {
type: PatchType.PARAGRAPH,
children: [new TextRun("John Smith")],
},
order_number: {
type: PatchType.PARAGRAPH,
children: [new TextRun("12345")],
},
ship_date: {
type: PatchType.PARAGRAPH,
children: [new TextRun("January 15, 2024")],
},
company_name: {
type: PatchType.PARAGRAPH,
children: [new TextRun("Acme Corp")],
},
},
});
fs.writeFileSync("output.docx", doc);
Patch Types
The examples below patch simple-template.docx, which has placeholders such as {{name}}, {{paragraph_replace}} and {{table}}.
PARAGRAPH Type
Use PatchType.PARAGRAPH to replace with inline content (TextRun, images, hyperlinks):
import * as fs from "fs";
import { patchDocument, PatchType, TextRun } from "docx";
const doc = await patchDocument({
outputType: "nodebuffer",
data: fs.readFileSync("./demo/assets/simple-template.docx"),
patches: {
name: {
type: PatchType.PARAGRAPH,
children: [new TextRun("Hello "), new TextRun({ text: "World", bold: true })],
},
},
});
fs.writeFileSync("My Document.docx", doc);
DOCUMENT Type
Use PatchType.DOCUMENT to replace with block-level content (paragraphs, tables):
import * as fs from "fs";
import { Paragraph, patchDocument, PatchType, Table, TableCell, TableRow } from "docx";
const doc = await patchDocument({
outputType: "nodebuffer",
data: fs.readFileSync("./demo/assets/simple-template.docx"),
patches: {
paragraph_replace: {
type: PatchType.DOCUMENT,
children: [
new Paragraph("First paragraph"),
new Paragraph("Second paragraph"),
new Table({
rows: [
new TableRow({
children: [
new TableCell({ children: [new Paragraph("First cell")] }),
new TableCell({ children: [new Paragraph("Second cell")] }),
],
}),
],
}),
],
},
},
});
fs.writeFileSync("My Document.docx", doc);
Advanced Patches
Images
import * as fs from "fs";
import { ImageRun, patchDocument, PatchType } from "docx";
const doc = await patchDocument({
outputType: "nodebuffer",
data: fs.readFileSync("./demo/assets/simple-template.docx"),
patches: {
image_test: {
type: PatchType.PARAGRAPH,
children: [
new ImageRun({
type: "png",
data: fs.readFileSync("./demo/assets/images/dog.png"),
transformation: { width: 100, height: 90 },
}),
],
},
},
});
fs.writeFileSync("My Document.docx", doc);
Hyperlinks
import * as fs from "fs";
import { ExternalHyperlink, patchDocument, PatchType, TextRun } from "docx";
const doc = await patchDocument({
outputType: "nodebuffer",
data: fs.readFileSync("./demo/assets/simple-template.docx"),
patches: {
item_1: {
type: PatchType.PARAGRAPH,
children: [
new ExternalHyperlink({
children: [
new TextRun({
text: "Visit our website",
style: "Hyperlink",
}),
],
link: "https://example.com",
}),
],
},
},
});
fs.writeFileSync("My Document.docx", doc);
Tables
import * as fs from "fs";
import { Paragraph, patchDocument, PatchType, Table, TableCell, TableRow } from "docx";
const doc = await patchDocument({
outputType: "nodebuffer",
data: fs.readFileSync("./demo/assets/simple-template.docx"),
patches: {
table: {
type: PatchType.DOCUMENT,
children: [
new Table({
rows: [
new TableRow({
children: [
new TableCell({ children: [new Paragraph("Item")] }),
new TableCell({ children: [new Paragraph("Price")] }),
],
}),
new TableRow({
children: [
new TableCell({ children: [new Paragraph("Widget")] }),
new TableCell({ children: [new Paragraph("$9.99")] }),
],
}),
],
}),
],
},
},
});
fs.writeFileSync("My Document.docx", doc);
Preserving Styles
Set keepOriginalStyles: true to preserve the formatting of the placeholder text:
import * as fs from "fs";
import { patchDocument, PatchType, TextRun } from "docx";
const doc = await patchDocument({
outputType: "nodebuffer",
data: fs.readFileSync("./demo/assets/simple-template-3.docx"),
keepOriginalStyles: true, // Preserve template formatting
patches: {
salutation: {
type: PatchType.PARAGRAPH,
children: [new TextRun("Mr.")],
},
"first-name": {
type: PatchType.PARAGRAPH,
children: [new TextRun("John")],
},
},
});
fs.writeFileSync("My Document.docx", doc);
Headers and Footers
Placeholders in headers and footers are also replaced:
import * as fs from "fs";
import { patchDocument, PatchType, TextRun } from "docx";
const doc = await patchDocument({
outputType: "nodebuffer",
data: fs.readFileSync("./demo/assets/simple-template.docx"),
patches: {
header_adjective: {
type: PatchType.PARAGRAPH,
children: [new TextRun("great header")],
},
footer_text: {
type: PatchType.PARAGRAPH,
children: [new TextRun("Confidential")],
},
},
});
fs.writeFileSync("My Document.docx", doc);
Complete Example
Invoice template:
import * as fs from "fs";
import { Document, Packer, Paragraph, patchDocument, PatchType, Table, TableCell, TableRow, TextRun } from "docx";
// Invoice data
const invoice = {
number: "INV-2024-001",
date: "January 10, 2024",
customer: "Acme Corporation",
items: [
{ name: "Widget A", qty: 5, price: 10.0 },
{ name: "Widget B", qty: 3, price: 15.0 },
],
total: 95.0,
};
// The template, made here as it would be in Word
const template = new Document({
sections: [
{
children: [
new Paragraph("Invoice {{invoice_number}}"),
new Paragraph("Date: {{invoice_date}}"),
new Paragraph("Bill to: {{customer_name}}"),
new Paragraph("{{line_items}}"),
new Paragraph("Total: {{total}}"),
],
},
],
});
const doc = await patchDocument({
outputType: "nodebuffer",
data: await Packer.toBuffer(template), // or fs.readFileSync("invoice-template.docx")
patches: {
invoice_number: {
type: PatchType.PARAGRAPH,
children: [new TextRun(invoice.number)],
},
invoice_date: {
type: PatchType.PARAGRAPH,
children: [new TextRun(invoice.date)],
},
customer_name: {
type: PatchType.PARAGRAPH,
children: [new TextRun(invoice.customer)],
},
line_items: {
type: PatchType.DOCUMENT,
children: [
new Table({
rows: [
new TableRow({
children: [
new TableCell({ children: [new Paragraph("Item")] }),
new TableCell({ children: [new Paragraph("Qty")] }),
new TableCell({ children: [new Paragraph("Price")] }),
],
}),
...invoice.items.map(
(item) =>
new TableRow({
children: [
new TableCell({ children: [new Paragraph(item.name)] }),
new TableCell({ children: [new Paragraph(String(item.qty))] }),
new TableCell({ children: [new Paragraph(`$${item.price.toFixed(2)}`)] }),
],
}),
),
],
}),
],
},
total: {
type: PatchType.PARAGRAPH,
children: [
new TextRun({
text: `$${invoice.total.toFixed(2)}`,
bold: true,
}),
],
},
},
});
fs.writeFileSync("invoice-output.docx", doc);
Tips
- Placeholder naming: Use descriptive names like
customer_nameinstead ofx1 - Testing: Open the template in Word to verify placeholders are formatted as plain text
- Complex layouts: Design the layout in Word, then add placeholders where content varies
- Reusable templates: Store templates in a dedicated folder for easy access
Demo
Source: https://github.com/dolanmiu/docx/blob/master/demo/templates/patch-document.ts