Files
docx/docs/usage/patcher.md
T
Dolan e008c45c0c feat(layout): read a .docx into the layout, to write a template's page numbers and check Word's own pages (#3619)
* feat(layout): read a .docx into the layout, to write a template's page numbers and check Word's own pages

docx/layout read only the document being written, from its formatted
XML. A second adapter, read-docx.ts, reads a parsed .docx into the same
blocks: it follows the package's relationships to the main document and
its styles, theme, numbering, settings, headers, footers and notes, and
reads them with the same reader, which now takes a document's parts
rather than context.file.

patchDocument takes the same estimatePageNumbers as Document, as its
pageNumbers. Once the patches are in, it gives the estimator the
template's parsed parts and writes the page numbers into the PAGEREF,
NUMPAGES and SECTIONPAGES fields of its body, headers and footers. The
numbers a template was saved with are those from before it was filled
in, so one the layout can't work out is left blank. The writing of the
fields is shared between formatted and parsed trees.

A document in compatibility mode stops the layout: Word lays it out as
an older version of Word did, which isn't followed. LibreOffice writes
mode 12, and docx writes 15.

compare-layout.ts lays out documents Word saved through the adapter, and
compares them with the pages Word marked with w:lastRenderedPageBreak,
read with the rules Word's PDFs of the layout demos showed, and with
Word's PDFs. The 7 demos whose marks have all their pages are committed
in scripts/layout-probes, so CI checks docx/layout against Word's own
pages. A new demo fills a template in with patchDocument and writes its
page numbers.

* fix(layout): fail the layout comparison when there are no documents saved from Word to compare

compare-layout.sh copied the documents saved from Word in
scripts/layout-probes into its output directory only if they were there,
so when the glob found none, as when the script runs from another
directory, Word's own pages weren't compared and the comparison passed
anyway. It now stops with an error. compare-layout.ts still compares a
directory without them, as it does when run on its own.

* fix(layout): compare documents saved from Word only with the pages Word marked in them

compare-layout.ts compared each document saved from Word with Word's PDF
of the demo of the same name too. When a demo changes, as columns did in
#3611, Word's PDF is made again of the new demo, and no longer is of the
document Word saved, so the two disagreed although docx/layout matched
both. A document saved from Word has Word's own pages in its marks, so it
is compared only with them, and one whose marks don't have all its pages
isn't compared.

* fix(layout): fail the layout comparison when a committed document saved from Word can't be compared

The documents saved from Word in scripts/layout-probes are committed
because Word's marks have all their pages. One whose marks no longer read
as having them all was skipped without failing, so a mistake in reading
Word's pages would have turned off the check in CI. It now fails. A
document only in the output directory whose marks don't have all its
pages, as Word's columns and long-table-of-contents, is still left out.
2026-10-02 01:48:30 +01:00

5.1 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);

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.

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 footnotes and endnotes, for the notes that patches refer to with a FootnoteReferenceRun or an EndnoteReferenceRun. See Footnotes and endnotes.

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.

A patch can also be for a drawing whose alt text holds the placeholder, rather than for text: ChartDataPatch from docx/charts gives a chart made in Word new data, keeping its look. See Charts in Templates.

How to patch existing document

  1. Open your existing word document in your favorite Word Processor
  2. Write tags in the document where you want to patch in a mustache style notation. For example, {{my_patch}} and {{my_second_patch}}.
  3. Run the patcher with the patches as a key value pair.

Example

Word Document

Word Document screenshot

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

Example