* fix: patch placeholders in links, content controls and tracked changes patchDocument and patchDetector only read runs that are direct children of a paragraph, so a placeholder in a link, a content control, text typed with Track Changes on, a smart tag or a field's result was left as it was, with no error. Runs in those elements are now read and patched where they are. Where the content can't go in what holds the placeholder, it goes where Word can open it: a link is taken out of a tracked insertion (whose piece after it gets an id of its own) or a link, a plain text content control given more than text becomes a rich text one, and a content control showing its placeholder text stops showing it. Addresses #2679 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * test: cover every branch of patching runs in links and content controls CI's coverage fell below 100%: an empty link, a content control without properties, and runs that stay together when a tracked insertion is split weren't tested. The name fallbacks in the replacer's lookups could never be reached, so the lookups take an element's name as it is. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * feat: find placeholders with custom delimiters with patchDetector, and say why a placeholder isn't replaced patchDetector takes placeholderDelimiters, as patchDocument does, so it finds the same placeholders. Before, it only knew {{ and }}, and found nothing in a template with <<name>>. templates.md has a section on a placeholder that isn't replaced: how to find the patches whose placeholder isn't in the template with patchDetector, as patchDocument leaves them out without an error, and the usual reasons, such as a key written with its braces. Addresses #2679 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * fix: unbind a content control a patch fills, so Word doesn't put the placeholder back Word fills a control bound to custom XML or a document property (w:dataBinding) in from its data when it opens a document. A patched placeholder in one came back: Word for Mac showed {{name}} from the XML, though the control held the patch's text. The binding is now removed from a control a patch's content goes in. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * perf: split a tracked change around a link in linear time The stretches were built by copying the stretch so far for each element, so a tracked insertion of n runs took n² steps to split. Each stretch is now sliced from where it starts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * docs: list a placeholder only in alt text among the reasons a patch isn't applied patchDetector finds placeholders in pictures' and charts' alt text, so comparing its keys with the patches' doesn't show a text patch for one, which leaves it as it is. It's now one of the listed reasons, saying so. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * fix: don't let a start delimiter before a placeholder hide it from patchDetector A key ran from the first start delimiter to the next end delimiter, so in "<<unfinished <<name>>" patchDetector found "unfinished <<name", not "name", which patchDocument patches. With one-character delimiters such as < and >, any "<" in the text did this. A key now has no start delimiter in it. The search from a start delimiter with no end after it also stops at the next one, rather than going on to the end of the paragraph each time: 120,000 characters of unmatched "<" took 1.4 s, and now take no time. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * test: check the link a patch puts in a content control without properties The test only checked the control's text and its one child, so content that lost the link would have passed it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
9.0 KiB
Patcher
The patcher allows you to modify existing documents, and add new content to them.
!> The Patcher requires an understanding of Paragraphs.
Usage
import * as fs from "fs";
import { patchDocument } from "docx";
const doc = await patchDocument({
outputType: "nodebuffer",
data: fs.readFileSync("My Document.docx"),
patches: {
// Patches here
},
});
fs.writeFileSync("My Patched Document.docx", doc);
data can be a Buffer, Uint8Array, ArrayBuffer, Blob, JSZip instance, or a Node.js stream such as fs.createReadStream("My Document.docx") or Packer.toStream(doc). A stream can be read only once, so to pass the same template to both patchDetector and patchDocument, read it into a Buffer first.
Discover placeholders before building patches
Use patchDetector({ data }) to find the placeholder keys in a template before calling patchDocument. It returns distinct keys without the {{ and }} delimiters. This is useful when templates differ: an expensive patch, such as downloading images, only needs to be built when its placeholder is present.
If the template's placeholders have other delimiters, such as <<name>>, give patchDetector the same placeholderDelimiters as patchDocument, such as { start: "<<", end: ">>" }.
If the template's placeholders can have spaces inside their braces, such as {{ name }}, give both patchDetector and patchDocument trimPlaceholders: true. patchDetector then gives the key as name, and patchDocument patches the placeholder with the patch name. See Spaces inside placeholders.
The following example uses the existing simple-template.docx. Keep patch builders as functions so that discovering placeholders does not run every builder. Reuse the same template data for detection and patching.
import * as fs from "fs";
import { type IPatch, Paragraph, patchDetector, patchDocument, PatchType, TextRun } from "docx";
const data = fs.readFileSync("./demo/assets/simple-template.docx");
const builders: Readonly<Record<string, () => Promise<IPatch>>> = {
name: async () => ({ type: PatchType.PARAGRAPH, children: [new TextRun("John Doe")] }),
paragraph_replace: async () => ({
type: PatchType.DOCUMENT,
children: [new Paragraph("This content is built only if the template requests it.")],
}),
};
const keys = await patchDetector({ data });
const entries = await Promise.all(
keys.filter((key) => Object.hasOwn(builders, key)).map(async (key) => [key, await builders[key]()] as const),
);
const doc = await patchDocument({ outputType: "nodebuffer", data, patches: Object.fromEntries(entries) });
fs.writeFileSync("My Patched Document.docx", doc);
This example patches only keys with a registered builder; other placeholders remain in the document. To find patches whose placeholder isn't in the template, which patchDocument leaves out without an error, see A placeholder isn't replaced. If every placeholder must be resolved, validate the detected keys against your builders and report unsupported keys before patching. Detection discovers keys; it does not generate replacement content or call patchDocument for you.
Patches
The patcher takes in a patches object, which is a map of string to Patch:
interface Patch {
type: PatchType;
children: FileChild[] | ParagraphChild[];
}
| Property | Type | Notes | Possible Values |
|---|---|---|---|
| type | PatchType |
Required | DOCUMENT, PARAGRAPH |
| children | FileChild[] or ParagraphChild[] |
Required | The contents to replace with. A FileChild is a Paragraph or Table, whereas a ParagraphChild is typical Paragraph children. |
A patch can also repeat the rows of a table in the template, once for each row of data, keeping the table's look: { type: PatchType.TABLE_ROWS, rows: [...] }, where each row gives the patches for its copy's fields, such as {{items.name}}. See TABLE_ROWS Type.
A paragraph in a patch can be a heading. Its style is added to a template that doesn't have it yet. See Headings and styles.
The patcher also takes in a keepOriginalStyles boolean, which will preserve the styles of the patched text when set to true.
It also takes in placeholderDelimiters, for a template whose placeholders aren't in double curly braces, such as { start: "<<", end: ">>" } for <<name>>.
It also takes in a trimPlaceholders boolean, which patches a placeholder with spaces inside its delimiters, such as {{ name }}, as if it had none. See Spaces inside placeholders.
It also takes in footnotes and endnotes, for the notes that patches refer to with a FootnoteReferenceRun or an EndnoteReferenceRun. See Footnotes and endnotes.
It takes in numbering too, for the lists that the paragraphs in patches use with numbering: { reference, level }, as in a Document. See Lists.
Given estimatePageNumbers from docx/layout as its pageNumbers, it writes the page numbers of the template's tables of contents and page references, and its numbers of pages, once the patches are in. See Page numbers.
It also takes in properties, such as the document's title, tags and comments, which replace the template's. See Document Properties.
A patch can also be for a drawing whose alt text holds the placeholder, rather than for text: ImagePatch gives a picture in the template a new image, keeping its size, position and border (see Replacing a Picture), and ChartDataPatch from docx/charts gives a chart made in Word new data, keeping its look (see Charts in Templates).
How to patch existing document
- Open your existing word document in your favorite Word Processor
- Write tags in the document where you want to patch in a mustache style notation. For example,
{{my_patch}}and{{my_second_patch}}. - Run the patcher with the patches as a key value pair.
Example
Word Document
Patcher
?> Notice how there is no handlebar notation in the key.
The patch can be as simple as a string, or as complex as a table. Images, hyperlinks, charts from docx/charts (see Charts in Templates), and other complex elements within the docx library are also supported.
This example patches {{name}} and {{paragraph_replace}} in simple-template.docx:
import * as fs from "fs";
import { ExternalHyperlink, ImageRun, Paragraph, 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("Sir. "), new TextRun("John Doe"), new TextRun("(The Conqueror)")],
},
paragraph_replace: {
type: PatchType.DOCUMENT,
children: [
new Paragraph("Lorem ipsum paragraph"),
new Paragraph("Another paragraph"),
new Paragraph({
children: [
new TextRun("This is a "),
new ExternalHyperlink({
children: [
new TextRun({
text: "Google Link",
}),
],
link: "https://www.google.co.uk",
}),
new ImageRun({
type: "png",
data: fs.readFileSync("./demo/assets/images/dog.png"),
transformation: { width: 100, height: 100 },
}),
],
}),
],
},
},
});
fs.writeFileSync("My Document.docx", doc);
Demo
Source: https://github.com/dolanmiu/docx/blob/master/demo/templates/patch-document.ts
