Edit

Share via


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

activeTheme

Gets the name of the active theme and formatting options.

activeThemeDisplayName

Gets the display name of the active theme.

activeWindow

Gets the active window for the document.

areFilePropertiesPasswordEncrypted

Gets whether Word encrypts file properties for password-protected documents.

areGrammaticalErrorsShown

Specifies whether grammatical errors are marked by a wavy green line in the document.

areMathDefaultsUsed

Specifies whether to use the default math settings when creating new equations.

areNewerFeaturesDisabled

Specifies whether to disable features introduced after a specified version.

areSpellingErrorsShown

Specifies whether Microsoft Word underlines spelling errors in the document.

areStylesUpdatedOnOpen

Specifies whether the styles in this document are updated to match the styles in the attached template each time the document is opened.

areTrueTypeFontsEmbedded

Specifies whether Microsoft Word embeds TrueType fonts in the document when it's saved.

attachedTemplate

Specifies a Template object that represents the template attached to the document.

autoHyphenation

Specifies if automatic hyphenation is turned on for the document.

autoSaveOn

Specifies if the edits in the document are automatically saved.

background

Gets a Shape object that represents the background image for the document.

bibliography

Returns a Bibliography object that represents the bibliography references contained within the document.

body

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

bookmarks

Returns a BookmarkCollection object that represents all the bookmarks in the document.

builtInDocumentProperties

Gets a DocumentProperties object that represents all the built-in document properties for the document.

changeTrackingMode

Specifies the ChangeTracking mode.

characters

Gets the RangeScopedCollection object that represents all the characters in the document.

coauthoring

Gets a Coauthoring object for managing coauthoring in the document.

codeName

Gets the code name for the document.

comments

Gets a CommentCollection object that represents all the comments in the document.

compatibilityMode

Gets the compatibility mode that Word uses when opening the document.

consecutiveHyphensLimit

Specifies the maximum number of consecutive lines that can end with hyphens.

content

Gets a Range object that represents the main document story.

contentControls

Gets the collection of ContentControl 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.

currentRsid

Gets a random number that Word assigns to changes in the document.

customDocumentProperties

Gets a DocumentProperties collection that represents all the custom document properties for the document.

customXmlParts

Gets the custom XML parts in the document.

defaultTabStop

Specifies the interval (in points) between the default tab stops in the document.

defaultTargetFrame

Specifies the browser frame for displaying a webpage via hyperlink.

documentLibraryVersions

Returns a DocumentLibraryVersionCollection object that represents the collection of versions of a shared document that has versioning enabled and that's stored in a document library on a server.

doNotEmbedSystemFonts

Specifies whether Word should not embed common system fonts.

encryptionProvider

Specifies the name of the algorithm encryption provider that Microsoft Word uses when encrypting documents.

farEastLineBreakLanguage

Specifies the East Asian language used for line breaking.

farEastLineBreakLevel

Specifies the line break control level.

fields

Gets a FieldCollection object that represents all the fields in the document.

formattingIsNextLevelShown

Specifies whether Word shows the next heading level when the previous is used.

formattingIsUserStyleNameShown

Specifies whether to show user-defined styles.

frames

Returns a FrameCollection object that represents all the frames in the document.

fullName

Gets the name of a document, including the path.

grammaticalErrors

Gets a RangeCollection object that represents the sentences that failed the grammar check in the document.

gridDistanceHorizontal

Specifies the horizontal space between invisible gridlines that Microsoft Word uses when you draw, move, and resize AutoShapes or East Asian characters in the document.

gridDistanceVertical

Specifies the vertical space between invisible gridlines that Microsoft Word uses when you draw, move, and resize AutoShapes or East Asian characters in the document.

gridIsOriginFromMargin

Specifies whether the character grid starts from the upper-left corner of the page.

gridOriginHorizontal

Specifies the horizontal origin point for the invisible grid.

gridOriginVertical

Specifies the vertical origin point for the invisible grid.

gridSpaceBetweenHorizontalLines

Specifies the interval for horizontal character gridlines in print layout view.

gridSpaceBetweenVerticalLines

Specifies the interval for vertical character gridlines in print layout view.

hasPassword

Gets whether a password is required to open the document.

hasVbProject

Gets whether the document has an attached Microsoft Visual Basic for Applications project.

hyperlinks

Returns a HyperlinkCollection object that represents all the hyperlinks in the document.

hyphenateCaps

Specifies whether words in all capital letters can be hyphenated.

hyphenationZone

Specifies the width of the hyphenation zone, in points.

indexes

Returns an IndexCollection object that represents all the indexes in the document.

isAutoFormatOverrideOn

Specifies whether automatic formatting options override formatting restrictions.

isChartDataPointTracked

Specifies whether charts in the active document use cell-reference data-point tracking.

isCompatible

Specifies whether the compatibility option specified by the type property is enabled.

isFinal

Specifies whether the document is final.

isFontsSubsetSaved

Specifies whether Microsoft Word saves a subset of the embedded TrueType fonts with the document.

isFormsDataPrinted

Specifies whether Microsoft Word prints onto a preprinted form only the data entered in the corresponding online form.

isFormsDataSaved

Specifies whether Microsoft Word saves the data entered in a form as a tab-delimited record for use in a database.

isGrammarChecked

Specifies whether a grammar check has been run on the document.

isInAutoSave

Gets whether the most recent firing of the Application.DocumentBeforeSave event was the result of an automatic save by the document or a manual save by the user.

isInFormsDesign

Gets whether the document is in form design mode.

isKerningByAlgorithm

Specifies whether Word kerns half-width Latin characters and punctuation marks.

isLinguisticDataEmbedded

Specifies whether to embed speech and handwriting data.

isMasterDocument

Gets whether this document is a master document.

isOptimizedForWord97

Specifies whether Word optimizes the document for Word 97.

isPostScriptPrintedOverText

Specifies whether PRINT field instructions (such as PostScript commands) in the document are to be printed on top of text and graphics when a PostScript printer is used.

isQuickStyleSetLocked

Specifies whether users can change the Quick Style set.

isReadOnly

Gets whether changes to the document cannot be saved to the original document.

isReadOnlyRecommended

Specifies whether Microsoft Word displays a message box whenever a user opens the document, suggesting that it be opened as read-only.

isSnappedToGrid

Specifies whether AutoShapes or East Asian characters are automatically aligned with an invisible grid.

isSnappedToShapes

Specifies whether AutoShapes or East Asian characters align with invisible gridlines through other shapes.

isSpellingChecked

Specifies whether spelling has been checked throughout the document.

isStyleEnforced

Specifies whether formatting restrictions are enforced in a protected document.

isSubdocument

Gets whether this document is a subdocument of a master document.

isThemeLocked

Specifies whether users can change the document theme.

isUserControl

Specifies whether the document was created or opened by the user.

isVbaSigned

Gets whether the VBA project is digitally signed.

isWriteReserved

Gets whether the document is protected with a write password.

justificationMode

Specifies the character spacing adjustment.

kind

Specifies the format type that Microsoft Word uses when automatically formatting the document.

languageDetected

Specifies whether Microsoft Word has detected the language of the document text.

listParagraphs

Gets a ParagraphCollection object that represents all the numbered paragraphs in the document.

lists

Gets a ListCollection object that contains all the formatted lists in the document.

listTemplates

Returns a ListTemplateCollection object that represents all the list templates in the document.

noLineBreakAfter

Specifies the kinsoku characters after which Word will not break a line.

noLineBreakBefore

Specifies the kinsoku characters before which Word will not break a line.

openEncoding

Gets the encoding used to open the document.

originalDocumentTitle

Gets the title of the original document after legal-blackline comparison.

pageSetup

Returns a PageSetup object that's associated with the document.

paragraphs

Gets a ParagraphCollection object that represents all the paragraphs in the document.

password

Sets a password that must be supplied to open the document.

passwordEncryptionAlgorithm

Gets the algorithm used for password encryption.

passwordEncryptionKeyLength

Gets the key length used for password encryption.

passwordEncryptionProvider

Gets the name of the password encryption provider.

path

Gets the disk or the web path to the document (excludes the document name).

printRevisions

Specifies whether revision marks are printed with the document.

properties

Gets the properties of the document.

protectionType

Gets the protection type for the document.

readabilityStatistics

Gets a ReadabilityStatisticCollection object that represents the readability statistics for the document.

readingLayoutSizeX

Specifies the width of pages in reading layout view when frozen.

readingLayoutSizeY

Specifies the height of pages in reading layout view when frozen.

readingModeIsLayoutFrozen

Specifies whether pages in reading layout view are frozen for handwritten markup.

removePersonalInformationOnSave

Specifies whether Word removes user information upon saving.

revisedDocumentTitle

Gets the title of the revised document after legal-blackline comparison.

revisions

Gets the collection of revisions that represents the tracked changes in 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.

saveEncoding

Specifies the encoding used when saving the document.

saveFormat

Gets the file format of the document.

sections

Gets the collection of Section objects in the document.

selection

Returns a Selection object that represents the current selection in the document.

sentences

Gets the RangeScopedCollection object that represents all the sentences in the document.

settings

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

spellingErrors

Gets a RangeCollection object that represents the words identified as spelling errors in the document.

storyRanges

Gets a RangeCollection object that represents all the stories in the document.

styles

Gets a StyleCollection for the document.

tableOfAuthoritiesCategories

Returns a TableOfAuthoritiesCategoryCollection object that represents the available table of authorities categories in the document.

tables

Gets a TableCollection object that represents all the tables in the document.

tablesOfAuthorities

Returns a TableOfAuthoritiesCollection object that represents all the tables of authorities in the document.

tablesOfContents

Returns a TableOfContentsCollection object that represents all the tables of contents in the document.

tablesOfFigures

Returns a TableOfFiguresCollection object that represents all the tables of figures in the document.

textEncoding

Specifies the encoding for saving as encoded text.

textLineEnding

Specifies how Word marks line and paragraph breaks in text files.

trackedChangesAreDateAndTimeRemoved

Specifies whether to remove or store date and time metadata for tracked changes.

trackFormatting

Specifies whether to track formatting changes when change tracking is on.

trackMoves

Specifies whether to mark moved text when Track Changes is on.

trackRevisions

Specifies whether changes are tracked in the document.

type

Gets the document type (template or document).

webSettings

Gets the WebSettings object for webpage-related attributes.

windows

Gets the collection of Word.Window objects for the document.

words

Gets the RangeScopedCollection object that represents each word in the document.

writePassword

Sets a password for saving changes to the document.

xmlAreAdvancedErrorsShown

Specifies whether error messages are generated from built-in Word messages or MSXML (Microsoft XML).

xmlIsXsltUsedWhenSaving

Specifies whether to save a document through an Extensible Stylesheet Language Transformation (XSLT).

xmlSaveThroughXslt

Specifies the path and file name for the XSLT to apply when saving a document.

Methods

acceptAllRevisions()

Accepts all tracked changes in the document.

acceptAllRevisionsShown()

Accepts all revisions in the document that are displayed on the screen.

activate()

Activates the document so that it becomes the active document.

addStyle(name, type)

Adds a style into the document by name and type.

addStyle(name, type)

Adds a style into the document by name and type.

addToFavorites()

Creates a shortcut to the document or hyperlink and adds it to the Favorites folder.

applyQuickStyleSet(style)

Applies the specified Quick Style set to the document.

applyQuickStyleSet(style)

Applies the specified Quick Style set to the document.

applyTheme(name)

Applies the specified theme to this document.

autoFormat()

Automatically formats the document.

canCheckin()

Returns true if Microsoft Word can check in the document to a server.

checkConsistencyJapanese()

Searches all text in a Japanese language document and displays instances where character usage is inconsistent for the same words.

checkGrammar()

Begins a spelling and grammar check for the document.

checkIn(options)

Checks in the document from the local computer to a server and sets the local document to read-only so that it cannot be edited locally.

checkInWithVersion(options)

Saves the document to a server from a local computer, and sets the local document to read-only so that it cannot be edited locally.

checkSpelling(options)

Begins a spelling check for the document.

close(closeBehavior)

Closes the current document.

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

close(closeBehavior)

Closes the current document.

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

closePrintPreview()

Switches the document from print preview to the previous view.

compare(filePath, documentCompareOptions)

Displays revision marks that indicate where the specified document differs from another document.

compareFromBase64(base64File, documentCompareOptions)

Displays revision marks that indicate where the specified document differs from another document.

computeStatistics(statistic, includeFootnotesAndEndnotes)

Returns a statistic based on the contents of the document.

computeStatistics(statistic, includeFootnotesAndEndnotes)

Returns a statistic based on the contents of the document.

convert()

Converts the file to the newest format and enables all features.

convertAutoHyphens()

Converts automatic hyphens to manual hyphens.

convertNumbersToText(numberType)

Changes the list numbers and LISTNUM fields in the document to text.

convertNumbersToText(numberType)

Changes the list numbers and LISTNUM fields in the document to text.

convertVietnameseDocument(codePageOrigin)

Reconverts a Vietnamese document to Unicode using a code page other than the default.

copyStylesFromTemplate(StyleTemplate)

Copies styles from the specified template to the document.

countNumberedItems(options)

Returns the number of bulleted or numbered items and LISTNUM fields in the document.

deleteAllComments()

Deletes all comments from the document.

deleteAllCommentsShown()

Deletes all revisions in the document that are displayed on the screen.

deleteAllInkAnnotations()

Deletes all handwritten ink annotations in the document.

deleteBookmark(name)

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

detectLanguage()

Analyzes the document text to determine the language.

endReview(options)

Terminates a review of the file that has been sent for review.

exportAsFixedFormat(outputFileName, exportFormat, options)

Saves the document in PDF or XPS format.

exportAsFixedFormat(outputFileName, exportFormat, options)

Saves the document in PDF or XPS format.

exportAsFixedFormat2(outputFileName, exportFormat, options)

Saves the document in PDF or XPS format.

exportAsFixedFormat2(outputFileName, exportFormat, options)

Saves the document in PDF or XPS format.

exportAsFixedFormat3(outputFileName, exportFormat, options)

Saves the document in PDF or XPS format with improved tagging.

exportAsFixedFormat3(outputFileName, exportFormat, options)

Saves the document in PDF or XPS format with improved tagging.

fitToPages()

Decreases the font size of text just enough so that the document page count drops by one.

followHyperlink(options)

Displays a cached document, if it has already been downloaded. Otherwise, this method resolves the hyperlink, downloads the target document, and displays the document in the appropriate application.

freezeLayout()

Fixes the layout of the document in Web view.

getAnnotationById(id)

Gets the annotation by ID. Throws an ItemNotFound error if annotation isn't found.

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.

getCrossReferenceItems(referenceType)

Returns an array of items that can be cross-referenced based on the specified cross-reference type.

getCrossReferenceItems(referenceType)

Returns an array of items that can be cross-referenced based on the specified cross-reference type.

