> ## Documentation Index
> Fetch the complete documentation index at: https://docs.reducto.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# WordDocument

The document. Open or create one, then edit it through `body`, `sections`, `comments` and the other collections. [Concepts](https://docs.reducto.ai/office/docx/js-api/concepts.md) explains the model.

## `WordDocument`

Unsupported OfficeJS surface kept on the prototype for API-shape compatibility.

Import from `@reductoai/docx/officejs`.

### WordDocument properties

| Name | Type | Description |
| - | - | - |
| `body` | `Body` | read-only |
| `layout` | `DocumentLayout` | read-only Renderer-backed headless extensions; not part of Microsoft's OfficeJS surface. |
| `sections` | `SectionCollection<Section>` | read-only |
| `session` | `DocxSession` | read-only |
| `activeTheme` | `string` | read-only office.js Document.activeTheme: the theme part's name ("Office Theme"); "" with no theme. |
| `activeThemeDisplayName` | `string` | read-only |
| `areTrueTypeFontsEmbedded` | `boolean` | w:embedTrueTypeFonts: the faces stored with `embedFont` travel with the file. |
| `background` | `DocumentBackground` | read-only office.js Document.background: the page colour, through a ShapeFill-shaped fill. |
| `bookmarks` | `HandleCollection<Bookmark>` | read-only office.js Document.bookmarks: the main story's bookmarks as a live `HandleCollection<Bookmark>`, not a `BookmarkCollection`. Excludes bookmarks whose names begin with `_`, such as Word's `_Toc…` and `_GoBack`. Use `Range.getBookmarks(true, …)` to include them. |
| `builtInDocumentProperties` | `DocumentProperties` | read-only office.js Document.builtInDocumentProperties: the handle `properties` returns. |
| `changeTrackingMode` | `"Off" \| "TrackAll" \| "TrackMineOnly"` | Read this right after open: a file carrying w:trackRevisions opens as "TrackAll", and every edit is then authored as a redline until the mode is set to "Off". |
| `comments` | `CommentCollection` | read-only |
| `compatibilityMode` | `CompatibilityMode` | read-only The layout generation Word lays the file out with (w:compatSetting compatibilityMode). |
| `content` | `Range` | read-only office.js Document.content: the whole main story as one live Range — every body paragraph, table-cell paragraphs included, covered WHOLE. Edits through it are ordinary Range edits: `insertText(text, "End")` lands at the end of the last body paragraph. |
| `contentControls` | `ContentControlCollection` | read-only |
| `customDocumentProperties` | `CustomPropertyCollection` | read-only The docProps/custom.xml door. It is REAL and live — read, write, add and delete — but its SHAPE diverges: office.js types it as a second `DocumentProperties`, while OfficeJS here answers with the keyed `CustomPropertyCollection` that `properties.customProperties` returns. |
| `customXmlParts` | `CustomXmlPartCollection` | read-only |
| `documentDefaults` | `DocumentDefaults` | read-only Extension: `w:docDefaults`, the font and paragraph format under every style. |
| `documentTheme` | `DocumentTheme` | read-only Extension (VBA `Document.DocumentTheme`): the theme's colour and font schemes. |
| `editVersion` | `number` | read-only Monotonic count of registered edits — the one-step no-op detector. Compare before and after a verb: an unchanged count means nothing was registered for save, so the verb did not touch the document. |
| `fields` | `FieldCollection` | read-only office.js Document.fields: the MAIN TEXT STORY's fields, the scope VBA's `Document.Fields` has. A field authored in a HEADER, FOOTER, FOOTNOTE, ENDNOTE or TEXTBOX is in another story and is NOT here — read it through that story's own body. |
| `frames` | `FrameCollection` | read-only office.js Document.frames: the main story's text frames (w:framePr), drop caps aside. |
| `hyperlinks` | `HandleCollection<Hyperlink>` | read-only office.js Document.hyperlinks: the main story's links as a live `HandleCollection<Hyperlink>`, not a `HyperlinkCollection`. Same story scope and same membership as `Range.hyperlinks` over the whole story. |
| `indexes` | `IndexCollection` | read-only |
| `justificationMode` | `JustificationMode` | w:characterSpacingControl: doNotCompress, compressPunctuation, compressPunctuationAndJapaneseKana. |
| `listParagraphs` | `ParagraphCollection<Paragraph>` | read-only office.js Document.listParagraphs: every main-story paragraph that carries list numbering, in DOCUMENT ORDER, as a live `ParagraphCollection`. Membership is the door `Body.lists` and `Range.lists` use, so the two always agree: DIRECT `w:pPr/w:numPr` first, else the numbering the paragraph's STYLE CHAIN carries — a Heading whose style numbers it counts here with no direct markup of its own. `w:numId` 0 means "no list" and is excluded, as Word treats it. |
| `lists` | `HandleCollection<List>` | read-only Unique lists represented in the main document body scope. |
| `paragraphs` | `ParagraphCollection<Paragraph>` | read-only Main-story paragraphs; table-cell paragraphs remain cell-scoped. |
| `properties` | `DocumentProperties` | read-only Package metadata: docProps/core.xml, docProps/app.xml, docProps/custom.xml. |
| `protectionType` | `ProtectionType` | read-only |
| `removePersonalInformationOnSave` | `boolean` | |
| `revisionAuthor` | `string` | Extension (VBA `Application.UserName`): the author stamped on new tracked changes and comments. |
| `revisionDate` | `Date \| undefined` | Extension: pins the `w:date` of new revisions and comments; unset stamps the current time. |
| `revisions` | `RevisionCollection` | read-only |
| `styles` | `DocumentStyle[]` | read-only Snapshot of the styles part: every defined style's id, name, and type. |
| `tableOfAuthoritiesCategories` | `TableOfAuthoritiesCategoryCollection` | read-only |
| `tables` | `TableCollection<Table>` | read-only Top-level tables in the main document body. |
| `tablesOfAuthorities` | `TableOfAuthoritiesCollection` | read-only |
| `tablesOfContents` | `TableOfContentsCollection` | read-only |
| `tablesOfFigures` | `TableOfFiguresCollection` | read-only |
| `trackedChangesAreDateAndTimeRemoved` | `boolean` | read-only |
| `trackMoves` | `boolean` | Word's Track Moves option (`w:doNotTrackMoves`): off, Paragraph.moveTo records a deletion and an insertion. |
| `trackRevisions` | `boolean` | |
| `type` | `"Document"` | read-only |
| `watermark` | `TextWatermark \| null` | read-only Extension (Design > Watermark): the text watermark the first header carries, or null. |

### `WordDocument.create()`

```ts theme={null}
static create<T extends WordDocument>(
  this: WordDocumentClass<T>,
  options?: WordDocumentOptions,
): Promise<T>
```

Create a blank document from the built-in default template.

### `WordDocument.from()`

```ts theme={null}
static from<T extends WordDocument>(
  this: WordDocumentClass<T>,
  session: DocxSession,
  options?: WordDocumentOptions,
): T
```

Wrap an open session; pass an editor host's `pages` as `layout` to share its IR.

### `WordDocument.fromBytes()`

```ts theme={null}
static fromBytes<T extends WordDocument>(
  this: WordDocumentClass<T>,
  bytes: Uint8Array,
  options?: WordDocumentOptions,
): Promise<T>
```

### `acceptAllRevisions()`

```ts theme={null}
acceptAllRevisions(): void
```

### `acceptAllRevisionsShown()`

```ts theme={null}
acceptAllRevisionsShown(..._args: unknown[]): void
```

### `addStyle()`

```ts theme={null}
addStyle(name: string, type: string): Style
```

### `assertPageCount()`

```ts theme={null}
assertPageCount(maximum: number): Promise<number>
```

Throws with an actionable message when layout exceeds `maximum`.

### `convertNotes()`

```ts theme={null}
convertNotes(to: ConvertNotesTo): ClientResult<number>
```

Extension (References > Footnotes > Convert): every footnote to an endnote, every endnote to a
footnote, or both at once. Both kinds renumber in document order. Returns the notes moved.

### `declareFont()`

```ts theme={null}
declareFont(name: string, declaration: FontDeclaration): void
```

Extension: describe a font in the font table, so a host without it picks a like stand-in.

### `deleteAllComments()`

```ts theme={null}
deleteAllComments(): void
```

### `deleteAllCommentsShown()`

```ts theme={null}
deleteAllCommentsShown(..._args: unknown[]): void
```

### `deleteBookmark()`

```ts theme={null}
deleteBookmark(name: string): void
```

Remove a bookmark's markers by name (case-insensitive); its content stays.

### `dispose()`

```ts theme={null}
dispose(): Promise<void>
```

Extension: frees the layout engine's copy of this document now; GC frees it otherwise.
The document stays usable, and its next layout starts from scratch.

### `embedFont()`

```ts theme={null}
embedFont(
  name: string,
  base64: string,
  style?: "Regular" | "Bold" | "Italic" | "BoldItalic",
): void
```

Extension: store one face of a TrueType/OpenType font in the file and set areTrueTypeFontsEmbedded.

### `getBookmarkRange()`

```ts theme={null}
getBookmarkRange(name: string): Range
```

### `getBookmarkRangeOrNullObject()`

```ts theme={null}
getBookmarkRangeOrNullObject(name: string): Range & { isNullObject: boolean }
```

### `getCompatibility()`

```ts theme={null}
getCompatibility(option: CompatibilityOption): boolean
```

Extension (VBA `Document.Compatibility(Type)`): one layout option of w:compat.

### `getCrossReferenceItems()`

```ts theme={null}
getCrossReferenceItems(referenceType: string): ClientResult<string[]>
```

office.js Document.getCrossReferenceItems; a caption label ("Figure") also works, as in VBA.

### `getFontDeclaration()`

```ts theme={null}
getFontDeclaration(name: string): FontDeclaration | null
```

Extension: the font table's description of `name`, or null when it has none.

### `getPageCount()`

```ts theme={null}
getPageCount(): Promise<number>
```

Layout-backed page count for keeping authored documents within a page budget.

### `getParagraphByUniqueLocalId()`

```ts theme={null}
getParagraphByUniqueLocalId(id: string): Paragraph
```

The paragraph whose `uniqueLocalId` is `id`, in the body, a header, a footer or a note;
throws ItemNotFound. Unlike Word, an id read before a save or a reload still finds it.

### `getSelection()`

```ts theme={null}
getSelection(): Range
```

The user's selection at the moment of the call, as a Range. Present only
when the host that opened this document supplies one (`options.selection`,
see WordDocument.from); a headless document throws, as Word does with no
window. A collapsed caret is an empty range at that point.

### `getStyles()`

```ts theme={null}
getStyles(): StyleCollection
```

### `getTarget()`

```ts theme={null}
getTarget(targetId: string): Chart | Shape | Paragraph | TableCell
```

Resolve a CLI/page-sketch target id (`p:N`, `c:N:ROW:COL`, `shape:ID`,
`chart:ID`) to a live handle. `p:N` counts TOP-LEVEL body blocks — the
same address space `docx read`/`find` print — which is NOT an index into
`body.paragraphs.items` (that collection includes table-cell paragraphs).

### `insertFileFromBase64()`

```ts theme={null}
insertFileFromBase64(
  base64File: DocxFile,
  insertLocation: "Replace" | "Start" | "End",
): Promise<Range>
```

The file goes into the body, as Body.insertFileFromBase64; resolves to the inserted range.

### `protect()`

```ts theme={null}
protect(type: ProtectionType, options?: ProtectOptions): void
```

Extension: OfficeJS only reads protection. AllowOnlyRevisions locks tracking on.

### `readPage()`

```ts theme={null}
readPage(page: number): Promise<string>
```

Layout-backed sketch of one 1-based page: header/footer, body text with
`p:N` addresses, images, and empty bands. Use before inserting so you
don't drop content onto a closing plate or split a last page.

### `readPages()`

```ts theme={null}
readPages(pages?: number[]): Promise<string>
```

Omit `pages` for a one-line index of every page; pass 1-based numbers for
full sketches joined by a blank line.

### `rejectAllRevisions()`

```ts theme={null}
rejectAllRevisions(): void
```

### `rejectAllRevisionsShown()`

```ts theme={null}
rejectAllRevisionsShown(..._args: unknown[]): void
```

### `removeDocumentInformation()`

```ts theme={null}
removeDocumentInformation(
  removeDocInfoType: "All" | "Comments" | "Template" | "Revisions" | "Versions" | "RemovePersonalInformation" | "EmailHeader" | "RoutingSlip" | "SendForReview" | "DocumentProperties" | "DocumentWorkspace" | "InkAnnotations" | "DocumentServerProperties" | "DocumentManagementPolicy" | "ContentType" | "TaskpaneWebExtensions" | "AtMentions" | "DocumentTasks" | "DocumentIntelligence" | "CommentReactions",
): void
```

Word's Document Inspector; see the parity map for what each type scrubs.

### `removePageNumbers()`

```ts theme={null}
removePageNumbers(): ClientResult<boolean>
```

Extension (Insert > Page Number > Remove Page Numbers): every PAGE field and page-number block
in the headers and footers goes; "Page 3 of 9" goes whole. False when there was none.

### `removeWatermark()`

```ts theme={null}
removeWatermark(): void
```

Extension (Design > Watermark > Remove Watermark).

### `replaceAll()`

```ts theme={null}
replaceAll(
  find: string,
  replacement: string,
  format?: OfficeRunFormatInput,
  options?: SearchOptions,
): number
```

Replace every occurrence of `find`; returns the number of hits.

### `search()`

```ts theme={null}
search(needle: string, options?: SearchOptions): RangeCollection<Range>
```

Literal search over the whole body PLUS every textbox story anchored in
it (body.search stays story-scoped, like OfficeJS). Body hits come
first, then textbox hits in document order.

### `set()`

```ts theme={null}
set(properties: WordDocumentUpdateData, options?: UpdateOptions): void
```

### `setCompatibility()`

```ts theme={null}
setCompatibility(option: CompatibilityOption, value: boolean): void
```

Extension (VBA `Document.Compatibility(Type) = value`).

### `setCompatibilityMode()`

```ts theme={null}
setCompatibilityMode(mode: CompatibilityMode): void
```

Extension (VBA `Document.SetCompatibilityMode`): "Word2013" and "Current" both write mode 15.

### `setDefaultFont()`

```ts theme={null}
setDefaultFont(name: string): SetDefaultFontReport
```

Document-wide default font. Rewrites the theme's latin typefaces (major
and minor) and the styles part's docDefaults w:rFonts, so Normal,
headings, and bullets that inherit the default all follow — no per-run
writes needed. Direct run formatting and styles with their own w:rFonts
still win, per the usual OOXML precedence, so the report counts what this
call did NOT reach: when `directRuns` is most of `runs`, the page will not
change, and `body.font.name = face` is the write that does.

