Skip to content
Office Open

DOCX

Patching

Modify an existing .docx through canonical DocumentOptions commands

patchDocument parses an existing .docx into DocumentOptions, applies ordered commands, and regenerates the package. Canonical round-trip fields preserve package facts that are not part of the edited subtree.

#Commands

CommandPurpose
insertAdd canonical items to an array field or nested collection
replaceReplace a canonical field/node or selected text
updateDeep-merge object fields; arrays are replaced as a whole
removeRemove a canonical node or selected text
moveReorder an item in a canonical array
ts
import { patchDocument } from "@office-open/docx";

const result = await patchDocument({
  data: template,
  commands: [
    {
      type: "replace",
      at: { field: "sections", route: [{ index: 0 }], text: { placeholder: "name" } },
      value: "John Doe",
    },
    {
      type: "insert",
      at: { field: "sections", route: [{ index: 0 }, { collection: "children" }] },
      position: "end",
      value: [{ paragraph: { children: ["Appendix"] } }],
    },
    { type: "update", at: { field: "title" }, set: "Quarterly Report" },
  ],
});

field is a DocumentOptions root field. route selects nested nodes by property, array index, or a native identity such as id, name, reference, or address. Text matches are singular unless all: true; a missing match throws PatchError.

#Options

OptionTypeDefault
dataDataTyperequired
commandsreadonly DocumentPatchCommand[]required
outputTypeOutputType"uint8array"
packageVariant"standard" | "macro" | "template" | "macroTemplate""standard"
placeholderDelimiters{ start, end }{ start: "{{", end: "}}" }