getEndnoteBody()

Gets the document's endnotes in a single body.

getFootnoteBody()

Gets the document's footnotes in a single body.

getParagraphByUniqueLocalId(id)

Gets the paragraph by its unique local ID. Throws an ItemNotFound error if the collection is empty.

getRange(options)

Returns a Range object by using the specified starting and ending character positions.

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.

goTo(options)

Returns a Range object that represents the start position of the specified item, such as a page, bookmark, or field.

importStylesFromJson(stylesJson, importedStylesConflictBehavior)

Import styles from a JSON-formatted string.

importStylesFromJson(stylesJson, importedStylesConflictBehavior)

Import styles from a JSON-formatted string.

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.

lockServerFile()

Locks the file on the server preventing anyone else from editing it.

makeCompatibilityDefault()

Sets the compatibility options.

manualHyphenation()

Initiates manual hyphenation of a document, one line at a time.

merge(fileName, options)

Merges the changes marked with revision marks from one document to another.

post()

Posts the document to a public folder in Microsoft Exchange.

presentIt()

Opens PowerPoint with the Word document loaded.

printOut(options)

Prints all or part of the document.

printPreview()

Switches the view to print preview.

protect(type, options)

Protects the document from unauthorized changes.

protect(type, options)

Protects the document from unauthorized changes.

redo(times)

Redoes the last action that was undone (reverses the undo method).

rejectAllRevisions()

Rejects all tracked changes in the document.

rejectAllRevisionsShown()

Rejects all revisions in the document that are displayed on the screen.

reload()

Reloads a cached document by resolving the hyperlink to the document and downloading it.

reloadAs(encoding)

Reloads the document based on an HTML document, using the document encoding.

reloadAs(encoding)

Reloads the document based on an HTML document, using the document encoding.

removeDocumentInformation(removeDocInfoType)

Removes sensitive information, properties, comments, and other metadata from the document.

removeDocumentInformation(removeDocInfoType)

Removes sensitive information, properties, comments, and other metadata from the document.

removeLockedStyles()

Purges the document of locked styles when formatting restrictions have been applied in the document.

removeNumbers(numberType)

Removes numbers or bullets from the document.

removeNumbers(numberType)

Removes numbers or bullets from the document.

removeTheme()

Removes the active theme from the current document.

repaginate()

Repaginates the entire document.

replyWithChanges(options)

Sends an email message to the author of the document that has been sent out for review, notifying them that a reviewer has completed review of the document.

resetFormFields()

Clears all form fields in the document, preparing the form to be filled in again.

returnToLastReadPosition()

Returns the document to the last saved reading position.

runAutoMacro(autoMacro)

Runs an auto macro that's stored in the document. If the specified auto macro doesn't exist, nothing happens.

runAutoMacro(autoMacro)

Runs an auto macro that's stored in the document. If the specified auto macro doesn't exist, nothing happens.

save(saveBehavior, fileName)

Saves the document.

save(saveBehavior, fileName)

Saves the document.

saveAsQuickStyleSet(fileName)

Saves the group of quick styles currently in use.

search(searchText, searchOptions)

Performs a search with the specified search options on the scope of the whole document. The search results are a collection of Range objects.

select()

Selects the contents of the document.

selectContentControlsByTag(tag)

Returns all content controls with the specified tag.

selectContentControlsByTitle(title)

Returns a ContentControlCollection object that represents all the content controls in the document with the specified title.

selectLinkedControls(node)

Returns a ContentControlCollection object that represents all content controls in the document that are linked to the specific custom XML node.

selectNodes(xPath, options)

Returns an XmlNodeCollection object that represents all the nodes that match the XPath parameter in the order in which they appear in the document.

selectSingleNode(xPath, options)

Returns an XmlNode object that represents the first node that matches the XPath parameter in the document.

selectUnlinkedControls(stream)

Returns a ContentControlCollection object that represents all content controls in the document that are not linked to an XML node.

sendFax(address, subject)

Sends the document as a fax, without any user interaction.

sendFaxOverInternet(options)

Sends the document to a fax service provider, who faxes the document to one or more specified recipients.

sendForReview(options)

Sends the document in an email message for review by the specified recipients.

sendMail()

Opens a message window for sending the document through Microsoft Exchange.

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.

setDefaultTableStyle(style, setInTemplate)

Specifies the table style to use for newly created tables in the document.

setPasswordEncryptionOptions(passwordEncryptionProvider, passwordEncryptionAlgorithm, passwordEncryptionKeyLength, passwordEncryptFileProperties)

Sets the options Microsoft Word uses for encrypting documents with passwords.

toggleFormsDesign()

Switches form design mode on or off.

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's 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.

transformDocument(path, dataOnly)

Applies the specified Extensible Stylesheet Language Transformation (XSLT) file to this document and replaces the document with the results.

undo(times)

Undoes the last action or a sequence of actions, which are displayed in the Undo list.

undoClear()

Clears the list of actions that can be undone in the document.

unprotect(password)

Removes protection from the document.

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.

updateStyles()

Copies all styles from the attached template into the document, overwriting any existing styles in the document that have the same name.

viewCode()

Displays the code window for the selected Microsoft ActiveX control in the document.

viewPropertyBrowser()

Displays the property window for the selected Microsoft ActiveX control in the document.

webPagePreview()

Displays a preview of the current document as it would look if saved as a webpage.

Events

onAnnotationClicked

Occurs when the user clicks an annotation (or selects it using Alt+Down).

onAnnotationHovered

Occurs when the user hovers the cursor over an annotation.

onAnnotationInserted

Occurs when the user adds one or more annotations.

onAnnotationPopupAction

Occurs when the user performs an action in an annotation pop-up menu.

onAnnotationRemoved

Occurs when the user deletes one or more annotations.

onContentControlAdded

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

onParagraphAdded

Occurs when the user adds new paragraphs.

onParagraphChanged

Occurs when the user changes paragraphs.

onParagraphDeleted

Occurs when the user deletes paragraphs.

Property Details

activeTheme

Gets the name of the active theme and formatting options.

readonly activeTheme: string;

Property Value

string

Remarks

[ API set: WordApiDesktop 1.4 ]

activeThemeDisplayName

Gets the display name of the active theme.

readonly activeThemeDisplayName: string;

Property Value

string

Remarks

[ API set: WordApiDesktop 1.4 ]

activeWindow

Gets the active window for the document.

readonly activeWindow: Word.Window;

Property Value

Remarks

[ API set: WordApiDesktop 1.2 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/get-pages.yaml

await Word.run(async (context) => {
  // Gets the first paragraph of each page.
  console.log("Getting first paragraph of each page...");

  // Get the active window.
  const activeWindow: Word.Window = context.document.activeWindow;
  activeWindow.load();

  // Get the active pane.
  const activePane: Word.Pane = activeWindow.activePane;
  activePane.load();

  // Get all pages.
  const pages: Word.PageCollection = activePane.pages;
  pages.load();

  await context.sync();

  // Get page index and paragraphs of each page.
  const pagesIndexes = [];
  const pagesNumberOfParagraphs = [];
  const pagesFirstParagraphText = [];
  for (let i = 0; i < pages.items.length; i++) {
    const page = pages.items[i];
    page.load("index");
    pagesIndexes.push(page);

    const paragraphs = page.getRange().paragraphs;
    paragraphs.load("items/length");
    pagesNumberOfParagraphs.push(paragraphs);

    const firstParagraph = paragraphs.getFirst();
    firstParagraph.load("text");
    pagesFirstParagraphText.push(firstParagraph);
  }

  await context.sync();

  for (let i = 0; i < pagesIndexes.length; i++) {
    console.log(`Page index: ${pagesIndexes[i].index}`);
    console.log(`Number of paragraphs: ${pagesNumberOfParagraphs[i].items.length}`);
    console.log("First paragraph's text:", pagesFirstParagraphText[i].text);
  }
});

areFilePropertiesPasswordEncrypted

Gets whether Word encrypts file properties for password-protected documents.

readonly areFilePropertiesPasswordEncrypted: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

areGrammaticalErrorsShown

Specifies whether grammatical errors are marked by a wavy green line in the document.

areGrammaticalErrorsShown: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

areMathDefaultsUsed

Specifies whether to use the default math settings when creating new equations.

areMathDefaultsUsed: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

areNewerFeaturesDisabled

Specifies whether to disable features introduced after a specified version.

areNewerFeaturesDisabled: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

areSpellingErrorsShown

Specifies whether Microsoft Word underlines spelling errors in the document.

areSpellingErrorsShown: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

areStylesUpdatedOnOpen

Specifies whether the styles in this document are updated to match the styles in the attached template each time the document is opened.

areStylesUpdatedOnOpen: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

areTrueTypeFontsEmbedded

Specifies whether Microsoft Word embeds TrueType fonts in the document when it's saved.

areTrueTypeFontsEmbedded: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

attachedTemplate

Specifies a Template object that represents the template attached to the document.

attachedTemplate: Word.Template;

Property Value

Remarks

[ API set: WordApiDesktop 1.3 ]

autoHyphenation

Specifies if automatic hyphenation is turned on for the document.

autoHyphenation: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.3 ]

autoSaveOn

Specifies if the edits in the document are automatically saved.

autoSaveOn: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.3 ]

background

Gets a Shape object that represents the background image for the document.

readonly background: Word.Shape;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

bibliography

Returns a Bibliography object that represents the bibliography references contained within the document.

readonly bibliography: Word.Bibliography;

Property Value

Remarks

[ API set: WordApiDesktop 1.3 ]

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 ]

bookmarks

Returns a BookmarkCollection object that represents all the bookmarks in the document.

readonly bookmarks: Word.BookmarkCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

builtInDocumentProperties

Gets a DocumentProperties object that represents all the built-in document properties for the document.

readonly builtInDocumentProperties: Word.DocumentProperties;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

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.");
  }
});

characters

Gets the RangeScopedCollection object that represents all the characters in the document.

readonly characters: Word.RangeScopedCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

coauthoring

Gets a Coauthoring object for managing coauthoring in the document.

readonly coauthoring: Word.Coauthoring;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

codeName

Gets the code name for the document.

readonly codeName: string;

Property Value

string

Remarks

[ API set: WordApiDesktop 1.4 ]

comments

Gets a CommentCollection object that represents all the comments in the document.

readonly comments: Word.CommentCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

compatibilityMode

Gets the compatibility mode that Word uses when opening the document.

readonly compatibilityMode: Word.CompatibilityMode | "Word2003" | "Word2007" | "Word2010" | "Word2013" | "Current";

Property Value

Word.CompatibilityMode | "Word2003" | "Word2007" | "Word2010" | "Word2013" | "Current"

Remarks

[ API set: WordApiDesktop 1.4 ]

consecutiveHyphensLimit

Specifies the maximum number of consecutive lines that can end with hyphens.

consecutiveHyphensLimit: number;

Property Value

number

Remarks

[ API set: WordApiDesktop 1.3 ]

content

Gets a Range object that represents the main document story.

readonly content: Word.Range;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

contentControls

Gets the collection of ContentControl 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

currentRsid

Gets a random number that Word assigns to changes in the document.

readonly currentRsid: number;

Property Value

number

Remarks

[ API set: WordApiDesktop 1.4 ]

customDocumentProperties

Gets a DocumentProperties collection that represents all the custom document properties for the document.

readonly customDocumentProperties: Word.DocumentProperties;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

customXmlParts

Gets the custom XML parts in the document.

readonly customXmlParts: Word.CustomXmlPartCollection;

Property Value

Remarks

[ API set: WordApi 1.4 ]

defaultTabStop

Specifies the interval (in points) between the default tab stops in the document.

defaultTabStop: number;

Property Value

number

Remarks

[ API set: WordApiDesktop 1.4 ]

defaultTargetFrame

Specifies the browser frame for displaying a webpage via hyperlink.

defaultTargetFrame: string;

Property Value

string

Remarks

[ API set: WordApiDesktop 1.4 ]

documentLibraryVersions

Returns a DocumentLibraryVersionCollection object that represents the collection of versions of a shared document that has versioning enabled and that's stored in a document library on a server.

readonly documentLibraryVersions: Word.DocumentLibraryVersionCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.3 ]

doNotEmbedSystemFonts

Specifies whether Word should not embed common system fonts.

doNotEmbedSystemFonts: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

encryptionProvider

Specifies the name of the algorithm encryption provider that Microsoft Word uses when encrypting documents.

encryptionProvider: string;

Property Value

string

Remarks

[ API set: WordApiDesktop 1.4 ]

farEastLineBreakLanguage

Specifies the East Asian language used for line breaking.

farEastLineBreakLanguage: Word.FarEastLineBreakLanguageId | "TraditionalChinese" | "Japanese" | "Korean" | "SimplifiedChinese";

Property Value

Word.FarEastLineBreakLanguageId | "TraditionalChinese" | "Japanese" | "Korean" | "SimplifiedChinese"

Remarks

[ API set: WordApiDesktop 1.4 ]

farEastLineBreakLevel

Specifies the line break control level.

farEastLineBreakLevel: Word.FarEastLineBreakLevel | "Normal" | "Strict" | "Custom";

Property Value

Word.FarEastLineBreakLevel | "Normal" | "Strict" | "Custom"

Remarks

[ API set: WordApiDesktop 1.4 ]

fields

Gets a FieldCollection object that represents all the fields in the document.

readonly fields: Word.FieldCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

formattingIsNextLevelShown

Specifies whether Word shows the next heading level when the previous is used.

formattingIsNextLevelShown: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

formattingIsUserStyleNameShown

Specifies whether to show user-defined styles.

formattingIsUserStyleNameShown: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

frames

Returns a FrameCollection object that represents all the frames in the document.

readonly frames: Word.FrameCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.3 ]

fullName

Gets the name of a document, including the path.

readonly fullName: string;

Property Value

string

Remarks

[ API set: WordApiDesktop 1.4 ]

grammaticalErrors

Gets a RangeCollection object that represents the sentences that failed the grammar check in the document.

readonly grammaticalErrors: Word.RangeCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

gridDistanceHorizontal

Specifies the horizontal space between invisible gridlines that Microsoft Word uses when you draw, move, and resize AutoShapes or East Asian characters in the document.

gridDistanceHorizontal: number;

Property Value

number

Remarks

[ API set: WordApiDesktop 1.4 ]

gridDistanceVertical

Specifies the vertical space between invisible gridlines that Microsoft Word uses when you draw, move, and resize AutoShapes or East Asian characters in the document.

gridDistanceVertical: number;

Property Value

number

Remarks

[ API set: WordApiDesktop 1.4 ]

gridIsOriginFromMargin

Specifies whether the character grid starts from the upper-left corner of the page.

gridIsOriginFromMargin: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

gridOriginHorizontal

Specifies the horizontal origin point for the invisible grid.

gridOriginHorizontal: number;

Property Value

number

Remarks

[ API set: WordApiDesktop 1.4 ]