### `setWatermark()`

```ts theme={null}
setWatermark(watermark: TextWatermark): void
```

Extension (Design > Watermark > Custom Watermark, Text): a text watermark behind every page,
placed in every header (a first-page or even header too). Replaces one already there.

### `toBytes()`

```ts theme={null}
toBytes(): Promise<Uint8Array<ArrayBufferLike>>
```

### `toLayout()`

```ts theme={null}
toLayout(request?: LayoutRequest): Promise<LayoutDocument>
```

The laid pages of the current edit state, for a painter (@reductoai/viewer, a PDF writer).
`throughPage` lays only up to that page after an edit; later pages and the page count may be stale.

### `unprotect()`

```ts theme={null}
unprotect(password?: string): void
```

### `updateFields()`

```ts theme={null}
updateFields(options?: UpdateFieldsOptions): Promise<FieldRefreshReport>
```

Update field caches and optionally rebuild TOCs; see docs/field-updates.md.

**Not implemented.** These Office.js members throw: `activeWindow`, `areFilePropertiesPasswordEncrypted`, `areGrammaticalErrorsShown`, `areMathDefaultsUsed`, `areNewerFeaturesDisabled`, `areSpellingErrorsShown`, `areStylesUpdatedOnOpen`, `attachedTemplate`, `autoHyphenation`, `autoSaveOn`, `bibliography`, `characters`, `coauthoring`, `codeName`, `consecutiveHyphensLimit`, `currentRsid`, `defaultTabStop`, `defaultTargetFrame`, `documentLibraryVersions`, `doNotEmbedSystemFonts`, `encryptionProvider`, `farEastLineBreakLanguage`, `farEastLineBreakLevel`, `formattingIsNextLevelShown`, `formattingIsUserStyleNameShown`, `fullName`, `grammaticalErrors`, `gridDistanceHorizontal`, `gridDistanceVertical`, `gridIsOriginFromMargin`, `gridOriginHorizontal`, `gridOriginVertical`, `gridSpaceBetweenHorizontalLines`, `gridSpaceBetweenVerticalLines`, `hasPassword`, `hasVbProject`, `hyphenateCaps`, `hyphenationZone`, `isAutoFormatOverrideOn`, `isChartDataPointTracked`, `isCompatible`, `isFinal`, `isFontsSubsetSaved`, `isFormsDataPrinted`, `isFormsDataSaved`, `isGrammarChecked`, `isInAutoSave`, `isInFormsDesign`, `isKerningByAlgorithm`, `isLinguisticDataEmbedded`, `isMasterDocument`, `isOptimizedForWord97`, `isPostScriptPrintedOverText`, `isQuickStyleSetLocked`, `isReadOnly`, `isReadOnlyRecommended`, `isSnappedToGrid`, `isSnappedToShapes`, `isSpellingChecked`, `isStyleEnforced`, `isSubdocument`, `isThemeLocked`, `isUserControl`, `isVbaSigned`, `isWriteReserved`, `kind`, `languageDetected`, `listTemplates`, `noLineBreakAfter`, `noLineBreakBefore`, `onAnnotationClicked`, `onAnnotationHovered`, `onAnnotationInserted`, `onAnnotationPopupAction`, `onAnnotationRemoved`, `onContentControlAdded`, `onParagraphAdded`, `onParagraphChanged`, `onParagraphDeleted`, `openEncoding`, `originalDocumentTitle`, `pageSetup`, `password`, `passwordEncryptionAlgorithm`, `passwordEncryptionKeyLength`, `passwordEncryptionProvider`, `path`, `printRevisions`, `readabilityStatistics`, `readingLayoutSizeX`, `readingLayoutSizeY`, `readingModeIsLayoutFrozen`, `revisedDocumentTitle`, `saved`, `saveEncoding`, `saveFormat`, `selection`, `sentences`, `settings`, `spellingErrors`, `storyRanges`, `textEncoding`, `textLineEnding`, `trackFormatting`, `webSettings`, `windows`, `words`, `writePassword`, `xmlAreAdvancedErrorsShown`, `xmlIsXsltUsedWhenSaving`, `xmlSaveThroughXslt`, `activate`, `addToFavorites`, `applyQuickStyleSet`, `applyTheme`, `autoFormat`, `canCheckin`, `checkConsistencyJapanese`, `checkGrammar`, `close`, `closePrintPreview`, `compare`, `compareFromBase64`, `convert`, `convertAutoHyphens`, `convertNumbersToText`, `convertVietnameseDocument`, `copyStylesFromTemplate`, `deleteAllInkAnnotations`, `detectLanguage`, `fitToPages`, `freezeLayout`, `getAnnotationById`, `getContentControls`, `getEndnoteBody`, `getFootnoteBody`, `importStylesFromJson`, `lockServerFile`, `makeCompatibilityDefault`, `manualHyphenation`, `post`, `presentIt`, `printPreview`, `redo`, `reload`, `reloadAs`, `removeLockedStyles`, `removeNumbers`, `removeTheme`, `repaginate`, `resetFormFields`, `returnToLastReadPosition`, `runAutoMacro`, `saveAsQuickStyleSet`, `select`, `selectContentControlsByTag`, `selectContentControlsByTitle`, `selectLinkedControls`, `selectNodes`, `selectSingleNode`, `selectUnlinkedControls`, `sendFax`, `sendMail`, `setDefaultTableStyle`, `setPasswordEncryptionOptions`, `toggleFormsDesign`, `transformDocument`, `undo`, `undoClear`, `updateStyles`, `viewCode`, `viewPropertyBrowser`, `webPagePreview`.

