Edit

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

Used by

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.

sensitivityLabel

Returns the sensitivity label of 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.