gridOriginVertical

Specifies the vertical origin point for the invisible grid.

gridOriginVertical: number;

Property Value

number

Remarks

[ API set: WordApiDesktop 1.4 ]

gridSpaceBetweenHorizontalLines

Specifies the interval for horizontal character gridlines in print layout view.

gridSpaceBetweenHorizontalLines: number;

Property Value

number

Remarks

[ API set: WordApiDesktop 1.4 ]

gridSpaceBetweenVerticalLines

Specifies the interval for vertical character gridlines in print layout view.

gridSpaceBetweenVerticalLines: number;

Property Value

number

Remarks

[ API set: WordApiDesktop 1.4 ]

hasPassword

Gets whether a password is required to open the document.

readonly hasPassword: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

hasVbProject

Gets whether the document has an attached Microsoft Visual Basic for Applications project.

readonly hasVbProject: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

Returns a HyperlinkCollection object that represents all the hyperlinks in the document.

readonly hyperlinks: Word.HyperlinkCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.3 ]

hyphenateCaps

Specifies whether words in all capital letters can be hyphenated.

hyphenateCaps: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.3 ]

hyphenationZone

Specifies the width of the hyphenation zone, in points.

hyphenationZone: number;

Property Value

number

Remarks

[ API set: WordApiDesktop 1.4 ]

indexes

Returns an IndexCollection object that represents all the indexes in the document.

readonly indexes: Word.IndexCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

isAutoFormatOverrideOn

Specifies whether automatic formatting options override formatting restrictions.

isAutoFormatOverrideOn: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isChartDataPointTracked

Specifies whether charts in the active document use cell-reference data-point tracking.

isChartDataPointTracked: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isCompatible

Specifies whether the compatibility option specified by the type property is enabled.

isCompatible: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isFinal

Specifies whether the document is final.

isFinal: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isFontsSubsetSaved

Specifies whether Microsoft Word saves a subset of the embedded TrueType fonts with the document.

isFontsSubsetSaved: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isFormsDataPrinted

Specifies whether Microsoft Word prints onto a preprinted form only the data entered in the corresponding online form.

isFormsDataPrinted: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isFormsDataSaved

Specifies whether Microsoft Word saves the data entered in a form as a tab-delimited record for use in a database.

isFormsDataSaved: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isGrammarChecked

Specifies whether a grammar check has been run on the document.

isGrammarChecked: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isInAutoSave

Gets whether the most recent firing of the Application.DocumentBeforeSave event was the result of an automatic save by the document or a manual save by the user.

readonly isInAutoSave: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isInFormsDesign

Gets whether the document is in form design mode.

readonly isInFormsDesign: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isKerningByAlgorithm

Specifies whether Word kerns half-width Latin characters and punctuation marks.

isKerningByAlgorithm: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isLinguisticDataEmbedded

Specifies whether to embed speech and handwriting data.

isLinguisticDataEmbedded: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isMasterDocument

Gets whether this document is a master document.

readonly isMasterDocument: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isOptimizedForWord97

Specifies whether Word optimizes the document for Word 97.

isOptimizedForWord97: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isPostScriptPrintedOverText

Specifies whether PRINT field instructions (such as PostScript commands) in the document are to be printed on top of text and graphics when a PostScript printer is used.

isPostScriptPrintedOverText: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isQuickStyleSetLocked

Specifies whether users can change the Quick Style set.

isQuickStyleSetLocked: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isReadOnly

Gets whether changes to the document cannot be saved to the original document.

readonly isReadOnly: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isReadOnlyRecommended

Specifies whether Microsoft Word displays a message box whenever a user opens the document, suggesting that it be opened as read-only.

isReadOnlyRecommended: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isSnappedToGrid

Specifies whether AutoShapes or East Asian characters are automatically aligned with an invisible grid.

isSnappedToGrid: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isSnappedToShapes

Specifies whether AutoShapes or East Asian characters align with invisible gridlines through other shapes.

isSnappedToShapes: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isSpellingChecked

Specifies whether spelling has been checked throughout the document.

isSpellingChecked: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isStyleEnforced

Specifies whether formatting restrictions are enforced in a protected document.

isStyleEnforced: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isSubdocument

Gets whether this document is a subdocument of a master document.

readonly isSubdocument: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isThemeLocked

Specifies whether users can change the document theme.

isThemeLocked: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isUserControl

Specifies whether the document was created or opened by the user.

isUserControl: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isVbaSigned

Gets whether the VBA project is digitally signed.

readonly isVbaSigned: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

isWriteReserved

Gets whether the document is protected with a write password.

readonly isWriteReserved: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

justificationMode

Specifies the character spacing adjustment.

justificationMode: Word.JustificationMode | "Expand" | "Compress" | "CompressKana";

Property Value

Word.JustificationMode | "Expand" | "Compress" | "CompressKana"

Remarks

[ API set: WordApiDesktop 1.4 ]

kind

Specifies the format type that Microsoft Word uses when automatically formatting the document.

kind: Word.DocumentKind | "NotSpecified" | "Letter" | "Email";

Property Value

Word.DocumentKind | "NotSpecified" | "Letter" | "Email"

Remarks

[ API set: WordApiDesktop 1.4 ]

languageDetected

Specifies whether Microsoft Word has detected the language of the document text.

languageDetected: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.3 ]

listParagraphs

Gets a ParagraphCollection object that represents all the numbered paragraphs in the document.

readonly listParagraphs: Word.ParagraphCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

lists

Gets a ListCollection object that contains all the formatted lists in the document.

readonly lists: Word.ListCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

listTemplates

Returns a ListTemplateCollection object that represents all the list templates in the document.

readonly listTemplates: Word.ListTemplateCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

noLineBreakAfter

Specifies the kinsoku characters after which Word will not break a line.

noLineBreakAfter: string;

Property Value

string

Remarks

[ API set: WordApiDesktop 1.4 ]

noLineBreakBefore

Specifies the kinsoku characters before which Word will not break a line.

noLineBreakBefore: string;

Property Value

string

Remarks

[ API set: WordApiDesktop 1.4 ]

openEncoding

Gets the encoding used to open the document.

readonly openEncoding: Word.DocumentEncoding | "Thai" | "JapaneseShiftJis" | "SimplifiedChineseGbk" | "Korean" | "TraditionalChineseBig5" | "UnicodeLittleEndian" | "UnicodeBigEndian" | "CentralEuropean" | "Cyrillic" | "Western" | "Greek" | "Turkish" | "Hebrew" | "Arabic" | "Baltic" | "Vietnamese" | "AutoDetect" | "JapaneseAutoDetect" | "SimplifiedChineseAutoDetect" | "KoreanAutoDetect" | "TraditionalChineseAutoDetect" | "CyrillicAutoDetect" | "GreekAutoDetect" | "ArabicAutoDetect" | "Iso88591Latin1" | "Iso88592CentralEurope" | "Iso88593Latin3" | "Iso88594Baltic" | "Iso88595Cyrillic" | "Iso88596Arabic" | "Iso88597Greek" | "Iso88598Hebrew" | "Iso88599Turkish" | "Iso885915Latin9" | "Iso88598HebrewLogical" | "Iso2022JpNoHalfwidthKatakana" | "Iso2022JpJisX02021984" | "Iso2022JpJisX02011989" | "Iso2022Kr" | "Iso2022CnTraditionalChinese" | "Iso2022CnSimplifiedChinese" | "MacRoman" | "MacJapanese" | "MacTraditionalChineseBig5" | "MacKorean" | "MacArabic" | "MacHebrew" | "MacGreek1" | "MacCyrillic" | "MacSimplifiedChineseGb2312" | "MacRomania" | "MacUkraine" | "MacLatin2" | "MacIcelandic" | "MacTurkish" | "MacCroatia" | "EbcdicUsCanada" | "EbcdicInternational" | "EbcdicMultilingualRoeceLatin2" | "EbcdicGreekModern" | "EbcdicTurkishLatin5" | "EbcdicGermany" | "EbcdicDenmarkNorway" | "EbcdicFinlandSweden" | "EbcdicItaly" | "EbcdicLatinAmericaSpain" | "EbcdicUnitedKingdom" | "EbcdicJapaneseKatakanaExtended" | "EbcdicFrance" | "EbcdicArabic" | "EbcdicGreek" | "EbcdicHebrew" | "EbcdicKoreanExtended" | "EbcdicThai" | "EbcdicIcelandic" | "EbcdicTurkish" | "EbcdicRussian" | "EbcdicSerbianBulgarian" | "EbcdicJapaneseKatakanaExtendedAndJapanese" | "EbcdicUsCanadaAndJapanese" | "EbcdicKoreanExtendedAndKorean" | "EbcdicSimplifiedChineseExtendedAndSimplifiedChinese" | "EbcdicUsCanadaAndTraditionalChinese" | "EbcdicJapaneseLatinExtendedAndJapanese" | "OemUnitedStates" | "OemGreek437G" | "OemBaltic" | "OemMultilingualLatinI" | "OemMultilingualLatinIi" | "OemCyrillic" | "OemTurkish" | "OemPortuguese" | "OemIcelandic" | "OemHebrew" | "OemCanadianFrench" | "OemArabic" | "OemNordic" | "OemCyrillicIi" | "OemModernGreek" | "EucJapanese" | "EucChineseSimplifiedChinese" | "EucKorean" | "EucTaiwaneseTraditionalChinese" | "IsciiDevanagari" | "IsciiBengali" | "IsciiTamil" | "IsciiTelugu" | "IsciiAssamese" | "IsciiOriya" | "IsciiKannada" | "IsciiMalayalam" | "IsciiGujarati" | "IsciiPunjabi" | "ArabicAsmo" | "ArabicTransparentAsmo" | "KoreanJohab" | "TaiwanCns" | "TaiwanTca" | "TaiwanEten" | "TaiwanIbm5550" | "TaiwanTeleText" | "TaiwanWang" | "Ia5Irv" | "Ia5German" | "Ia5Swedish" | "Ia5Norwegian" | "UsaAscii" | "T61" | "Iso6937NonSpacingAccent" | "Koi8R" | "ExtAlphaLowercase" | "Koi8U" | "Europa3" | "HzGbSimplifiedChinese" | "SimplifiedChineseGb18030" | "Utf7" | "Utf8";

Property Value

Word.DocumentEncoding | "Thai" | "JapaneseShiftJis" | "SimplifiedChineseGbk" | "Korean" | "TraditionalChineseBig5" | "UnicodeLittleEndian" | "UnicodeBigEndian" | "CentralEuropean" | "Cyrillic" | "Western" | "Greek" | "Turkish" | "Hebrew" | "Arabic" | "Baltic" | "Vietnamese" | "AutoDetect" | "JapaneseAutoDetect" | "SimplifiedChineseAutoDetect" | "KoreanAutoDetect" | "TraditionalChineseAutoDetect" | "CyrillicAutoDetect" | "GreekAutoDetect" | "ArabicAutoDetect" | "Iso88591Latin1" | "Iso88592CentralEurope" | "Iso88593Latin3" | "Iso88594Baltic" | "Iso88595Cyrillic" | "Iso88596Arabic" | "Iso88597Greek" | "Iso88598Hebrew" | "Iso88599Turkish" | "Iso885915Latin9" | "Iso88598HebrewLogical" | "Iso2022JpNoHalfwidthKatakana" | "Iso2022JpJisX02021984" | "Iso2022JpJisX02011989" | "Iso2022Kr" | "Iso2022CnTraditionalChinese" | "Iso2022CnSimplifiedChinese" | "MacRoman" | "MacJapanese" | "MacTraditionalChineseBig5" | "MacKorean" | "MacArabic" | "MacHebrew" | "MacGreek1" | "MacCyrillic" | "MacSimplifiedChineseGb2312" | "MacRomania" | "MacUkraine" | "MacLatin2" | "MacIcelandic" | "MacTurkish" | "MacCroatia" | "EbcdicUsCanada" | "EbcdicInternational" | "EbcdicMultilingualRoeceLatin2" | "EbcdicGreekModern" | "EbcdicTurkishLatin5" | "EbcdicGermany" | "EbcdicDenmarkNorway" | "EbcdicFinlandSweden" | "EbcdicItaly" | "EbcdicLatinAmericaSpain" | "EbcdicUnitedKingdom" | "EbcdicJapaneseKatakanaExtended" | "EbcdicFrance" | "EbcdicArabic" | "EbcdicGreek" | "EbcdicHebrew" | "EbcdicKoreanExtended" | "EbcdicThai" | "EbcdicIcelandic" | "EbcdicTurkish" | "EbcdicRussian" | "EbcdicSerbianBulgarian" | "EbcdicJapaneseKatakanaExtendedAndJapanese" | "EbcdicUsCanadaAndJapanese" | "EbcdicKoreanExtendedAndKorean" | "EbcdicSimplifiedChineseExtendedAndSimplifiedChinese" | "EbcdicUsCanadaAndTraditionalChinese" | "EbcdicJapaneseLatinExtendedAndJapanese" | "OemUnitedStates" | "OemGreek437G" | "OemBaltic" | "OemMultilingualLatinI" | "OemMultilingualLatinIi" | "OemCyrillic" | "OemTurkish" | "OemPortuguese" | "OemIcelandic" | "OemHebrew" | "OemCanadianFrench" | "OemArabic" | "OemNordic" | "OemCyrillicIi" | "OemModernGreek" | "EucJapanese" | "EucChineseSimplifiedChinese" | "EucKorean" | "EucTaiwaneseTraditionalChinese" | "IsciiDevanagari" | "IsciiBengali" | "IsciiTamil" | "IsciiTelugu" | "IsciiAssamese" | "IsciiOriya" | "IsciiKannada" | "IsciiMalayalam" | "IsciiGujarati" | "IsciiPunjabi" | "ArabicAsmo" | "ArabicTransparentAsmo" | "KoreanJohab" | "TaiwanCns" | "TaiwanTca" | "TaiwanEten" | "TaiwanIbm5550" | "TaiwanTeleText" | "TaiwanWang" | "Ia5Irv" | "Ia5German" | "Ia5Swedish" | "Ia5Norwegian" | "UsaAscii" | "T61" | "Iso6937NonSpacingAccent" | "Koi8R" | "ExtAlphaLowercase" | "Koi8U" | "Europa3" | "HzGbSimplifiedChinese" | "SimplifiedChineseGb18030" | "Utf7" | "Utf8"

Remarks

[ API set: WordApiDesktop 1.4 ]

originalDocumentTitle

Gets the title of the original document after legal-blackline comparison.

readonly originalDocumentTitle: string;

Property Value

string

Remarks

[ API set: WordApiDesktop 1.4 ]

pageSetup

Returns a PageSetup object that's associated with the document.

readonly pageSetup: Word.PageSetup;

Property Value

Remarks

[ API set: WordApiDesktop 1.3 ]

paragraphs