## Node additions

### `WordDocument.open()` (node)

```ts theme={null}
static open(path: string, options?: WordDocumentOptions): Promise<WordDocument>
```

Opens like `fromBytes`, so it starts or joins the document's billable Session too.

### `WordDocument.dispose()` (node)

```ts theme={null}
dispose(): Promise<void>
```

Extension: frees the layout engine's copy of this document now; GC frees it otherwise.
The document stays usable, and its next layout starts from scratch.

### `WordDocument.save()` (node)

```ts theme={null}
save(path: string): Promise<void>
```

Writes to `path`; OfficeJS never writes the source file in place by itself.

### `WordDocument.toPdf()` (node)

```ts theme={null}
toPdf(path?: string, options?: ToPdfOptions): Promise<Uint8Array<ArrayBufferLike>>
```

Lays out and paints the final view, or the review view asked for; writes `path` when given.

### `WordDocument.toPng()` (node)

```ts theme={null}
toPng(options?: ToPngOptions): Promise<RenderedPng[]>
```

One PNG per laid page (or per `pages`) of the final or the asked review view, as `toPdf` lays it.

## Browser additions

### `WordDocument.toPdf()` (browser)

```ts theme={null}
toPdf(
  options?: RenderPdfOptions & { fonts?: Pick<FaceProvider, "fetch"> },
): Promise<Uint8Array<ArrayBufferLike>>
```

Lays out the current edit state and paints it. Faces come through `fonts`,
by default the provider `browserLayoutHost` was installed with.

## `WordDocumentOptions`

How a WordDocument reaches laid pages and the user's selection. Omit `layout`
for the platform default. `selection` is read on every `getSelection()`, so a
host that owns an editor can hand over the live caret without a new handle.

Import from `@reductoai/docx/node`, `@reductoai/docx/officejs`.

| Name | Type | Description |
| - | - | - |
| `layout?` | `LayoutHost` | |
| `selection?` | `() => SelectionSpan \| null \| undefined` | |
