Word.Document class

The Document object is the top level object. A Document object contains one or more sections, content controls, and the body that contains the contents of the document.

Extends

Remarks

[ API set: WordApi 1.1 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-change-tracking.yaml

// Gets the current change tracking mode.
await Word.run(async (context) => {
  const document: Word.Document = context.document;
  document.load("changeTrackingMode");
  await context.sync();

  if (document.changeTrackingMode === Word.ChangeTrackingMode.trackMineOnly) {
    console.log("Only my changes are being tracked.");
  } else if (document.changeTrackingMode === Word.ChangeTrackingMode.trackAll) {
    console.log("Everyone's changes are being tracked.");
  } else {
    console.log("No changes are being tracked.");
  }
});

Properties

body

Gets the body object of the main document. The body is the text that excludes headers, footers, footnotes, textboxes, etc.

changeTrackingMode

Specifies the ChangeTracking mode.

contentControls

Gets the collection of content control objects in the document. This includes content controls in the body of the document, headers, footers, textboxes, etc.

context

The request context associated with the object. This connects the add-in's process to the Office host application's process.

customXmlParts

Gets the custom XML parts in the document.

properties

Gets the properties of the document.

saved

Indicates whether the changes in the document have been saved. A value of true indicates that the document hasn't changed since it was saved.

sections

Gets the collection of section objects in the document.

settings

Gets the add-in's settings in the document.

Methods

addStyle(name, type)

Adds a style into the document by name and type.

addStyle(name, typeString)

Adds a style into the document by name and type.

close(closeBehavior)

Closes the current document.

Note: This API isn't supported in Word on the web.

close(closeBehaviorString)

Closes the current document.

Note: This API isn't supported in Word on the web.

deleteBookmark(name)

Deletes a bookmark, if it exists, from the document.

getBookmarkRange(name)

Gets a bookmark's range. Throws an ItemNotFound error if the bookmark doesn't exist.

getBookmarkRangeOrNullObject(name)

Gets a bookmark's range. If the bookmark doesn't exist, then this method will return an object with its isNullObject property set to true. For further information, see *OrNullObject methods and properties.

getContentControls(options)

Gets the currently supported content controls in the document.

getEndnoteBody()

Gets the document's endnotes in a single body.

getFootnoteBody()

Gets the document's footnotes in a single body.

getSelection()

Gets the current selection of the document. Multiple selections aren't supported.

getStyles()

Gets a StyleCollection object that represents the whole style set of the document.

insertFileFromBase64(base64File, insertLocation, insertFileOptions)

Inserts a document into the target document at a specific location with additional properties. Headers, footers, watermarks, and other section properties are copied by default.

load(options)

Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties.

load(propertyNames)

Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties.

load(propertyNamesAndPaths)

Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties.

save(saveBehavior, fileName)

Saves the document.

save(saveBehaviorString, fileName)

Saves the document.

set(properties, options)

Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type.

set(properties)

Sets multiple properties on the object at the same time, based on an existing loaded object.

toJSON()

Overrides the JavaScript toJSON() method in order to provide more useful output when an API object is passed to JSON.stringify(). (JSON.stringify, in turn, calls the toJSON method of the object that is passed to it.) Whereas the original Word.Document object is an API object, the toJSON method returns a plain JavaScript object (typed as Word.Interfaces.DocumentData) that contains shallow copies of any loaded child properties from the original object.

track()

Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you're using this object across .sync calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you need to add the object to the tracked object collection when the object was first created. If this object is part of a collection, you should also track the parent collection.

untrack()

Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You'll need to call context.sync() before the memory release takes effect.

Events

onContentControlAdded

Occurs when a content control is added. Run context.sync() in the handler to get the new content control's properties.

Property Details

body

Gets the body object of the main document. The body is the text that excludes headers, footers, footnotes, textboxes, etc.

readonly body: Word.Body;

Property Value

Remarks

[ API set: WordApi 1.1 ]

changeTrackingMode

Specifies the ChangeTracking mode.

changeTrackingMode: Word.ChangeTrackingMode | "Off" | "TrackAll" | "TrackMineOnly";

Property Value

Word.ChangeTrackingMode | "Off" | "TrackAll" | "TrackMineOnly"

Remarks

[ API set: WordApi 1.4 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-change-tracking.yaml

// Gets the current change tracking mode.
await Word.run(async (context) => {
  const document: Word.Document = context.document;
  document.load("changeTrackingMode");
  await context.sync();

  if (document.changeTrackingMode === Word.ChangeTrackingMode.trackMineOnly) {
    console.log("Only my changes are being tracked.");
  } else if (document.changeTrackingMode === Word.ChangeTrackingMode.trackAll) {
    console.log("Everyone's changes are being tracked.");
  } else {
    console.log("No changes are being tracked.");
  }
});

contentControls

Gets the collection of content control objects in the document. This includes content controls in the body of the document, headers, footers, textboxes, etc.

readonly contentControls: Word.ContentControlCollection;

Property Value

Remarks

[ API set: WordApi 1.1 ]

context

The request context associated with the object. This connects the add-in's process to the Office host application's process.

context: RequestContext;

Property Value

customXmlParts

Gets the custom XML parts in the document.

readonly customXmlParts: Word.CustomXmlPartCollection;

Property Value

Remarks

[ API set: WordApi 1.4 ]

properties

Gets the properties of the document.

readonly properties: Word.DocumentProperties;

Property Value

Remarks

[ API set: WordApi 1.3 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/30-properties/get-built-in-properties.yaml

await Word.run(async (context) => {
    const builtInProperties: Word.DocumentProperties = context.document.properties;
    builtInProperties.load("*"); // Let's get all!

    await context.sync();
    console.log(JSON.stringify(builtInProperties, null, 4));
});

saved

Indicates whether the changes in the document have been saved. A value of true indicates that the document hasn't changed since it was saved.

readonly saved: boolean;

Property Value

boolean

Remarks

[ API set: WordApi 1.1 ]

sections

Gets the collection of section objects in the document.

readonly sections: Word.SectionCollection;

Property Value

Remarks

[ API set: WordApi 1.1 ]

settings

Gets the add-in's settings in the document.

readonly settings: Word.SettingCollection;

Property Value

Remarks

[ API set: WordApi 1.4 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-settings.yaml

// Gets all custom settings this add-in set on this document.
await Word.run(async (context) => {
  const settings: Word.SettingCollection = context.document.settings;
  settings.load("items");
  await context.sync();

  if (settings.items.length == 0) {
    console.log("There are no settings.");
  } else {
    console.log("All settings:");
    for (let i = 0; i < settings.items.length; i++) {
      console.log(settings.items[i]);
    }
  }
});

Method Details

addStyle(name, type)

Adds a style into the document by name and type.

addStyle(name: string, type: Word.StyleType): Word.Style;

Parameters

name

string

Required. A string representing the style name.

type
Word.StyleType

Required. The style type, including character, list, paragraph, or table.

Returns

Remarks

[ API set: WordApi 1.5 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-styles.yaml

// Adds a new style.
await Word.run(async (context) => {
  const newStyleName = $("#new-style-name").val() as string;
  if (newStyleName == "") {
    console.warn("Enter a style name to add.");
    return;
  }

  const style: Word.Style = context.document.getStyles().getByNameOrNullObject(newStyleName);
  style.load();
  await context.sync();

  if (!style.isNullObject) {
    console.warn(
      `There's an existing style with the same name '${newStyleName}'! Please provide another style name.`
    );
    return;
  }

  const newStyleType = ($("#new-style-type").val() as unknown) as Word.StyleType;
  context.document.addStyle(newStyleName, newStyleType);
  await context.sync();
  
  console.log(newStyleName + " has been added to the style list.");
});

addStyle(name, typeString)

Adds a style into the document by name and type.

addStyle(name: string, typeString: "Character" | "List" | "Paragraph" | "Table"): Word.Style;

Parameters

name

string

Required. A string representing the style name.

typeString

"Character" | "List" | "Paragraph" | "Table"

Required. The style type, including character, list, paragraph, or table.

Returns

Remarks

[ API set: WordApi 1.5 ]

close(closeBehavior)

Closes the current document.

Note: This API isn't supported in Word on the web.

close(closeBehavior?: Word.CloseBehavior): void;

Parameters

closeBehavior
Word.CloseBehavior

Optional. The close behavior must be 'Save' or 'SkipSave'. Default value is 'Save'.

Returns

void

Remarks

[ API set: WordApi 1.5 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/save-close.yaml

// Closes the document with default behavior
// for current state of the document.
await Word.run(async (context) => {
  context.document.close();
});

close(closeBehaviorString)

Closes the current document.

Note: This API isn't supported in Word on the web.

close(closeBehaviorString?: "Save" | "SkipSave"): void;

Parameters

closeBehaviorString

"Save" | "SkipSave"

Optional. The close behavior must be 'Save' or 'SkipSave'. Default value is 'Save'.

Returns

void

Remarks

[ API set: WordApi 1.5 ]

deleteBookmark(name)

Deletes a bookmark, if it exists, from the document.

deleteBookmark(name: string): void;

Parameters

name

string

Required. The case-insensitive bookmark name.

Returns

void

Remarks

[ API set: WordApi 1.4 ]

getBookmarkRange(name)

Gets a bookmark's range. Throws an ItemNotFound error if the bookmark doesn't exist.

getBookmarkRange(name: string): Word.Range;

Parameters

name

string

Required. The case-insensitive bookmark name.

Returns

Remarks

[ API set: WordApi 1.4 ]

getBookmarkRangeOrNullObject(name)

Gets a bookmark's range. If the bookmark doesn't exist, then this method will return an object with its isNullObject property set to true. For further information, see *OrNullObject methods and properties.

getBookmarkRangeOrNullObject(name: string): Word.Range;

Parameters

name

string

Required. The case-insensitive bookmark name.

Returns

Remarks

[ API set: WordApi 1.4 ]

getContentControls(options)

Gets the currently supported content controls in the document.

getContentControls(options?: Word.ContentControlOptions): Word.ContentControlCollection;

Parameters

options
Word.ContentControlOptions

Optional. Options that define which content controls are returned.

Returns

Remarks

[ API set: WordApi 1.5 ]

Important: If specific types are provided in the options parameter, only content controls of supported types are returned. Be aware that an exception will be thrown on using methods of a generic Word.ContentControl that aren't relevant for the specific type. With time, additional types of content controls may be supported. Therefore, your add-in should request and handle specific types of content controls.

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/insert-and-change-checkbox-content-control.yaml

// Toggles the isChecked property on all checkbox content controls.
await Word.run(async (context) => {
  let contentControls = context.document.getContentControls({
    types: [Word.ContentControlType.checkBox]
  });
  contentControls.load("items");

  await context.sync();

  const length = contentControls.items.length;
  console.log(`Number of checkbox content controls: ${length}`);

  if (length <= 0) {
    return;
  }

  const checkboxContentControls = [];
  for (let i = 0; i < length; i++) {
    let contentControl = contentControls.items[i];
    contentControl.load("id,checkboxContentControl/isChecked");
    checkboxContentControls.push(contentControl);
  }

  await context.sync();

  console.log("isChecked state before:");
  const updatedCheckboxContentControls = [];
  for (let i = 0; i < checkboxContentControls.length; i++) {
    const currentCheckboxContentControl = checkboxContentControls[i];
    const isCheckedBefore = currentCheckboxContentControl.checkboxContentControl.isChecked;
    console.log(`id: ${currentCheckboxContentControl.id} ... isChecked: ${isCheckedBefore}`);

    currentCheckboxContentControl.checkboxContentControl.isChecked = !isCheckedBefore;
    currentCheckboxContentControl.load("id,checkboxContentControl/isChecked");
    updatedCheckboxContentControls.push(currentCheckboxContentControl);
  }

  await context.sync();

  console.log("isChecked state after:");
  for (let i = 0; i < updatedCheckboxContentControls.length; i++) {
    const currentCheckboxContentControl = updatedCheckboxContentControls[i];
    console.log(
      `id: ${currentCheckboxContentControl.id} ... isChecked: ${currentCheckboxContentControl.checkboxContentControl.isChecked}`
    );
  }
});

getEndnoteBody()

Gets the document's endnotes in a single body.

getEndnoteBody(): Word.Body;

Returns

Remarks

[ API set: WordApi 1.5 ]

getFootnoteBody()

Gets the document's footnotes in a single body.

getFootnoteBody(): Word.Body;

Returns

Remarks

[ API set: WordApi 1.5 ]

getSelection()

Gets the current selection of the document. Multiple selections aren't supported.

getSelection(): Word.Range;

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    const textSample = 'This is an example of the insert text method. This is a method ' + 
        'which allows users to insert text into a selection. It can insert text into a ' +
        'relative location or it can overwrite the current selection. Since the ' +
        'getSelection method returns a range object, look up the range object documentation ' +
        'for everything you can do with a selection.';
    
    // Create a range proxy object for the current selection.
    const range = context.document.getSelection();
    
    // Queue a command to insert text at the end of the selection.
    range.insertText(textSample, Word.InsertLocation.end);
    
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Inserted the text at the end of the selection.');
});  

getStyles()

Gets a StyleCollection object that represents the whole style set of the document.

getStyles(): Word.StyleCollection;

Returns

Remarks

[ API set: WordApi 1.5 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-styles.yaml

// Gets the number of styles.
await Word.run(async (context) => {
  const styles: Word.StyleCollection = context.document.getStyles();
  const count = styles.getCount();
  await context.sync();

  console.log(`Number of styles: ${count.value}`);
});

insertFileFromBase64(base64File, insertLocation, insertFileOptions)

Inserts a document into the target document at a specific location with additional properties. Headers, footers, watermarks, and other section properties are copied by default.

insertFileFromBase64(base64File: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End", insertFileOptions?: Word.InsertFileOptions): Word.SectionCollection;

Parameters

base64File

string

Required. The Base64-encoded content of a .docx file.

insertLocation

replace | start | end | "Replace" | "Start" | "End"

Required. The value must be 'Replace', 'Start', or 'End'.

insertFileOptions
Word.InsertFileOptions

Optional. The additional properties that should be imported to the destination document.

Returns

Remarks

[ API set: WordApi 1.5 ]

Note: Insertion isn't supported if the document being inserted contains an ActiveX control (likely in a form field). Consider replacing such a form field with a content control or other option appropriate for your scenario.

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/insert-external-document.yaml

// Inserts content (applying selected settings) from another document passed in as a Base64-encoded string.
await Word.run(async (context) => {
  // Use the Base64-encoded string representation of the selected .docx file.
  context.document.insertFileFromBase64(externalDocument, "Replace", {
    importTheme: true,
    importStyles: true,
    importParagraphSpacing: true,
    importPageColor: true,
    importChangeTrackingMode: true,
    importCustomProperties: true,
    importCustomXmlParts: true,
    importDifferentOddEvenPages: true
  });
  await context.sync();
});

load(options)

Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties.

load(options?: Word.Interfaces.DocumentLoadOptions): Word.Document;

Parameters

options
Word.Interfaces.DocumentLoadOptions

Provides options for which properties of the object to load.

Returns

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the document.
    const thisDocument = context.document;
    
    // Queue a command to load content control properties.
    thisDocument.load('contentControls/id, contentControls/text, contentControls/tag');
    
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (thisDocument.contentControls.items.length !== 0) {
        for (let i = 0; i < thisDocument.contentControls.items.length; i++) {
            console.log(thisDocument.contentControls.items[i].id);
            console.log(thisDocument.contentControls.items[i].text);
            console.log(thisDocument.contentControls.items[i].tag);
        }
    } else {
        console.log('No content controls in this document.');
    }
});

load(propertyNames)

Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties.

load(propertyNames?: string | string[]): Word.Document;

Parameters

propertyNames

string | string[]

A comma-delimited string or an array of strings that specify the properties to load.

Returns

load(propertyNamesAndPaths)

Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties.

load(propertyNamesAndPaths?: {
            select?: string;
            expand?: string;
        }): Word.Document;

Parameters

propertyNamesAndPaths

{ select?: string; expand?: string; }

propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load.

Returns

save(saveBehavior, fileName)

Saves the document.

save(saveBehavior?: Word.SaveBehavior, fileName?: string): void;

Parameters

saveBehavior
Word.SaveBehavior

Optional. The save behavior must be 'Save' or 'Prompt'. Default value is 'Save'.

fileName

string

Optional. The file name (exclude file extension). Only takes effect for a new document.

Returns

void

Remarks

[ API set: WordApi 1.1 ]

Note: The saveBehavior and fileName parameters were introduced in WordApi 1.5.

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the document.
    const thisDocument = context.document;

    // Queue a command to load the document save state (on the saved property).
    thisDocument.load('saved');    
    
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
        
    if (thisDocument.saved === false) {
        // Queue a command to save this document.
        thisDocument.save();
        
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Saved the document');
    } else {
        console.log('The document has not changed since the last save.');
    }
});
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/save-close.yaml

// Saves the document with default behavior
// for current state of the document.
await Word.run(async (context) => {
  context.document.save();
  await context.sync();
});

save(saveBehaviorString, fileName)

Saves the document.

save(saveBehaviorString?: "Save" | "Prompt", fileName?: string): void;

Parameters

saveBehaviorString

"Save" | "Prompt"

Optional. The save behavior must be 'Save' or 'Prompt'. Default value is 'Save'.

fileName

string

Optional. The file name (exclude file extension). Only takes effect for a new document.

Returns

void

Remarks

[ API set: WordApi 1.1 ]

Note: The saveBehavior and fileName parameters were introduced in WordApi 1.5.

set(properties, options)

Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type.

set(properties: Interfaces.DocumentUpdateData, options?: OfficeExtension.UpdateOptions): void;

Parameters

properties
Word.Interfaces.DocumentUpdateData

A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called.

options
OfficeExtension.UpdateOptions

Provides an option to suppress errors if the properties object tries to set any read-only properties.

Returns

void

set(properties)

Sets multiple properties on the object at the same time, based on an existing loaded object.

set(properties: Word.Document): void;

Parameters

properties
Word.Document

Returns

void

toJSON()

Overrides the JavaScript toJSON() method in order to provide more useful output when an API object is passed to JSON.stringify(). (JSON.stringify, in turn, calls the toJSON method of the object that is passed to it.) Whereas the original Word.Document object is an API object, the toJSON method returns a plain JavaScript object (typed as Word.Interfaces.DocumentData) that contains shallow copies of any loaded child properties from the original object.

toJSON(): Word.Interfaces.DocumentData;

Returns

track()

Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you're using this object across .sync calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you need to add the object to the tracked object collection when the object was first created. If this object is part of a collection, you should also track the parent collection.

track(): Word.Document;

Returns

untrack()

Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You'll need to call context.sync() before the memory release takes effect.

untrack(): Word.Document;

Returns

Event Details

onContentControlAdded

Occurs when a content control is added. Run context.sync() in the handler to get the new content control's properties.

readonly onContentControlAdded: OfficeExtension.EventHandlers<Word.ContentControlAddedEventArgs>;

Event Type

Remarks

[ API set: WordApi 1.5 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/content-control-onadded-event.yaml

// Registers the onAdded event handler on the document.
await Word.run(async (context) => {
  eventContext = context.document.onContentControlAdded.add(contentControlAdded);
  await context.sync();

  console.log("Added event handler for when content controls are added.");
});

...

async function contentControlAdded(event: Word.ContentControlAddedEventArgs) {
  await Word.run(async (context) => {
    console.log(`${event.eventType} event detected. IDs of content controls that were added:`, event.ids);
  });
}