Gets a ParagraphCollection object that represents all the paragraphs in the document.

readonly paragraphs: Word.ParagraphCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

password

Sets a password that must be supplied to open the document.

password: string;

Property Value

string

Remarks

[ API set: WordApiDesktop 1.4 ]

passwordEncryptionAlgorithm

Gets the algorithm used for password encryption.

readonly passwordEncryptionAlgorithm: string;

Property Value

string

Remarks

[ API set: WordApiDesktop 1.4 ]

passwordEncryptionKeyLength

Gets the key length used for password encryption.

readonly passwordEncryptionKeyLength: number;

Property Value

number

Remarks

[ API set: WordApiDesktop 1.4 ]

passwordEncryptionProvider

Gets the name of the password encryption provider.

readonly passwordEncryptionProvider: string;

Property Value

string

Remarks

[ API set: WordApiDesktop 1.4 ]

path

Gets the disk or the web path to the document (excludes the document name).

readonly path: string;

Property Value

string

Remarks

[ API set: WordApiDesktop 1.4 ]

printRevisions

Specifies whether revision marks are printed with the document.

printRevisions: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 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));
});

protectionType

Gets the protection type for the document.

readonly protectionType: Word.ProtectionType | "NoProtection" | "AllowOnlyRevisions" | "AllowOnlyComments" | "AllowOnlyFormFields" | "AllowOnlyReading";

Property Value

Word.ProtectionType | "NoProtection" | "AllowOnlyRevisions" | "AllowOnlyComments" | "AllowOnlyFormFields" | "AllowOnlyReading"

Remarks

[ API set: WordApiDesktop 1.4 ]

readabilityStatistics

Gets a ReadabilityStatisticCollection object that represents the readability statistics for the document.

readonly readabilityStatistics: Word.ReadabilityStatisticCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

readingLayoutSizeX

Specifies the width of pages in reading layout view when frozen.

readingLayoutSizeX: number;

Property Value

number

Remarks

[ API set: WordApiDesktop 1.4 ]

readingLayoutSizeY

Specifies the height of pages in reading layout view when frozen.

readingLayoutSizeY: number;

Property Value

number

Remarks

[ API set: WordApiDesktop 1.4 ]

readingModeIsLayoutFrozen

Specifies whether pages in reading layout view are frozen for handwritten markup.

readingModeIsLayoutFrozen: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

removePersonalInformationOnSave

Specifies whether Word removes user information upon saving.

removePersonalInformationOnSave: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

revisedDocumentTitle

Gets the title of the revised document after legal-blackline comparison.

readonly revisedDocumentTitle: string;

Property Value

string

Remarks

[ API set: WordApiDesktop 1.4 ]

revisions

Gets the collection of revisions that represents the tracked changes in the document.

readonly revisions: Word.RevisionCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.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 ]

saveEncoding

Specifies the encoding used when saving the document.

saveEncoding: Word.DocumentEncoding | "Thai" | "JapaneseShiftJis" | "SimplifiedChineseGbk" | "Korean" | "TraditionalChineseBig5" | "UnicodeLittleEndian" | "UnicodeBigEndian" | "CentralEuropean" | "Cyrillic" | "Western" | "Greek" | "Turkish" | "Hebrew" | "Arabic" | "Baltic" | "Vietnamese" | "AutoDetect" | "JapaneseAutoDetect" | "SimplifiedChineseAutoDetect" | "KoreanAutoDetect" | "TraditionalChineseAutoDetect" | "CyrillicAutoDetect" | "GreekAutoDetect" | "ArabicAutoDetect" | "Iso88591Latin1" | "Iso88592CentralEurope" | "Iso88593Latin3" | "Iso88594Baltic" | "Iso88595Cyrillic" | "Iso88596Arabic" | "Iso88597Greek" | "Iso88598Hebrew" | "Iso88599Turkish" | "Iso885915Latin9" | "Iso88598HebrewLogical" | "Iso2022JpNoHalfwidthKatakana" | "Iso2022JpJisX02021984" | "Iso2022JpJisX02011989" | "Iso2022Kr" | "Iso2022CnTraditionalChinese" | "Iso2022CnSimplifiedChinese" | "MacRoman" | "MacJapanese" | "MacTraditionalChineseBig5" | "MacKorean" | "MacArabic" | "MacHebrew" | "MacGreek1" | "MacCyrillic" | "MacSimplifiedChineseGb2312" | "MacRomania" | "MacUkraine" | "MacLatin2" | "MacIcelandic" | "MacTurkish" | "MacCroatia" | "EbcdicUsCanada" | "EbcdicInternational" | "EbcdicMultilingualRoeceLatin2" | "EbcdicGreekModern" | "EbcdicTurkishLatin5" | "EbcdicGermany" | "EbcdicDenmarkNorway" | "EbcdicFinlandSweden" | "EbcdicItaly" | "EbcdicLatinAmericaSpain" | "EbcdicUnitedKingdom" | "EbcdicJapaneseKatakanaExtended" | "EbcdicFrance" | "EbcdicArabic" | "EbcdicGreek" | "EbcdicHebrew" | "EbcdicKoreanExtended" | "EbcdicThai" | "EbcdicIcelandic" | "EbcdicTurkish" | "EbcdicRussian" | "EbcdicSerbianBulgarian" | "EbcdicJapaneseKatakanaExtendedAndJapanese" | "EbcdicUsCanadaAndJapanese" | "EbcdicKoreanExtendedAndKorean" | "EbcdicSimplifiedChineseExtendedAndSimplifiedChinese" | "EbcdicUsCanadaAndTraditionalChinese" | "EbcdicJapaneseLatinExtendedAndJapanese" | "OemUnitedStates" | "OemGreek437G" | "OemBaltic" | "OemMultilingualLatinI" | "OemMultilingualLatinIi" | "OemCyrillic" | "OemTurkish" | "OemPortuguese" | "OemIcelandic" | "OemHebrew" | "OemCanadianFrench" | "OemArabic" | "OemNordic" | "OemCyrillicIi" | "OemModernGreek" | "EucJapanese" | "EucChineseSimplifiedChinese" | "EucKorean" | "EucTaiwaneseTraditionalChinese" | "IsciiDevanagari" | "IsciiBengali" | "IsciiTamil" | "IsciiTelugu" | "IsciiAssamese" | "IsciiOriya" | "IsciiKannada" | "IsciiMalayalam" | "IsciiGujarati" | "IsciiPunjabi" | "ArabicAsmo" | "ArabicTransparentAsmo" | "KoreanJohab" | "TaiwanCns" | "TaiwanTca" | "TaiwanEten" | "TaiwanIbm5550" | "TaiwanTeleText" | "TaiwanWang" | "Ia5Irv" | "Ia5German" | "Ia5Swedish" | "Ia5Norwegian" | "UsaAscii" | "T61" | "Iso6937NonSpacingAccent" | "Koi8R" | "ExtAlphaLowercase" | "Koi8U" | "Europa3" | "HzGbSimplifiedChinese" | "SimplifiedChineseGb18030" | "Utf7" | "Utf8";

Property Value

Word.DocumentEncoding | "Thai" | "JapaneseShiftJis" | "SimplifiedChineseGbk" | "Korean" | "TraditionalChineseBig5" | "UnicodeLittleEndian" | "UnicodeBigEndian" | "CentralEuropean" | "Cyrillic" | "Western" | "Greek" | "Turkish" | "Hebrew" | "Arabic" | "Baltic" | "Vietnamese" | "AutoDetect" | "JapaneseAutoDetect" | "SimplifiedChineseAutoDetect" | "KoreanAutoDetect" | "TraditionalChineseAutoDetect" | "CyrillicAutoDetect" | "GreekAutoDetect" | "ArabicAutoDetect" | "Iso88591Latin1" | "Iso88592CentralEurope" | "Iso88593Latin3" | "Iso88594Baltic" | "Iso88595Cyrillic" | "Iso88596Arabic" | "Iso88597Greek" | "Iso88598Hebrew" | "Iso88599Turkish" | "Iso885915Latin9" | "Iso88598HebrewLogical" | "Iso2022JpNoHalfwidthKatakana" | "Iso2022JpJisX02021984" | "Iso2022JpJisX02011989" | "Iso2022Kr" | "Iso2022CnTraditionalChinese" | "Iso2022CnSimplifiedChinese" | "MacRoman" | "MacJapanese" | "MacTraditionalChineseBig5" | "MacKorean" | "MacArabic" | "MacHebrew" | "MacGreek1" | "MacCyrillic" | "MacSimplifiedChineseGb2312" | "MacRomania" | "MacUkraine" | "MacLatin2" | "MacIcelandic" | "MacTurkish" | "MacCroatia" | "EbcdicUsCanada" | "EbcdicInternational" | "EbcdicMultilingualRoeceLatin2" | "EbcdicGreekModern" | "EbcdicTurkishLatin5" | "EbcdicGermany" | "EbcdicDenmarkNorway" | "EbcdicFinlandSweden" | "EbcdicItaly" | "EbcdicLatinAmericaSpain" | "EbcdicUnitedKingdom" | "EbcdicJapaneseKatakanaExtended" | "EbcdicFrance" | "EbcdicArabic" | "EbcdicGreek" | "EbcdicHebrew" | "EbcdicKoreanExtended" | "EbcdicThai" | "EbcdicIcelandic" | "EbcdicTurkish" | "EbcdicRussian" | "EbcdicSerbianBulgarian" | "EbcdicJapaneseKatakanaExtendedAndJapanese" | "EbcdicUsCanadaAndJapanese" | "EbcdicKoreanExtendedAndKorean" | "EbcdicSimplifiedChineseExtendedAndSimplifiedChinese" | "EbcdicUsCanadaAndTraditionalChinese" | "EbcdicJapaneseLatinExtendedAndJapanese" | "OemUnitedStates" | "OemGreek437G" | "OemBaltic" | "OemMultilingualLatinI" | "OemMultilingualLatinIi" | "OemCyrillic" | "OemTurkish" | "OemPortuguese" | "OemIcelandic" | "OemHebrew" | "OemCanadianFrench" | "OemArabic" | "OemNordic" | "OemCyrillicIi" | "OemModernGreek" | "EucJapanese" | "EucChineseSimplifiedChinese" | "EucKorean" | "EucTaiwaneseTraditionalChinese" | "IsciiDevanagari" | "IsciiBengali" | "IsciiTamil" | "IsciiTelugu" | "IsciiAssamese" | "IsciiOriya" | "IsciiKannada" | "IsciiMalayalam" | "IsciiGujarati" | "IsciiPunjabi" | "ArabicAsmo" | "ArabicTransparentAsmo" | "KoreanJohab" | "TaiwanCns" | "TaiwanTca" | "TaiwanEten" | "TaiwanIbm5550" | "TaiwanTeleText" | "TaiwanWang" | "Ia5Irv" | "Ia5German" | "Ia5Swedish" | "Ia5Norwegian" | "UsaAscii" | "T61" | "Iso6937NonSpacingAccent" | "Koi8R" | "ExtAlphaLowercase" | "Koi8U" | "Europa3" | "HzGbSimplifiedChinese" | "SimplifiedChineseGb18030" | "Utf7" | "Utf8"

Remarks

[ API set: WordApiDesktop 1.4 ]

saveFormat

Gets the file format of the document.

readonly saveFormat: Word.FileSaveFormat | "Document" | "Template" | "Text" | "TextLineBreaks" | "DosText" | "DosTextLineBreaks" | "Rtf" | "UnicodeText" | "Html" | "WebArchive" | "FilteredHtml" | "Xml" | "XmlDocument" | "XmlDocumentMacroEnabled" | "XmlTemplate" | "XmlTemplateMacroEnabled" | "DocumentDefault" | "Pdf" | "Xps" | "FlatXml" | "FlatXmlMacroEnabled" | "FlatXmlTemplate" | "FlatXmlTemplateMacroEnabled" | "OpenDocumentText" | "StrictOpenXmlDocument";

Property Value

Word.FileSaveFormat | "Document" | "Template" | "Text" | "TextLineBreaks" | "DosText" | "DosTextLineBreaks" | "Rtf" | "UnicodeText" | "Html" | "WebArchive" | "FilteredHtml" | "Xml" | "XmlDocument" | "XmlDocumentMacroEnabled" | "XmlTemplate" | "XmlTemplateMacroEnabled" | "DocumentDefault" | "Pdf" | "Xps" | "FlatXml" | "FlatXmlMacroEnabled" | "FlatXmlTemplate" | "FlatXmlTemplateMacroEnabled" | "OpenDocumentText" | "StrictOpenXmlDocument"

Remarks

[ API set: WordApiDesktop 1.4 ]

sections

Gets the collection of Section objects in the document.

readonly sections: Word.SectionCollection;

Property Value

Remarks

[ API set: WordApi 1.1 ]

selection

Returns a Selection object that represents the current selection in the document.

readonly selection: Word.Selection;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

sentences

Gets the RangeScopedCollection object that represents all the sentences in the document.

readonly sentences: Word.RangeScopedCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

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]);
    }
  }
});

spellingErrors

Gets a RangeCollection object that represents the words identified as spelling errors in the document.

readonly spellingErrors: Word.RangeCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

storyRanges

Gets a RangeCollection object that represents all the stories in the document.

readonly storyRanges: Word.RangeCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

styles

Gets a StyleCollection for the document.

readonly styles: Word.StyleCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

tableOfAuthoritiesCategories

Returns a TableOfAuthoritiesCategoryCollection object that represents the available table of authorities categories in the document.

readonly tableOfAuthoritiesCategories: Word.TableOfAuthoritiesCategoryCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

tables

Gets a TableCollection object that represents all the tables in the document.

readonly tables: Word.TableCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

tablesOfAuthorities

Returns a TableOfAuthoritiesCollection object that represents all the tables of authorities in the document.

readonly tablesOfAuthorities: Word.TableOfAuthoritiesCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

tablesOfContents

Returns a TableOfContentsCollection object that represents all the tables of contents in the document.

readonly tablesOfContents: Word.TableOfContentsCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

tablesOfFigures

Returns a TableOfFiguresCollection object that represents all the tables of figures in the document.

readonly tablesOfFigures: Word.TableOfFiguresCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

textEncoding

Specifies the encoding for saving as encoded text.

textEncoding: Word.DocumentEncoding | "Thai" | "JapaneseShiftJis" | "SimplifiedChineseGbk" | "Korean" | "TraditionalChineseBig5" | "UnicodeLittleEndian" | "UnicodeBigEndian" | "CentralEuropean" | "Cyrillic" | "Western" | "Greek" | "Turkish" | "Hebrew" | "Arabic" | "Baltic" | "Vietnamese" | "AutoDetect" | "JapaneseAutoDetect" | "SimplifiedChineseAutoDetect" | "KoreanAutoDetect" | "TraditionalChineseAutoDetect" | "CyrillicAutoDetect" | "GreekAutoDetect" | "ArabicAutoDetect" | "Iso88591Latin1" | "Iso88592CentralEurope" | "Iso88593Latin3" | "Iso88594Baltic" | "Iso88595Cyrillic" | "Iso88596Arabic" | "Iso88597Greek" | "Iso88598Hebrew" | "Iso88599Turkish" | "Iso885915Latin9" | "Iso88598HebrewLogical" | "Iso2022JpNoHalfwidthKatakana" | "Iso2022JpJisX02021984" | "Iso2022JpJisX02011989" | "Iso2022Kr" | "Iso2022CnTraditionalChinese" | "Iso2022CnSimplifiedChinese" | "MacRoman" | "MacJapanese" | "MacTraditionalChineseBig5" | "MacKorean" | "MacArabic" | "MacHebrew" | "MacGreek1" | "MacCyrillic" | "MacSimplifiedChineseGb2312" | "MacRomania" | "MacUkraine" | "MacLatin2" | "MacIcelandic" | "MacTurkish" | "MacCroatia" | "EbcdicUsCanada" | "EbcdicInternational" | "EbcdicMultilingualRoeceLatin2" | "EbcdicGreekModern" | "EbcdicTurkishLatin5" | "EbcdicGermany" | "EbcdicDenmarkNorway" | "EbcdicFinlandSweden" | "EbcdicItaly" | "EbcdicLatinAmericaSpain" | "EbcdicUnitedKingdom" | "EbcdicJapaneseKatakanaExtended" | "EbcdicFrance" | "EbcdicArabic" | "EbcdicGreek" | "EbcdicHebrew" | "EbcdicKoreanExtended" | "EbcdicThai" | "EbcdicIcelandic" | "EbcdicTurkish" | "EbcdicRussian" | "EbcdicSerbianBulgarian" | "EbcdicJapaneseKatakanaExtendedAndJapanese" | "EbcdicUsCanadaAndJapanese" | "EbcdicKoreanExtendedAndKorean" | "EbcdicSimplifiedChineseExtendedAndSimplifiedChinese" | "EbcdicUsCanadaAndTraditionalChinese" | "EbcdicJapaneseLatinExtendedAndJapanese" | "OemUnitedStates" | "OemGreek437G" | "OemBaltic" | "OemMultilingualLatinI" | "OemMultilingualLatinIi" | "OemCyrillic" | "OemTurkish" | "OemPortuguese" | "OemIcelandic" | "OemHebrew" | "OemCanadianFrench" | "OemArabic" | "OemNordic" | "OemCyrillicIi" | "OemModernGreek" | "EucJapanese" | "EucChineseSimplifiedChinese" | "EucKorean" | "EucTaiwaneseTraditionalChinese" | "IsciiDevanagari" | "IsciiBengali" | "IsciiTamil" | "IsciiTelugu" | "IsciiAssamese" | "IsciiOriya" | "IsciiKannada" | "IsciiMalayalam" | "IsciiGujarati" | "IsciiPunjabi" | "ArabicAsmo" | "ArabicTransparentAsmo" | "KoreanJohab" | "TaiwanCns" | "TaiwanTca" | "TaiwanEten" | "TaiwanIbm5550" | "TaiwanTeleText" | "TaiwanWang" | "Ia5Irv" | "Ia5German" | "Ia5Swedish" | "Ia5Norwegian" | "UsaAscii" | "T61" | "Iso6937NonSpacingAccent" | "Koi8R" | "ExtAlphaLowercase" | "Koi8U" | "Europa3" | "HzGbSimplifiedChinese" | "SimplifiedChineseGb18030" | "Utf7" | "Utf8";

Property Value

Word.DocumentEncoding | "Thai" | "JapaneseShiftJis" | "SimplifiedChineseGbk" | "Korean" | "TraditionalChineseBig5" | "UnicodeLittleEndian" | "UnicodeBigEndian" | "CentralEuropean" | "Cyrillic" | "Western" | "Greek" | "Turkish" | "Hebrew" | "Arabic" | "Baltic" | "Vietnamese" | "AutoDetect" | "JapaneseAutoDetect" | "SimplifiedChineseAutoDetect" | "KoreanAutoDetect" | "TraditionalChineseAutoDetect" | "CyrillicAutoDetect" | "GreekAutoDetect" | "ArabicAutoDetect" | "Iso88591Latin1" | "Iso88592CentralEurope" | "Iso88593Latin3" | "Iso88594Baltic" | "Iso88595Cyrillic" | "Iso88596Arabic" | "Iso88597Greek" | "Iso88598Hebrew" | "Iso88599Turkish" | "Iso885915Latin9" | "Iso88598HebrewLogical" | "Iso2022JpNoHalfwidthKatakana" | "Iso2022JpJisX02021984" | "Iso2022JpJisX02011989" | "Iso2022Kr" | "Iso2022CnTraditionalChinese" | "Iso2022CnSimplifiedChinese" | "MacRoman" | "MacJapanese" | "MacTraditionalChineseBig5" | "MacKorean" | "MacArabic" | "MacHebrew" | "MacGreek1" | "MacCyrillic" | "MacSimplifiedChineseGb2312" | "MacRomania" | "MacUkraine" | "MacLatin2" | "MacIcelandic" | "MacTurkish" | "MacCroatia" | "EbcdicUsCanada" | "EbcdicInternational" | "EbcdicMultilingualRoeceLatin2" | "EbcdicGreekModern" | "EbcdicTurkishLatin5" | "EbcdicGermany" | "EbcdicDenmarkNorway" | "EbcdicFinlandSweden" | "EbcdicItaly" | "EbcdicLatinAmericaSpain" | "EbcdicUnitedKingdom" | "EbcdicJapaneseKatakanaExtended" | "EbcdicFrance" | "EbcdicArabic" | "EbcdicGreek" | "EbcdicHebrew" | "EbcdicKoreanExtended" | "EbcdicThai" | "EbcdicIcelandic" | "EbcdicTurkish" | "EbcdicRussian" | "EbcdicSerbianBulgarian" | "EbcdicJapaneseKatakanaExtendedAndJapanese" | "EbcdicUsCanadaAndJapanese" | "EbcdicKoreanExtendedAndKorean" | "EbcdicSimplifiedChineseExtendedAndSimplifiedChinese" | "EbcdicUsCanadaAndTraditionalChinese" | "EbcdicJapaneseLatinExtendedAndJapanese" | "OemUnitedStates" | "OemGreek437G" | "OemBaltic" | "OemMultilingualLatinI" | "OemMultilingualLatinIi" | "OemCyrillic" | "OemTurkish" | "OemPortuguese" | "OemIcelandic" | "OemHebrew" | "OemCanadianFrench" | "OemArabic" | "OemNordic" | "OemCyrillicIi" | "OemModernGreek" | "EucJapanese" | "EucChineseSimplifiedChinese" | "EucKorean" | "EucTaiwaneseTraditionalChinese" | "IsciiDevanagari" | "IsciiBengali" | "IsciiTamil" | "IsciiTelugu" | "IsciiAssamese" | "IsciiOriya" | "IsciiKannada" | "IsciiMalayalam" | "IsciiGujarati" | "IsciiPunjabi" | "ArabicAsmo" | "ArabicTransparentAsmo" | "KoreanJohab" | "TaiwanCns" | "TaiwanTca" | "TaiwanEten" | "TaiwanIbm5550" | "TaiwanTeleText" | "TaiwanWang" | "Ia5Irv" | "Ia5German" | "Ia5Swedish" | "Ia5Norwegian" | "UsaAscii" | "T61" | "Iso6937NonSpacingAccent" | "Koi8R" | "ExtAlphaLowercase" | "Koi8U" | "Europa3" | "HzGbSimplifiedChinese" | "SimplifiedChineseGb18030" | "Utf7" | "Utf8"

Remarks

[ API set: WordApiDesktop 1.4 ]

textLineEnding

Specifies how Word marks line and paragraph breaks in text files.

textLineEnding: Word.LineEndingType | "Crlf" | "CrOnly" | "LfOnly" | "Lfcr" | "Lsps";

Property Value

Word.LineEndingType | "Crlf" | "CrOnly" | "LfOnly" | "Lfcr" | "Lsps"

Remarks

[ API set: WordApiDesktop 1.4 ]

trackedChangesAreDateAndTimeRemoved

Specifies whether to remove or store date and time metadata for tracked changes.

trackedChangesAreDateAndTimeRemoved: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

trackFormatting

Specifies whether to track formatting changes when change tracking is on.

trackFormatting: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

trackMoves

Specifies whether to mark moved text when Track Changes is on.

trackMoves: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

trackRevisions

Specifies whether changes are tracked in the document.

trackRevisions: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

type

Gets the document type (template or document).

readonly type: Word.DocumentType | "Document" | "Template" | "Frameset";

Property Value

Word.DocumentType | "Document" | "Template" | "Frameset"

Remarks

[ API set: WordApiDesktop 1.4 ]

webSettings

Gets the WebSettings object for webpage-related attributes.

readonly webSettings: Word.WebSettings;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

windows

Gets the collection of Word.Window objects for the document.

readonly windows: Word.WindowCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.2 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/get-pages.yaml

await Word.run(async (context) => {
  // Gets the document windows.
  const windows: Word.WindowCollection = context.document.windows;
  windows.load("windows/items/length");

  await context.sync();

  console.log(`Number of windows for this document: ${windows.items.length}`);
});

words

Gets the RangeScopedCollection object that represents each word in the document.

readonly words: Word.RangeScopedCollection;

Property Value

Remarks

[ API set: WordApiDesktop 1.4 ]

writePassword

Sets a password for saving changes to the document.

writePassword: string;

Property Value

string

Remarks

[ API set: WordApiDesktop 1.4 ]

xmlAreAdvancedErrorsShown

Specifies whether error messages are generated from built-in Word messages or MSXML (Microsoft XML).

xmlAreAdvancedErrorsShown: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

xmlIsXsltUsedWhenSaving

Specifies whether to save a document through an Extensible Stylesheet Language Transformation (XSLT).

xmlIsXsltUsedWhenSaving: boolean;

Property Value

boolean

Remarks

[ API set: WordApiDesktop 1.4 ]

xmlSaveThroughXslt

Specifies the path and file name for the XSLT to apply when saving a document.

xmlSaveThroughXslt: string;

Property Value

string

Remarks

[ API set: WordApiDesktop 1.4 ]

Method Details

acceptAllRevisions()

Accepts all tracked changes in the document.

acceptAllRevisions(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

acceptAllRevisionsShown()

Accepts all revisions in the document that are displayed on the screen.

acceptAllRevisionsShown(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

activate()

Activates the document so that it becomes the active document.

activate(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

addStyle(name, type)

Adds a style into the document by name and type.

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

Parameters

name

string

A string representing the style name.

type
Word.StyleType

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 = (document.getElementById("new-style-name") as HTMLInputElement).value;
  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 = ((document.getElementById("new-style-type") as HTMLSelectElement).value 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, type)

Adds a style into the document by name and type.

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

Parameters

name

string

A string representing the style name.

type

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

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

Returns

Remarks

[ API set: WordApi 1.5 ]

addToFavorites()

Creates a shortcut to the document or hyperlink and adds it to the Favorites folder.

addToFavorites(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

applyQuickStyleSet(style)

Applies the specified Quick Style set to the document.

applyQuickStyleSet(style: Word.ApplyQuickStyleSet): void;

Parameters

style
Word.ApplyQuickStyleSet

The style set to apply.

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

applyQuickStyleSet(style)

Applies the specified Quick Style set to the document.

applyQuickStyleSet(style: "SessionStart" | "Template"): void;

Parameters

style

"SessionStart" | "Template"

The style set to apply.

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

applyTheme(name)

Applies the specified theme to this document.

applyTheme(name: string): void;

Parameters

name

string

The name of the theme.

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

autoFormat()

Automatically formats the document.

autoFormat(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

canCheckin()

Returns true if Microsoft Word can check in the document to a server.

canCheckin(): OfficeExtension.ClientResult<boolean>;

Returns

true if the document can be checked in; otherwise, false.

Remarks

[ API set: WordApiDesktop 1.4 ]

checkConsistencyJapanese()

Searches all text in a Japanese language document and displays instances where character usage is inconsistent for the same words.

checkConsistencyJapanese(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

checkGrammar()

Begins a spelling and grammar check for the document.

checkGrammar(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

checkIn(options)

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Checks in the document from the local computer to a server and sets the local document to read-only so that it cannot be edited locally.

checkIn(options?: Word.DocumentCheckInOptions): void;

Parameters

options
Word.DocumentCheckInOptions

Optional. Configuration options for checking in the document.

Returns

void

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

checkInWithVersion(options)

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Saves the document to a server from a local computer, and sets the local document to read-only so that it cannot be edited locally.

checkInWithVersion(options?: Word.DocumentCheckInWithVersionOptions): void;

Parameters

options
Word.DocumentCheckInWithVersionOptions

Optional. Configuration options for checking in the document with version control.

Returns

void

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

checkSpelling(options)

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Begins a spelling check for the document.

checkSpelling(options?: Word.DocumentCheckSpellingOptions): void;

Parameters

options
Word.DocumentCheckSpellingOptions

Optional. Configuration options for the spell checking operation.

Returns

void

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

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(closeBehavior)

Closes the current document.

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

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

Parameters

closeBehavior

"Save" | "SkipSave"

Optional. The close behavior must be save or skipSave. Default value is save.

Returns

void

Remarks

[ API set: WordApi 1.5 ]

closePrintPreview()

Switches the document from print preview to the previous view.

closePrintPreview(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

compare(filePath, documentCompareOptions)

Displays revision marks that indicate where the specified document differs from another document.

compare(filePath: string, documentCompareOptions?: Word.DocumentCompareOptions): void;

Parameters

filePath

string

The path of the document with which the specified document is compared.

documentCompareOptions
Word.DocumentCompareOptions

Optional. The additional options that specifies the behavior of comparing document.

Returns

void

Remarks

[ API set: WordApiDesktop 1.1 ]

Examples

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

// Compares the current document with a specified external document.
await Word.run(async (context) => {
  // Absolute path of an online or local document.
  const filePath = (document.getElementById("filePath") as HTMLInputElement).value;
  // Options that configure the compare operation.
  const options: Word.DocumentCompareOptions = {
    compareTarget: Word.CompareTarget.compareTargetCurrent,
    detectFormatChanges: false
    // Other options you choose...
    };
  context.document.compare(filePath, options);

  await context.sync();

  console.log("Differences shown in the current document.");
});

compareFromBase64(base64File, documentCompareOptions)

Displays revision marks that indicate where the specified document differs from another document.

compareFromBase64(base64File: string, documentCompareOptions?: Word.DocumentCompareOptions): void;

Parameters

base64File

string

The Base64-encoded content of the document with which the specified document is compared.

documentCompareOptions
Word.DocumentCompareOptions

Optional. The additional options that specify the behavior for comparing the documents. Note that the compareTarget option isn't allowed to be compareTargetSelected in this API.

Returns

void

Remarks

[ API set: WordApiDesktop 1.2 ]

computeStatistics(statistic, includeFootnotesAndEndnotes)

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Returns a statistic based on the contents of the document.

computeStatistics(statistic: Word.StatisticType, includeFootnotesAndEndnotes?: boolean): OfficeExtension.ClientResult<number>;

Parameters

statistic
Word.StatisticType

The type of statistic to return.

includeFootnotesAndEndnotes

boolean

Optional. Whether to include footnotes and endnotes. The default value is false.

Returns

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

computeStatistics(statistic, includeFootnotesAndEndnotes)

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Returns a statistic based on the contents of the document.

computeStatistics(statistic: "Words" | "Lines" | "Pages" | "Characters" | "Paragraphs" | "CharactersWithSpaces" | "FarEastCharacters", includeFootnotesAndEndnotes?: boolean): OfficeExtension.ClientResult<number>;

Parameters

statistic

"Words" | "Lines" | "Pages" | "Characters" | "Paragraphs" | "CharactersWithSpaces" | "FarEastCharacters"

The type of statistic to return.

includeFootnotesAndEndnotes

boolean

Optional. Whether to include footnotes and endnotes. The default value is false.

Returns

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

convert()

Converts the file to the newest format and enables all features.

convert(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

convertAutoHyphens()

Converts automatic hyphens to manual hyphens.

convertAutoHyphens(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

convertNumbersToText(numberType)

Changes the list numbers and LISTNUM fields in the document to text.

convertNumbersToText(numberType?: Word.NumberType): void;

Parameters

numberType
Word.NumberType

Optional. The type of numbering to convert.

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

convertNumbersToText(numberType)

Changes the list numbers and LISTNUM fields in the document to text.

convertNumbersToText(numberType?: "Paragraph" | "ListNum" | "AllNumbers"): void;

Parameters

numberType

"Paragraph" | "ListNum" | "AllNumbers"

Optional. The type of numbering to convert.

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

convertVietnameseDocument(codePageOrigin)

Reconverts a Vietnamese document to Unicode using a code page other than the default.

convertVietnameseDocument(codePageOrigin: number): void;

Parameters

codePageOrigin

number

The code page to use.

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

copyStylesFromTemplate(StyleTemplate)

Copies styles from the specified template to the document.

copyStylesFromTemplate(StyleTemplate: string): void;

Parameters

StyleTemplate

string

The template to copy styles from.

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

countNumberedItems(options)

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Returns the number of bulleted or numbered items and LISTNUM fields in the document.

countNumberedItems(options?: Word.DocumentCountNumberedItemsOptions): OfficeExtension.ClientResult<number>;

Parameters

options
Word.DocumentCountNumberedItemsOptions

Optional. Configuration options for counting numbered items.

Returns

The count of numbered items.

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

deleteAllComments()

Deletes all comments from the document.

deleteAllComments(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

deleteAllCommentsShown()

Deletes all revisions in the document that are displayed on the screen.

deleteAllCommentsShown(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

deleteAllInkAnnotations()

Deletes all handwritten ink annotations in the document.

deleteAllInkAnnotations(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

deleteBookmark(name)

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

deleteBookmark(name: string): void;

Parameters

name

string

The case-insensitive bookmark name.

Returns

void

Remarks

[ API set: WordApi 1.4 ]

detectLanguage()

Analyzes the document text to determine the language.

detectLanguage(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.3 ]

endReview(options)

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Terminates a review of the file that has been sent for review.

endReview(options?: Word.DocumentEndReviewOptions): void;

Parameters

options
Word.DocumentEndReviewOptions

Optional. Configuration options for ending the review process.

Returns

void

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

exportAsFixedFormat(outputFileName, exportFormat, options)

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Saves the document in PDF or XPS format.

exportAsFixedFormat(outputFileName: string, exportFormat: Word.ExportFormat, options?: Word.DocumentExportAsFixedFormatOptions): void;

Parameters

outputFileName

string

The name of the output file.

exportFormat
Word.ExportFormat

The export format.

options
Word.DocumentExportAsFixedFormatOptions

Optional. Configuration options for the export operation.

Returns

void

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

exportAsFixedFormat(outputFileName, exportFormat, options)

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Saves the document in PDF or XPS format.

exportAsFixedFormat(outputFileName: string, exportFormat: "Pdf" | "Xps", options?: Word.DocumentExportAsFixedFormatOptions): void;

Parameters

outputFileName

string

The name of the output file.

exportFormat

"Pdf" | "Xps"

The export format.

options
Word.DocumentExportAsFixedFormatOptions

Optional. Configuration options for the export operation.

Returns

void

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

exportAsFixedFormat2(outputFileName, exportFormat, options)

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Saves the document in PDF or XPS format.

exportAsFixedFormat2(outputFileName: string, exportFormat: Word.ExportFormat, options?: Word.DocumentExportAsFixedFormat2Options): void;

Parameters

outputFileName

string

The output file name.

exportFormat
Word.ExportFormat

The format to export (PDF/XPS).

options
Word.DocumentExportAsFixedFormat2Options

Optional. Configuration options for the export operation.

Returns

void

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

exportAsFixedFormat2(outputFileName, exportFormat, options)

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Saves the document in PDF or XPS format.

exportAsFixedFormat2(outputFileName: string, exportFormat: "Pdf" | "Xps", options?: Word.DocumentExportAsFixedFormat2Options): void;

Parameters

outputFileName

string

The output file name.

exportFormat

"Pdf" | "Xps"

The format to export (PDF/XPS).

options
Word.DocumentExportAsFixedFormat2Options

Optional. Configuration options for the export operation.

Returns

void

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

exportAsFixedFormat3(outputFileName, exportFormat, options)

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Saves the document in PDF or XPS format with improved tagging.

exportAsFixedFormat3(outputFileName: string, exportFormat: Word.ExportFormat, options?: Word.DocumentExportAsFixedFormat3Options): void;

Parameters

outputFileName

string

The output file name.

exportFormat
Word.ExportFormat

The format to export (PDF/XPS).

options
Word.DocumentExportAsFixedFormat3Options

Optional. Configuration options for the export operation.

Returns

void

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

exportAsFixedFormat3(outputFileName, exportFormat, options)

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Saves the document in PDF or XPS format with improved tagging.

exportAsFixedFormat3(outputFileName: string, exportFormat: "Pdf" | "Xps", options?: Word.DocumentExportAsFixedFormat3Options): void;

Parameters

outputFileName

string

The output file name.

exportFormat

"Pdf" | "Xps"

The format to export (PDF/XPS).

options
Word.DocumentExportAsFixedFormat3Options

Optional. Configuration options for the export operation.

Returns

void

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

fitToPages()

Decreases the font size of text just enough so that the document page count drops by one.

fitToPages(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Displays a cached document, if it has already been downloaded. Otherwise, this method resolves the hyperlink, downloads the target document, and displays the document in the appropriate application.

followHyperlink(options?: Word.DocumentFollowHyperlinkOptions): void;

Parameters

options
Word.DocumentFollowHyperlinkOptions

Optional. Configuration options for following the hyperlink.

Returns

void

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

freezeLayout()

Fixes the layout of the document in Web view.

freezeLayout(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

getAnnotationById(id)

Gets the annotation by ID. Throws an ItemNotFound error if annotation isn't found.

getAnnotationById(id: string): Word.Annotation;

Parameters

id

string

The ID of the annotation to get.

Returns

Remarks

[ API set: WordApi 1.7 ]

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

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

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}`
    );
  }
});

getCrossReferenceItems(referenceType)

Returns an array of items that can be cross-referenced based on the specified cross-reference type.

getCrossReferenceItems(referenceType: Word.ReferenceType): OfficeExtension.ClientResult<string[]>;

Parameters

referenceType
Word.ReferenceType

The type of reference.

Returns

Remarks

[ API set: WordApiDesktop 1.4 ]

getCrossReferenceItems(referenceType)

Returns an array of items that can be cross-referenced based on the specified cross-reference type.

getCrossReferenceItems(referenceType: "NumberedItem" | "Heading" | "Bookmark" | "Footnote" | "Endnote"): OfficeExtension.ClientResult<string[]>;

Parameters

referenceType

"NumberedItem" | "Heading" | "Bookmark" | "Footnote" | "Endnote"

The type of reference.

Returns

Remarks

[ API set: WordApiDesktop 1.4 ]

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 ]

getParagraphByUniqueLocalId(id)

Gets the paragraph by its unique local ID. Throws an ItemNotFound error if the collection is empty.

getParagraphByUniqueLocalId(id: string): Word.Paragraph;

Parameters

id

string

Unique local ID in standard 8-4-4-4-12 GUID format without curly braces. Note that the ID differs across sessions and coauthors.

Returns

Remarks

[ API set: WordApi 1.6 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/onadded-event.yaml

await Word.run(async (context) => {
  const paragraphId = (document.getElementById("paragraph-id") as HTMLInputElement).value;
  const paragraph: Word.Paragraph = context.document.getParagraphByUniqueLocalId(paragraphId);
  paragraph.load();
  await paragraph.context.sync();

  console.log(paragraph);
});

getRange(options)

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Returns a Range object by using the specified starting and ending character positions.

getRange(options?: Word.DocumentRangeOptions): Word.Range;

Parameters

options
Word.DocumentRangeOptions

Optional. Configuration options for specifying the range parameters.

Returns

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

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 available styles stored with the document.
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}`);
});

goTo(options)

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Returns a Range object that represents the start position of the specified item, such as a page, bookmark, or field.

goTo(options?: Word.GoToOptions): Word.Range;

Parameters

options
Word.GoToOptions

Optional. Configuration options for specifying the goTo parameters.

Returns

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

importStylesFromJson(stylesJson, importedStylesConflictBehavior)

Import styles from a JSON-formatted string.

importStylesFromJson(stylesJson: string, importedStylesConflictBehavior?: Word.ImportedStylesConflictBehavior): OfficeExtension.ClientResult<string[]>;

Parameters

stylesJson

string

A JSON-formatted string representing the styles.

importedStylesConflictBehavior
Word.ImportedStylesConflictBehavior

Optional. Specifies how to handle any imported styles with the same name as existing styles in the current document. The default value is ignore.

Returns

Remarks

[ API set: WordApi 1.6 ]

Note: The importedStylesConflictBehavior parameter was introduced in WordApiDesktop 1.1.

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/40-tables/manage-custom-style.yaml

// Imports styles from JSON.
await Word.run(async (context) => {
  const str =
    '{"styles":[{"baseStyle":"Default Paragraph Font","builtIn":false,"inUse":true,"linked":false,"nameLocal":"NewCharStyle","priority":2,"quickStyle":true,"type":"Character","unhideWhenUsed":false,"visibility":false,"paragraphFormat":null,"font":{"name":"DengXian Light","size":16.0,"bold":true,"italic":false,"color":"#F1A983","underline":"None","subscript":false,"superscript":true,"strikeThrough":true,"doubleStrikeThrough":false,"highlightColor":null,"hidden":false},"shading":{"backgroundPatternColor":"#FF0000"}},{"baseStyle":"Normal","builtIn":false,"inUse":true,"linked":false,"nextParagraphStyle":"NewParaStyle","nameLocal":"NewParaStyle","priority":1,"quickStyle":true,"type":"Paragraph","unhideWhenUsed":false,"visibility":false,"paragraphFormat":{"alignment":"Centered","firstLineIndent":0.0,"keepTogether":false,"keepWithNext":false,"leftIndent":72.0,"lineSpacing":18.0,"lineUnitAfter":0.0,"lineUnitBefore":0.0,"mirrorIndents":false,"outlineLevel":"OutlineLevelBodyText","rightIndent":72.0,"spaceAfter":30.0,"spaceBefore":30.0,"widowControl":true},"font":{"name":"DengXian","size":14.0,"bold":true,"italic":true,"color":"#8DD873","underline":"Single","subscript":false,"superscript":false,"strikeThrough":false,"doubleStrikeThrough":true,"highlightColor":null,"hidden":false},"shading":{"backgroundPatternColor":"#00FF00"}},{"baseStyle":"Table Normal","builtIn":false,"inUse":true,"linked":false,"nextParagraphStyle":"NewTableStyle","nameLocal":"NewTableStyle","priority":100,"type":"Table","unhideWhenUsed":false,"visibility":false,"paragraphFormat":{"alignment":"Left","firstLineIndent":0.0,"keepTogether":false,"keepWithNext":false,"leftIndent":0.0,"lineSpacing":12.0,"lineUnitAfter":0.0,"lineUnitBefore":0.0,"mirrorIndents":false,"outlineLevel":"OutlineLevelBodyText","rightIndent":0.0,"spaceAfter":0.0,"spaceBefore":0.0,"widowControl":true},"font":{"name":"DengXian","size":20.0,"bold":false,"italic":true,"color":"#D86DCB","underline":"None","subscript":false,"superscript":false,"strikeThrough":false,"doubleStrikeThrough":false,"highlightColor":null,"hidden":false},"tableStyle":{"allowBreakAcrossPage":true,"alignment":"Left","bottomCellMargin":0.0,"leftCellMargin":0.08,"rightCellMargin":0.08,"topCellMargin":0.0,"cellSpacing":0.0},"shading":{"backgroundPatternColor":"#60CAF3"}}]}';
  const styles = context.document.importStylesFromJson(str);

  // If you'd like to set how conflicting styles are handled, use the importedStylesConflictBehavior parameter that was introduced in the Desktop 1.1 requirement set. "Ignore" is the default.
  ////const styles = context.document.importStylesFromJson(str, Word.ImportedStylesConflictBehavior.Ignore);

  await context.sync();
  console.log("Styles imported from JSON:", styles);
});

importStylesFromJson(stylesJson, importedStylesConflictBehavior)

Import styles from a JSON-formatted string.

importStylesFromJson(stylesJson: string, importedStylesConflictBehavior?: "Ignore" | "Overwrite" | "CreateNew"): OfficeExtension.ClientResult<string[]>;

Parameters

stylesJson

string

A JSON-formatted string representing the styles.

importedStylesConflictBehavior

"Ignore" | "Overwrite" | "CreateNew"

Optional. Specifies how to handle any imported styles with the same name as existing styles in the current document. The default value is ignore.

Returns

Remarks

[ API set: WordApi 1.6 ]

Note: The importedStylesConflictBehavior parameter was introduced in WordApiDesktop 1.1.

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

The Base64-encoded content of a .docx file.

insertLocation

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

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 ]

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

lockServerFile()

Locks the file on the server preventing anyone else from editing it.

lockServerFile(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

makeCompatibilityDefault()

Sets the compatibility options.

makeCompatibilityDefault(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

manualHyphenation()

Initiates manual hyphenation of a document, one line at a time.

manualHyphenation(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.3 ]

merge(fileName, options)

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Merges the changes marked with revision marks from one document to another.

merge(fileName: string, options?: Word.DocumentMergeOptions): void;

Parameters

fileName

string

The name of the file to merge.

options
Word.DocumentMergeOptions

Optional. Configuration options for the merge operation.

Returns

void

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

post()

Posts the document to a public folder in Microsoft Exchange.

post(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

presentIt()

Opens PowerPoint with the Word document loaded.

presentIt(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

printOut(options)

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Prints all or part of the document.

printOut(options?: Word.DocumentPrintOutOptions): void;

Parameters

options
Word.DocumentPrintOutOptions

Optional. Configuration options for the print operation.

Returns

void

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

printPreview()

Switches the view to print preview.

printPreview(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

protect(type, options)

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Protects the document from unauthorized changes.

protect(type: Word.ProtectionType, options?: Word.DocumentProtectOptions): void;

Parameters

type
Word.ProtectionType

The type of protection.

options
Word.DocumentProtectOptions

Optional. Configuration options for document protection.

Returns

void

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

protect(type, options)

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Protects the document from unauthorized changes.

protect(type: "NoProtection" | "AllowOnlyRevisions" | "AllowOnlyComments" | "AllowOnlyFormFields" | "AllowOnlyReading", options?: Word.DocumentProtectOptions): void;

Parameters

type

"NoProtection" | "AllowOnlyRevisions" | "AllowOnlyComments" | "AllowOnlyFormFields" | "AllowOnlyReading"

The type of protection.

options
Word.DocumentProtectOptions

Optional. Configuration options for document protection.

Returns

void

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

redo(times)

Redoes the last action that was undone (reverses the undo method).

redo(times?: number): OfficeExtension.ClientResult<boolean>;

Parameters

times

number

Optional. The number of actions to redo.

Returns

true if the actions were redone successfully; otherwise, false.

Remarks

[ API set: WordApiDesktop 1.4 ]

rejectAllRevisions()

Rejects all tracked changes in the document.

rejectAllRevisions(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

rejectAllRevisionsShown()

Rejects all revisions in the document that are displayed on the screen.

rejectAllRevisionsShown(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

reload()

Reloads a cached document by resolving the hyperlink to the document and downloading it.

reload(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

reloadAs(encoding)

Reloads the document based on an HTML document, using the document encoding.

reloadAs(encoding: Word.DocumentEncoding): void;

Parameters

encoding
Word.DocumentEncoding

The encoding to use.

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

reloadAs(encoding)

Reloads the document based on an HTML document, using the document encoding.

reloadAs(encoding: "Thai" | "JapaneseShiftJis" | "SimplifiedChineseGbk" | "Korean" | "TraditionalChineseBig5" | "UnicodeLittleEndian" | "UnicodeBigEndian" | "CentralEuropean" | "Cyrillic" | "Western" | "Greek" | "Turkish" | "Hebrew" | "Arabic" | "Baltic" | "Vietnamese" | "AutoDetect" | "JapaneseAutoDetect" | "SimplifiedChineseAutoDetect" | "KoreanAutoDetect" | "TraditionalChineseAutoDetect" | "CyrillicAutoDetect" | "GreekAutoDetect" | "ArabicAutoDetect" | "Iso88591Latin1" | "Iso88592CentralEurope" | "Iso88593Latin3" | "Iso88594Baltic" | "Iso88595Cyrillic" | "Iso88596Arabic" | "Iso88597Greek" | "Iso88598Hebrew" | "Iso88599Turkish" | "Iso885915Latin9" | "Iso88598HebrewLogical" | "Iso2022JpNoHalfwidthKatakana" | "Iso2022JpJisX02021984" | "Iso2022JpJisX02011989" | "Iso2022Kr" | "Iso2022CnTraditionalChinese" | "Iso2022CnSimplifiedChinese" | "MacRoman" | "MacJapanese" | "MacTraditionalChineseBig5" | "MacKorean" | "MacArabic" | "MacHebrew" | "MacGreek1" | "MacCyrillic" | "MacSimplifiedChineseGb2312" | "MacRomania" | "MacUkraine" | "MacLatin2" | "MacIcelandic" | "MacTurkish" | "MacCroatia" | "EbcdicUsCanada" | "EbcdicInternational" | "EbcdicMultilingualRoeceLatin2" | "EbcdicGreekModern" | "EbcdicTurkishLatin5" | "EbcdicGermany" | "EbcdicDenmarkNorway" | "EbcdicFinlandSweden" | "EbcdicItaly" | "EbcdicLatinAmericaSpain" | "EbcdicUnitedKingdom" | "EbcdicJapaneseKatakanaExtended" | "EbcdicFrance" | "EbcdicArabic" | "EbcdicGreek" | "EbcdicHebrew" | "EbcdicKoreanExtended" | "EbcdicThai" | "EbcdicIcelandic" | "EbcdicTurkish" | "EbcdicRussian" | "EbcdicSerbianBulgarian" | "EbcdicJapaneseKatakanaExtendedAndJapanese" | "EbcdicUsCanadaAndJapanese" | "EbcdicKoreanExtendedAndKorean" | "EbcdicSimplifiedChineseExtendedAndSimplifiedChinese" | "EbcdicUsCanadaAndTraditionalChinese" | "EbcdicJapaneseLatinExtendedAndJapanese" | "OemUnitedStates" | "OemGreek437G" | "OemBaltic" | "OemMultilingualLatinI" | "OemMultilingualLatinIi" | "OemCyrillic" | "OemTurkish" | "OemPortuguese" | "OemIcelandic" | "OemHebrew" | "OemCanadianFrench" | "OemArabic" | "OemNordic" | "OemCyrillicIi" | "OemModernGreek" | "EucJapanese" | "EucChineseSimplifiedChinese" | "EucKorean" | "EucTaiwaneseTraditionalChinese" | "IsciiDevanagari" | "IsciiBengali" | "IsciiTamil" | "IsciiTelugu" | "IsciiAssamese" | "IsciiOriya" | "IsciiKannada" | "IsciiMalayalam" | "IsciiGujarati" | "IsciiPunjabi" | "ArabicAsmo" | "ArabicTransparentAsmo" | "KoreanJohab" | "TaiwanCns" | "TaiwanTca" | "TaiwanEten" | "TaiwanIbm5550" | "TaiwanTeleText" | "TaiwanWang" | "Ia5Irv" | "Ia5German" | "Ia5Swedish" | "Ia5Norwegian" | "UsaAscii" | "T61" | "Iso6937NonSpacingAccent" | "Koi8R" | "ExtAlphaLowercase" | "Koi8U" | "Europa3" | "HzGbSimplifiedChinese" | "SimplifiedChineseGb18030" | "Utf7" | "Utf8"): void;

Parameters

encoding

"Thai" | "JapaneseShiftJis" | "SimplifiedChineseGbk" | "Korean" | "TraditionalChineseBig5" | "UnicodeLittleEndian" | "UnicodeBigEndian" | "CentralEuropean" | "Cyrillic" | "Western" | "Greek" | "Turkish" | "Hebrew" | "Arabic" | "Baltic" | "Vietnamese" | "AutoDetect" | "JapaneseAutoDetect" | "SimplifiedChineseAutoDetect" | "KoreanAutoDetect" | "TraditionalChineseAutoDetect" | "CyrillicAutoDetect" | "GreekAutoDetect" | "ArabicAutoDetect" | "Iso88591Latin1" | "Iso88592CentralEurope" | "Iso88593Latin3" | "Iso88594Baltic" | "Iso88595Cyrillic" | "Iso88596Arabic" | "Iso88597Greek" | "Iso88598Hebrew" | "Iso88599Turkish" | "Iso885915Latin9" | "Iso88598HebrewLogical" | "Iso2022JpNoHalfwidthKatakana" | "Iso2022JpJisX02021984" | "Iso2022JpJisX02011989" | "Iso2022Kr" | "Iso2022CnTraditionalChinese" | "Iso2022CnSimplifiedChinese" | "MacRoman" | "MacJapanese" | "MacTraditionalChineseBig5" | "MacKorean" | "MacArabic" | "MacHebrew" | "MacGreek1" | "MacCyrillic" | "MacSimplifiedChineseGb2312" | "MacRomania" | "MacUkraine" | "MacLatin2" | "MacIcelandic" | "MacTurkish" | "MacCroatia" | "EbcdicUsCanada" | "EbcdicInternational" | "EbcdicMultilingualRoeceLatin2" | "EbcdicGreekModern" | "EbcdicTurkishLatin5" | "EbcdicGermany" | "EbcdicDenmarkNorway" | "EbcdicFinlandSweden" | "EbcdicItaly" | "EbcdicLatinAmericaSpain" | "EbcdicUnitedKingdom" | "EbcdicJapaneseKatakanaExtended" | "EbcdicFrance" | "EbcdicArabic" | "EbcdicGreek" | "EbcdicHebrew" | "EbcdicKoreanExtended" | "EbcdicThai" | "EbcdicIcelandic" | "EbcdicTurkish" | "EbcdicRussian" | "EbcdicSerbianBulgarian" | "EbcdicJapaneseKatakanaExtendedAndJapanese" | "EbcdicUsCanadaAndJapanese" | "EbcdicKoreanExtendedAndKorean" | "EbcdicSimplifiedChineseExtendedAndSimplifiedChinese" | "EbcdicUsCanadaAndTraditionalChinese" | "EbcdicJapaneseLatinExtendedAndJapanese" | "OemUnitedStates" | "OemGreek437G" | "OemBaltic" | "OemMultilingualLatinI" | "OemMultilingualLatinIi" | "OemCyrillic" | "OemTurkish" | "OemPortuguese" | "OemIcelandic" | "OemHebrew" | "OemCanadianFrench" | "OemArabic" | "OemNordic" | "OemCyrillicIi" | "OemModernGreek" | "EucJapanese" | "EucChineseSimplifiedChinese" | "EucKorean" | "EucTaiwaneseTraditionalChinese" | "IsciiDevanagari" | "IsciiBengali" | "IsciiTamil" | "IsciiTelugu" | "IsciiAssamese" | "IsciiOriya" | "IsciiKannada" | "IsciiMalayalam" | "IsciiGujarati" | "IsciiPunjabi" | "ArabicAsmo" | "ArabicTransparentAsmo" | "KoreanJohab" | "TaiwanCns" | "TaiwanTca" | "TaiwanEten" | "TaiwanIbm5550" | "TaiwanTeleText" | "TaiwanWang" | "Ia5Irv" | "Ia5German" | "Ia5Swedish" | "Ia5Norwegian" | "UsaAscii" | "T61" | "Iso6937NonSpacingAccent" | "Koi8R" | "ExtAlphaLowercase" | "Koi8U" | "Europa3" | "HzGbSimplifiedChinese" | "SimplifiedChineseGb18030" | "Utf7" | "Utf8"

The encoding to use.

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

removeDocumentInformation(removeDocInfoType)

Removes sensitive information, properties, comments, and other metadata from the document.

removeDocumentInformation(removeDocInfoType: Word.RemoveDocInfoType): void;

Parameters

removeDocInfoType
Word.RemoveDocInfoType

The type of document info to remove.

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

removeDocumentInformation(removeDocInfoType)

Removes sensitive information, properties, comments, and other metadata from the document.

removeDocumentInformation(removeDocInfoType: "Comments" | "Revisions" | "Versions" | "RemovePersonalInformation" | "EmailHeader" | "RoutingSlip" | "SendForReview" | "DocumentProperties" | "Template" | "DocumentWorkspace" | "InkAnnotations" | "DocumentServerProperties" | "DocumentManagementPolicy" | "ContentType" | "TaskpaneWebExtensions" | "AtMentions" | "DocumentTasks" | "DocumentIntelligence" | "CommentReactions" | "All"): void;

Parameters

removeDocInfoType

"Comments" | "Revisions" | "Versions" | "RemovePersonalInformation" | "EmailHeader" | "RoutingSlip" | "SendForReview" | "DocumentProperties" | "Template" | "DocumentWorkspace" | "InkAnnotations" | "DocumentServerProperties" | "DocumentManagementPolicy" | "ContentType" | "TaskpaneWebExtensions" | "AtMentions" | "DocumentTasks" | "DocumentIntelligence" | "CommentReactions" | "All"

The type of document info to remove.

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

removeLockedStyles()

Purges the document of locked styles when formatting restrictions have been applied in the document.

removeLockedStyles(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

removeNumbers(numberType)

Removes numbers or bullets from the document.

removeNumbers(numberType?: Word.NumberType): void;

Parameters

numberType
Word.NumberType

Optional. The type of numbering to remove.

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

removeNumbers(numberType)

Removes numbers or bullets from the document.

removeNumbers(numberType?: "Paragraph" | "ListNum" | "AllNumbers"): void;

Parameters

numberType

"Paragraph" | "ListNum" | "AllNumbers"

Optional. The type of numbering to remove.

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

removeTheme()

Removes the active theme from the current document.

removeTheme(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

repaginate()

Repaginates the entire document.

repaginate(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

replyWithChanges(options)

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Sends an email message to the author of the document that has been sent out for review, notifying them that a reviewer has completed review of the document.

replyWithChanges(options?: Word.DocumentReplyWithChangesOptions): void;

Parameters

options
Word.DocumentReplyWithChangesOptions

Optional. Configuration options for replying with changes.

Returns

void

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

resetFormFields()

Clears all form fields in the document, preparing the form to be filled in again.

resetFormFields(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

returnToLastReadPosition()

Returns the document to the last saved reading position.

returnToLastReadPosition(): OfficeExtension.ClientResult<number>;

Returns

Remarks

[ API set: WordApiDesktop 1.4 ]

runAutoMacro(autoMacro)

Runs an auto macro that's stored in the document. If the specified auto macro doesn't exist, nothing happens.

runAutoMacro(autoMacro: Word.AutoMacro): void;

Parameters

autoMacro
Word.AutoMacro

The auto macro to run.

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

runAutoMacro(autoMacro)

Runs an auto macro that's stored in the document. If the specified auto macro doesn't exist, nothing happens.

runAutoMacro(autoMacro: "StartWord" | "New" | "Open" | "Close" | "Exit" | "Sync"): void;

Parameters

autoMacro

"StartWord" | "New" | "Open" | "Close" | "Exit" | "Sync"

The auto macro to run.

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

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(saveBehavior, fileName)

Saves the document.

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

Parameters

saveBehavior

"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.

saveAsQuickStyleSet(fileName)

Saves the group of quick styles currently in use.

saveAsQuickStyleSet(fileName: string): void;

Parameters

fileName

string

The name of the file to save.

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

search(searchText, searchOptions)

Performs a search with the specified search options on the scope of the whole document. The search results are a collection of Range objects.

search(searchText: string, searchOptions?: Word.SearchOptions | {
            ignorePunct?: boolean;
            ignoreSpace?: boolean;
            matchCase?: boolean;
            matchPrefix?: boolean;
            matchSuffix?: boolean;
            matchWholeWord?: boolean;
            matchWildcards?: boolean;
        }): Word.RangeCollection;

Parameters

searchText

string

The text to search for.

searchOptions

Word.SearchOptions | { ignorePunct?: boolean; ignoreSpace?: boolean; matchCase?: boolean; matchPrefix?: boolean; matchSuffix?: boolean; matchWholeWord?: boolean; matchWildcards?: boolean; }

Optional. Options that define how the search is performed.

Returns

Remarks

[ API set: WordApi 1.7 ]

select()

Selects the contents of the document.

select(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

selectContentControlsByTag(tag)

Returns all content controls with the specified tag.

selectContentControlsByTag(tag: string): Word.ContentControlCollection;

Parameters

tag

string

The tag value to filter content controls.

Returns

Remarks

[ API set: WordApiDesktop 1.4 ]

selectContentControlsByTitle(title)

Returns a ContentControlCollection object that represents all the content controls in the document with the specified title.

selectContentControlsByTitle(title: string): Word.ContentControlCollection;

Parameters

title

string

The title of the content controls.

Returns

Remarks

[ API set: WordApiDesktop 1.4 ]

selectLinkedControls(node)

Returns a ContentControlCollection object that represents all content controls in the document that are linked to the specific custom XML node.

selectLinkedControls(node: Word.CustomXmlNode): Word.ContentControlCollection;

Parameters

node
Word.CustomXmlNode

The custom XML node.

Returns

Remarks

[ API set: WordApiDesktop 1.4 ]

selectNodes(xPath, options)

Returns an XmlNodeCollection object that represents all the nodes that match the XPath parameter in the order in which they appear in the document.

selectNodes(xPath: string, options?: Word.SelectNodesOptions): Word.XmlNodeCollection;

Parameters

xPath

string

The XPath expression.

options
Word.SelectNodesOptions

Optional. Configuration options for the nodes selection.

Returns

Remarks

[ API set: WordApiDesktop 1.4 ]

selectSingleNode(xPath, options)

Returns an XmlNode object that represents the first node that matches the XPath parameter in the document.

selectSingleNode(xPath: string, options?: Word.SelectSingleNodeOptions): Word.XmlNode;

Parameters

xPath

string

The XPath expression.

options
Word.SelectSingleNodeOptions

Optional. Configuration options for the node selection.

Returns

Remarks

[ API set: WordApiDesktop 1.4 ]

selectUnlinkedControls(stream)

Returns a ContentControlCollection object that represents all content controls in the document that are not linked to an XML node.

selectUnlinkedControls(stream?: Word.CustomXmlPart): Word.ContentControlCollection;

Parameters

stream
Word.CustomXmlPart

Optional. The custom XML part.

Returns

Remarks

[ API set: WordApiDesktop 1.4 ]

sendFax(address, subject)

Sends the document as a fax, without any user interaction.

sendFax(address: string, subject?: string): void;

Parameters

address

string

The fax address.

subject

string

Optional. The subject of the fax.

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

sendFaxOverInternet(options)

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Sends the document to a fax service provider, who faxes the document to one or more specified recipients.

sendFaxOverInternet(options?: Word.DocumentSendFaxOverInternetOptions): void;

Parameters

options
Word.DocumentSendFaxOverInternetOptions

Optional. Configuration options for sending the fax over the internet.

Returns

void

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

sendForReview(options)

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Sends the document in an email message for review by the specified recipients.

sendForReview(options?: Word.DocumentSendForReviewOptions): void;

Parameters

options
Word.DocumentSendForReviewOptions

Optional. Configuration options for sending the document for review.

Returns

void

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

sendMail()

Opens a message window for sending the document through Microsoft Exchange.

sendMail(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

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

setDefaultTableStyle(style, setInTemplate)

Specifies the table style to use for newly created tables in the document.

setDefaultTableStyle(style: string, setInTemplate: boolean): void;

Parameters

style

string

The style to apply.

setInTemplate

boolean

Whether to set the style in the template.

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

setPasswordEncryptionOptions(passwordEncryptionProvider, passwordEncryptionAlgorithm, passwordEncryptionKeyLength, passwordEncryptFileProperties)

Sets the options Microsoft Word uses for encrypting documents with passwords.

setPasswordEncryptionOptions(passwordEncryptionProvider: string, passwordEncryptionAlgorithm: string, passwordEncryptionKeyLength: number, passwordEncryptFileProperties?: boolean): void;

Parameters

passwordEncryptionProvider

string

The encryption provider.

passwordEncryptionAlgorithm

string

The encryption algorithm.

passwordEncryptionKeyLength

number

The key length.

passwordEncryptFileProperties

boolean

Optional. Whether to encrypt file properties.

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

toggleFormsDesign()

Switches form design mode on or off.

toggleFormsDesign(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

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's 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

transformDocument(path, dataOnly)

Applies the specified Extensible Stylesheet Language Transformation (XSLT) file to this document and replaces the document with the results.

transformDocument(path: string, dataOnly?: boolean): void;

Parameters

path

string

The path to the XSLT file.

dataOnly

boolean

Optional. Whether to use data only.

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

undo(times)

Undoes the last action or a sequence of actions, which are displayed in the Undo list.

undo(times?: number): OfficeExtension.ClientResult<boolean>;

Parameters

times

number

Optional. The number of actions to undo.

Returns

true if the actions were undone successfully; otherwise, false.

Remarks

[ API set: WordApiDesktop 1.4 ]

undoClear()

Clears the list of actions that can be undone in the document.

undoClear(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

unprotect(password)

Removes protection from the document.

unprotect(password?: string): void;

Parameters

password

string

Optional. The password to unprotect the document.

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

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

updateStyles()

Copies all styles from the attached template into the document, overwriting any existing styles in the document that have the same name.

updateStyles(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

viewCode()

Displays the code window for the selected Microsoft ActiveX control in the document.

viewCode(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

viewPropertyBrowser()

Displays the property window for the selected Microsoft ActiveX control in the document.

viewPropertyBrowser(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

webPagePreview()

Displays a preview of the current document as it would look if saved as a webpage.

webPagePreview(): void;

Returns

void

Remarks

[ API set: WordApiDesktop 1.4 ]

Event Details

onAnnotationClicked

Occurs when the user clicks an annotation (or selects it using Alt+Down).

readonly onAnnotationClicked: OfficeExtension.EventHandlers<Word.AnnotationClickedEventArgs>;

Event Type

Remarks

[ API set: WordApi 1.7 ]

Examples

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

// Registers event handlers.
await Word.run(async (context) => {
  eventContexts[0] = context.document.onParagraphAdded.add(paragraphChanged);
  eventContexts[1] = context.document.onParagraphChanged.add(paragraphChanged);

  eventContexts[2] = context.document.onAnnotationClicked.add(onClickedHandler);
  eventContexts[3] = context.document.onAnnotationHovered.add(onHoveredHandler);
  eventContexts[4] = context.document.onAnnotationInserted.add(onInsertedHandler);
  eventContexts[5] = context.document.onAnnotationRemoved.add(onRemovedHandler);
  eventContexts[6] = context.document.onAnnotationPopupAction.add(onPopupActionHandler);

  await context.sync();

  console.log("Event handlers registered.");
});

...

async function onClickedHandler(args: Word.AnnotationClickedEventArgs) {
  await Word.run(async (context) => {
    const annotation: Word.Annotation = context.document.getAnnotationById(args.id);
    annotation.load("critiqueAnnotation");

    await context.sync();

    console.log(`AnnotationClicked: ID ${args.id}:`, annotation.critiqueAnnotation.critique);
  });
}

onAnnotationHovered

Occurs when the user hovers the cursor over an annotation.

readonly onAnnotationHovered: OfficeExtension.EventHandlers<Word.AnnotationHoveredEventArgs>;

Event Type

Remarks

[ API set: WordApi 1.7 ]

Examples

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

// Registers event handlers.
await Word.run(async (context) => {
  eventContexts[0] = context.document.onParagraphAdded.add(paragraphChanged);
  eventContexts[1] = context.document.onParagraphChanged.add(paragraphChanged);

  eventContexts[2] = context.document.onAnnotationClicked.add(onClickedHandler);
  eventContexts[3] = context.document.onAnnotationHovered.add(onHoveredHandler);
  eventContexts[4] = context.document.onAnnotationInserted.add(onInsertedHandler);
  eventContexts[5] = context.document.onAnnotationRemoved.add(onRemovedHandler);
  eventContexts[6] = context.document.onAnnotationPopupAction.add(onPopupActionHandler);

  await context.sync();

  console.log("Event handlers registered.");
});

...

async function onHoveredHandler(args: Word.AnnotationHoveredEventArgs) {
  await Word.run(async (context) => {
    const annotation: Word.Annotation = context.document.getAnnotationById(args.id);
    annotation.load("critiqueAnnotation");

    await context.sync();

    console.log(`AnnotationHovered: ID ${args.id}:`, annotation.critiqueAnnotation.critique);
  });
}

onAnnotationInserted

Occurs when the user adds one or more annotations.

readonly onAnnotationInserted: OfficeExtension.EventHandlers<Word.AnnotationInsertedEventArgs>;

Event Type

Remarks

[ API set: WordApi 1.7 ]

Examples

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

// Registers event handlers.
await Word.run(async (context) => {
  eventContexts[0] = context.document.onParagraphAdded.add(paragraphChanged);
  eventContexts[1] = context.document.onParagraphChanged.add(paragraphChanged);

  eventContexts[2] = context.document.onAnnotationClicked.add(onClickedHandler);
  eventContexts[3] = context.document.onAnnotationHovered.add(onHoveredHandler);
  eventContexts[4] = context.document.onAnnotationInserted.add(onInsertedHandler);
  eventContexts[5] = context.document.onAnnotationRemoved.add(onRemovedHandler);
  eventContexts[6] = context.document.onAnnotationPopupAction.add(onPopupActionHandler);

  await context.sync();

  console.log("Event handlers registered.");
});

...

async function onInsertedHandler(args: Word.AnnotationInsertedEventArgs) {
  await Word.run(async (context) => {
    const annotations = [];
    for (let i = 0; i < args.ids.length; i++) {
      let annotation: Word.Annotation = context.document.getAnnotationById(args.ids[i]);
      annotation.load("id,critiqueAnnotation");

      annotations.push(annotation);
    }

    await context.sync();

    for (let annotation of annotations) {
      console.log(`AnnotationInserted: ID ${annotation.id}:`, annotation.critiqueAnnotation.critique);
    }
  });
}

onAnnotationPopupAction

Occurs when the user performs an action in an annotation pop-up menu.

readonly onAnnotationPopupAction: OfficeExtension.EventHandlers<Word.AnnotationPopupActionEventArgs>;

Event Type

Remarks

[ API set: WordApi 1.8 ]

Examples

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

// Registers event handlers.
await Word.run(async (context) => {
  eventContexts[0] = context.document.onParagraphAdded.add(paragraphChanged);
  eventContexts[1] = context.document.onParagraphChanged.add(paragraphChanged);

  eventContexts[2] = context.document.onAnnotationClicked.add(onClickedHandler);
  eventContexts[3] = context.document.onAnnotationHovered.add(onHoveredHandler);
  eventContexts[4] = context.document.onAnnotationInserted.add(onInsertedHandler);
  eventContexts[5] = context.document.onAnnotationRemoved.add(onRemovedHandler);
  eventContexts[6] = context.document.onAnnotationPopupAction.add(onPopupActionHandler);

  await context.sync();

  console.log("Event handlers registered.");
});

...

async function onPopupActionHandler(args: Word.AnnotationPopupActionEventArgs) {
  await Word.run(async (context) => {
    let message = `AnnotationPopupAction: ID ${args.id} = `;
    if (args.action === "Accept") {
      message += `Accepted: ${args.critiqueSuggestion}`;
    } else {
      message += "Rejected";
    }

    console.log(message);
  });
}

onAnnotationRemoved

Occurs when the user deletes one or more annotations.

readonly onAnnotationRemoved: OfficeExtension.EventHandlers<Word.AnnotationRemovedEventArgs>;

Event Type

Remarks

[ API set: WordApi 1.7 ]

Examples

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

// Registers event handlers.
await Word.run(async (context) => {
  eventContexts[0] = context.document.onParagraphAdded.add(paragraphChanged);
  eventContexts[1] = context.document.onParagraphChanged.add(paragraphChanged);

  eventContexts[2] = context.document.onAnnotationClicked.add(onClickedHandler);
  eventContexts[3] = context.document.onAnnotationHovered.add(onHoveredHandler);
  eventContexts[4] = context.document.onAnnotationInserted.add(onInsertedHandler);
  eventContexts[5] = context.document.onAnnotationRemoved.add(onRemovedHandler);
  eventContexts[6] = context.document.onAnnotationPopupAction.add(onPopupActionHandler);

  await context.sync();

  console.log("Event handlers registered.");
});

...

async function onRemovedHandler(args: Word.AnnotationRemovedEventArgs) {
  await Word.run(async (context) => {
    for (let id of args.ids) {
      console.log(`AnnotationRemoved: ID ${id}`);
    }
  });
}

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

onParagraphAdded

Occurs when the user adds new paragraphs.

readonly onParagraphAdded: OfficeExtension.EventHandlers<Word.ParagraphAddedEventArgs>;

Event Type

Remarks

[ API set: WordApi 1.6 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/onadded-event.yaml

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

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

...

async function paragraphAdded(event: Word.ParagraphAddedEventArgs) {
  await Word.run(async (context) => {
    console.log(`${event.type} event detected. IDs of paragraphs that were added:`, event.uniqueLocalIds);
  });
}

onParagraphChanged

Occurs when the user changes paragraphs.

readonly onParagraphChanged: OfficeExtension.EventHandlers<Word.ParagraphChangedEventArgs>;

Event Type

Remarks

[ API set: WordApi 1.6 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/onchanged-event.yaml

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

  console.log("Added event handler for when content is changed in paragraphs.");
});

...

async function paragraphChanged(event: Word.ParagraphChangedEventArgs) {
  await Word.run(async (context) => {
    console.log(`${event.type} event detected. IDs of paragraphs where content was changed:`, event.uniqueLocalIds);
  });
}

onParagraphDeleted

Occurs when the user deletes paragraphs.

readonly onParagraphDeleted: OfficeExtension.EventHandlers<Word.ParagraphDeletedEventArgs>;

Event Type

Remarks

[ API set: WordApi 1.6 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/ondeleted-event.yaml

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

  console.log("Added event handlers for when paragraphs are deleted.");
});

...

async function paragraphDeleted(event: Word.ParagraphDeletedEventArgs) {
  await Word.run(async (context) => {
    console.log(`${event.type} event detected. IDs of paragraphs that were deleted:`, event.uniqueLocalIds);
  });
}