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
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
| active |
Gets the name of the active theme and formatting options. |
| active |
Gets the display name of the active theme. |
| active |
Gets the active window for the document. |
| are |
Gets whether Word encrypts file properties for password-protected documents. |
| are |
Specifies whether grammatical errors are marked by a wavy green line in the document. |
| are |
Specifies whether to use the default math settings when creating new equations. |
| are |
Specifies whether to disable features introduced after a specified version. |
| are |
Specifies whether Microsoft Word underlines spelling errors in the document. |
| are |
Specifies whether the styles in this document are updated to match the styles in the attached template each time the document is opened. |
| are |
Specifies whether Microsoft Word embeds TrueType fonts in the document when it's saved. |
| attached |
Specifies a |
| auto |
Specifies if automatic hyphenation is turned on for the document. |
| auto |
Specifies if the edits in the document are automatically saved. |
| background | Gets a |
| bibliography | Returns a |
| body | Gets the |
| bookmarks | Returns a |
| built |
Gets a |
| change |
Specifies the ChangeTracking mode. |
| characters | Gets the |
| coauthoring | Gets a |
| code |
Gets the code name for the document. |
| comments | Gets a |
| compatibility |
Gets the compatibility mode that Word uses when opening the document. |
| consecutive |
Specifies the maximum number of consecutive lines that can end with hyphens. |
| content | Gets a |
| content |
Gets the collection of |
| context | The request context associated with the object. This connects the add-in's process to the Office host application's process. |
| current |
Gets a random number that Word assigns to changes in the document. |
| custom |
Gets a |
| custom |
Gets the custom XML parts in the document. |
| default |
Specifies the interval (in points) between the default tab stops in the document. |
| default |
Specifies the browser frame for displaying a webpage via hyperlink. |
| document |
Returns a |
| do |
Specifies whether Word should not embed common system fonts. |
| encryption |
Specifies the name of the algorithm encryption provider that Microsoft Word uses when encrypting documents. |
| far |
Specifies the East Asian language used for line breaking. |
| far |
Specifies the line break control level. |
| fields | Gets a |
| formatting |
Specifies whether Word shows the next heading level when the previous is used. |
| formatting |
Specifies whether to show user-defined styles. |
| frames | Returns a |
| full |
Gets the name of a document, including the path. |
| grammatical |
Gets a |
| grid |
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. |
| grid |
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. |
| grid |
Specifies whether the character grid starts from the upper-left corner of the page. |
| grid |
Specifies the horizontal origin point for the invisible grid. |
| grid |
Specifies the vertical origin point for the invisible grid. |
| grid |
Specifies the interval for horizontal character gridlines in print layout view. |
| grid |
Specifies the interval for vertical character gridlines in print layout view. |
| has |
Gets whether a password is required to open the document. |
| has |
Gets whether the document has an attached Microsoft Visual Basic for Applications project. |
| hyperlinks | Returns a |
| hyphenate |
Specifies whether words in all capital letters can be hyphenated. |
| hyphenation |
Specifies the width of the hyphenation zone, in points. |
| indexes | Returns an |
| is |
Specifies whether automatic formatting options override formatting restrictions. |
| is |
Specifies whether charts in the active document use cell-reference data-point tracking. |
| is |
Specifies whether the compatibility option specified by the |
| is |
Specifies whether the document is final. |
| is |
Specifies whether Microsoft Word saves a subset of the embedded TrueType fonts with the document. |
| is |
Specifies whether Microsoft Word prints onto a preprinted form only the data entered in the corresponding online form. |
| is |
Specifies whether Microsoft Word saves the data entered in a form as a tab-delimited record for use in a database. |
| is |
Specifies whether a grammar check has been run on the document. |
| is |
Gets whether the most recent firing of the |
| is |
Gets whether the document is in form design mode. |
| is |
Specifies whether Word kerns half-width Latin characters and punctuation marks. |
| is |
Specifies whether to embed speech and handwriting data. |
| is |
Gets whether this document is a master document. |
| is |
Specifies whether Word optimizes the document for Word 97. |
| is |
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. |
| is |
Specifies whether users can change the Quick Style set. |
| is |
Gets whether changes to the document cannot be saved to the original document. |
| is |
Specifies whether Microsoft Word displays a message box whenever a user opens the document, suggesting that it be opened as read-only. |
| is |
Specifies whether AutoShapes or East Asian characters are automatically aligned with an invisible grid. |
| is |
Specifies whether AutoShapes or East Asian characters align with invisible gridlines through other shapes. |
| is |
Specifies whether spelling has been checked throughout the document. |
| is |
Specifies whether formatting restrictions are enforced in a protected document. |
| is |
Gets whether this document is a subdocument of a master document. |
| is |
Specifies whether users can change the document theme. |
| is |
Specifies whether the document was created or opened by the user. |
| is |
Gets whether the VBA project is digitally signed. |
| is |
Gets whether the document is protected with a write password. |
| justification |
Specifies the character spacing adjustment. |
| kind | Specifies the format type that Microsoft Word uses when automatically formatting the document. |
| language |
Specifies whether Microsoft Word has detected the language of the document text. |
| list |
Gets a |
| lists | Gets a |
| list |
Returns a |
| no |
Specifies the kinsoku characters after which Word will not break a line. |
| no |
Specifies the kinsoku characters before which Word will not break a line. |
| open |
Gets the encoding used to open the document. |
| original |
Gets the title of the original document after legal-blackline comparison. |
| page |
Returns a |
| paragraphs | Gets a |
| password | Sets a password that must be supplied to open the document. |
| password |
Gets the algorithm used for password encryption. |
| password |
Gets the key length used for password encryption. |
| password |
Gets the name of the password encryption provider. |
| path | Gets the disk or the web path to the document (excludes the document name). |
| print |
Specifies whether revision marks are printed with the document. |
| properties | Gets the properties of the document. |
| protection |
Gets the protection type for the document. |
| readability |
Gets a |
| reading |
Specifies the width of pages in reading layout view when frozen. |
| reading |
Specifies the height of pages in reading layout view when frozen. |
| reading |
Specifies whether pages in reading layout view are frozen for handwritten markup. |
| remove |
Specifies whether Word removes user information upon saving. |
| revised |
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 |
| save |
Specifies the encoding used when saving the document. |
| save |
Gets the file format of the document. |
| sections | Gets the collection of |
| selection | Returns a |
| sentences | Gets the |
| settings | Gets the add-in's settings in the document. |
| spelling |
Gets a |
| story |
Gets a |
| styles | Gets a |
| table |
Returns a |
| tables | Gets a |
| tables |
Returns a |
| tables |
Returns a |
| tables |
Returns a |
| text |
Specifies the encoding for saving as encoded text. |
| text |
Specifies how Word marks line and paragraph breaks in text files. |
| tracked |
Specifies whether to remove or store date and time metadata for tracked changes. |
| track |
Specifies whether to track formatting changes when change tracking is on. |
| track |
Specifies whether to mark moved text when Track Changes is on. |
| track |
Specifies whether changes are tracked in the document. |
| type | Gets the document type (template or document). |
| web |
Gets the |
| windows | Gets the collection of |
| words | Gets the |
| write |
Sets a password for saving changes to the document. |
| xml |
Specifies whether error messages are generated from built-in Word messages or MSXML (Microsoft XML). |
| xml |
Specifies whether to save a document through an Extensible Stylesheet Language Transformation (XSLT). |
| xml |
Specifies the path and file name for the XSLT to apply when saving a document. |
Methods
| accept |
Accepts all tracked changes in the document. |
| accept |
Accepts all revisions in the document that are displayed on the screen. |
| activate() | Activates the document so that it becomes the active document. |
| add |
Adds a style into the document by name and type. |
| add |
Adds a style into the document by name and type. |
| add |
Creates a shortcut to the document or hyperlink and adds it to the Favorites folder. |
| apply |
Applies the specified Quick Style set to the document. |
| apply |
Applies the specified Quick Style set to the document. |
| apply |
Applies the specified theme to this document. |
| auto |
Automatically formats the document. |
| can |
Returns |
| check |
Searches all text in a Japanese language document and displays instances where character usage is inconsistent for the same words. |
| check |
Begins a spelling and grammar check for the document. |
| check |
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. |
| check |
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. |
| check |
Begins a spelling check for the document. |
| close(close |
Closes the current document. Note: This API isn't supported in Word on the web. |
| close(close |
Closes the current document. Note: This API isn't supported in Word on the web. |
| close |
Switches the document from print preview to the previous view. |
| compare(file |
Displays revision marks that indicate where the specified document differs from another document. |
| compare |
Displays revision marks that indicate where the specified document differs from another document. |
| compute |
Returns a statistic based on the contents of the document. |
| compute |
Returns a statistic based on the contents of the document. |
| convert() | Converts the file to the newest format and enables all features. |
| convert |
Converts automatic hyphens to manual hyphens. |
| convert |
Changes the list numbers and LISTNUM fields in the document to text. |
| convert |
Changes the list numbers and LISTNUM fields in the document to text. |
| convert |
Reconverts a Vietnamese document to Unicode using a code page other than the default. |
| copy |
Copies styles from the specified template to the document. |
| count |
Returns the number of bulleted or numbered items and LISTNUM fields in the document. |
| delete |
Deletes all comments from the document. |
| delete |
Deletes all revisions in the document that are displayed on the screen. |
| delete |
Deletes all handwritten ink annotations in the document. |
| delete |
Deletes a bookmark, if it exists, from the document. |
| detect |
Analyzes the document text to determine the language. |
| end |
Terminates a review of the file that has been sent for review. |
| export |
Saves the document in PDF or XPS format. |
| export |
Saves the document in PDF or XPS format. |
| export |
Saves the document in PDF or XPS format. |
| export |
Saves the document in PDF or XPS format. |
| export |
Saves the document in PDF or XPS format with improved tagging. |
| export |
Saves the document in PDF or XPS format with improved tagging. |
| fit |
Decreases the font size of text just enough so that the document page count drops by one. |
| follow |
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. |
| freeze |
Fixes the layout of the document in Web view. |
| get |
Gets the annotation by ID. Throws an |
| get |
Gets a bookmark's range. Throws an |
| get |
Gets a bookmark's range. If the bookmark doesn't exist, then this method will return an object with its |
| get |
Gets the currently supported content controls in the document. |
| get |
Returns an array of items that can be cross-referenced based on the specified cross-reference type. |
| get |
Returns an array of items that can be cross-referenced based on the specified cross-reference type. |
| get |
Gets the document's endnotes in a single body. |
| get |
Gets the document's footnotes in a single body. |
| get |
Gets the paragraph by its unique local ID. Throws an |
| get |
Returns a |
| get |
Gets the current selection of the document. Multiple selections aren't supported. |
| get |
Gets a |
| go |
Returns a |
| import |
Import styles from a JSON-formatted string. |
| import |
Import styles from a JSON-formatted string. |
| insert |
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 |
| load(property |
Queues up a command to load the specified properties of the object. You must call |
| load(property |
Queues up a command to load the specified properties of the object. You must call |
| lock |
Locks the file on the server preventing anyone else from editing it. |
| make |
Sets the compatibility options. |
| manual |
Initiates manual hyphenation of a document, one line at a time. |
| merge(file |
Merges the changes marked with revision marks from one document to another. |
| post() | Posts the document to a public folder in Microsoft Exchange. |
| present |
Opens PowerPoint with the Word document loaded. |
| print |
Prints all or part of the document. |
| print |
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 |
| reject |
Rejects all tracked changes in the document. |
| reject |
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. |
| reload |
Reloads the document based on an HTML document, using the document encoding. |
| reload |
Reloads the document based on an HTML document, using the document encoding. |
| remove |
Removes sensitive information, properties, comments, and other metadata from the document. |
| remove |
Removes sensitive information, properties, comments, and other metadata from the document. |
| remove |
Purges the document of locked styles when formatting restrictions have been applied in the document. |
| remove |
Removes numbers or bullets from the document. |
| remove |
Removes numbers or bullets from the document. |
| remove |
Removes the active theme from the current document. |
| repaginate() | Repaginates the entire document. |
| reply |
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. |
| reset |
Clears all form fields in the document, preparing the form to be filled in again. |
| return |
Returns the document to the last saved reading position. |
| run |
Runs an auto macro that's stored in the document. If the specified auto macro doesn't exist, nothing happens. |
| run |
Runs an auto macro that's stored in the document. If the specified auto macro doesn't exist, nothing happens. |
| save(save |
Saves the document. |
| save(save |
Saves the document. |
| save |
Saves the group of quick styles currently in use. |
| search(search |
Performs a search with the specified search options on the scope of the whole document. The search results are a collection of |
| select() | Selects the contents of the document. |
| select |
Returns all content controls with the specified tag. |
| select |
Returns a |
| select |
Returns a |
| select |
Returns an |
| select |
Returns an |
| select |
Returns a |
| send |
Sends the document as a fax, without any user interaction. |
| send |
Sends the document to a fax service provider, who faxes the document to one or more specified recipients. |
| send |
Sends the document in an email message for review by the specified recipients. |
| send |
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. |
| set |
Specifies the table style to use for newly created tables in the document. |
| set |
Sets the options Microsoft Word uses for encrypting documents with passwords. |
| toggle |
Switches form design mode on or off. |
| toJSON() | Overrides the JavaScript |
| 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 |
| transform |
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. |
| undo |
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 |
| update |
Copies all styles from the attached template into the document, overwriting any existing styles in the document that have the same name. |
| view |
Displays the code window for the selected Microsoft ActiveX control in the document. |
| view |
Displays the property window for the selected Microsoft ActiveX control in the document. |
| web |
Displays a preview of the current document as it would look if saved as a webpage. |
Events
| on |
Occurs when the user clicks an annotation (or selects it using Alt+Down). |
| on |
Occurs when the user hovers the cursor over an annotation. |
| on |
Occurs when the user adds one or more annotations. |
| on |
Occurs when the user performs an action in an annotation pop-up menu. |
| on |
Occurs when the user deletes one or more annotations. |
| on |
Occurs when a content control is added. Run context.sync() in the handler to get the new content control's properties. |
| on |
Occurs when the user adds new paragraphs. |
| on |
Occurs when the user changes paragraphs. |
| on |
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
activeThemeDisplayName
Gets the display name of the active theme.
readonly activeThemeDisplayName: string;
Property Value
string
Remarks
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
areGrammaticalErrorsShown
Specifies whether grammatical errors are marked by a wavy green line in the document.
areGrammaticalErrorsShown: boolean;
Property Value
boolean
Remarks
areMathDefaultsUsed
Specifies whether to use the default math settings when creating new equations.
areMathDefaultsUsed: boolean;
Property Value
boolean
Remarks
areNewerFeaturesDisabled
Specifies whether to disable features introduced after a specified version.
areNewerFeaturesDisabled: boolean;
Property Value
boolean
Remarks
areSpellingErrorsShown
Specifies whether Microsoft Word underlines spelling errors in the document.
areSpellingErrorsShown: boolean;
Property Value
boolean
Remarks
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
areTrueTypeFontsEmbedded
Specifies whether Microsoft Word embeds TrueType fonts in the document when it's saved.
areTrueTypeFontsEmbedded: boolean;
Property Value
boolean
Remarks
attachedTemplate
Specifies a Template object that represents the template attached to the document.
attachedTemplate: Word.Template;
Property Value
Remarks
autoHyphenation
Specifies if automatic hyphenation is turned on for the document.
autoHyphenation: boolean;
Property Value
boolean
Remarks
autoSaveOn
Specifies if the edits in the document are automatically saved.
autoSaveOn: boolean;
Property Value
boolean
Remarks
background
Gets a Shape object that represents the background image for the document.
readonly background: Word.Shape;
Property Value
Remarks
bibliography
Returns a Bibliography object that represents the bibliography references contained within the document.
readonly bibliography: Word.Bibliography;
Property Value
Remarks
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
bookmarks
Returns a BookmarkCollection object that represents all the bookmarks in the document.
readonly bookmarks: Word.BookmarkCollection;
Property Value
Remarks
builtInDocumentProperties
Gets a DocumentProperties object that represents all the built-in document properties for the document.
readonly builtInDocumentProperties: Word.DocumentProperties;
Property Value
Remarks
changeTrackingMode
Specifies the ChangeTracking mode.
changeTrackingMode: Word.ChangeTrackingMode | "Off" | "TrackAll" | "TrackMineOnly";
Property Value
Word.ChangeTrackingMode | "Off" | "TrackAll" | "TrackMineOnly"
Remarks
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
coauthoring
Gets a Coauthoring object for managing coauthoring in the document.
readonly coauthoring: Word.Coauthoring;
Property Value
Remarks
codeName
Gets the code name for the document.
readonly codeName: string;
Property Value
string
Remarks
comments
Gets a CommentCollection object that represents all the comments in the document.
readonly comments: Word.CommentCollection;
Property Value
Remarks
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
consecutiveHyphensLimit
Specifies the maximum number of consecutive lines that can end with hyphens.
consecutiveHyphensLimit: number;
Property Value
number
Remarks
content
Gets a Range object that represents the main document story.
readonly content: Word.Range;
Property Value
Remarks
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
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
customDocumentProperties
Gets a DocumentProperties collection that represents all the custom document properties for the document.
readonly customDocumentProperties: Word.DocumentProperties;
Property Value
Remarks
customXmlParts
Gets the custom XML parts in the document.
readonly customXmlParts: Word.CustomXmlPartCollection;
Property Value
Remarks
defaultTabStop
Specifies the interval (in points) between the default tab stops in the document.
defaultTabStop: number;
Property Value
number
Remarks
defaultTargetFrame
Specifies the browser frame for displaying a webpage via hyperlink.
defaultTargetFrame: string;
Property Value
string
Remarks
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
doNotEmbedSystemFonts
Specifies whether Word should not embed common system fonts.
doNotEmbedSystemFonts: boolean;
Property Value
boolean
Remarks
encryptionProvider
Specifies the name of the algorithm encryption provider that Microsoft Word uses when encrypting documents.
encryptionProvider: string;
Property Value
string
Remarks
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
farEastLineBreakLevel
Specifies the line break control level.
farEastLineBreakLevel: Word.FarEastLineBreakLevel | "Normal" | "Strict" | "Custom";
Property Value
Word.FarEastLineBreakLevel | "Normal" | "Strict" | "Custom"
Remarks
fields
Gets a FieldCollection object that represents all the fields in the document.
readonly fields: Word.FieldCollection;
Property Value
Remarks
formattingIsNextLevelShown
Specifies whether Word shows the next heading level when the previous is used.
formattingIsNextLevelShown: boolean;
Property Value
boolean
Remarks
formattingIsUserStyleNameShown
Specifies whether to show user-defined styles.
formattingIsUserStyleNameShown: boolean;
Property Value
boolean
Remarks
frames
Returns a FrameCollection object that represents all the frames in the document.
readonly frames: Word.FrameCollection;
Property Value
Remarks
fullName
Gets the name of a document, including the path.
readonly fullName: string;
Property Value
string
Remarks
grammaticalErrors
Gets a RangeCollection object that represents the sentences that failed the grammar check in the document.
readonly grammaticalErrors: Word.RangeCollection;
Property Value
Remarks
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
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
gridIsOriginFromMargin
Specifies whether the character grid starts from the upper-left corner of the page.
gridIsOriginFromMargin: boolean;
Property Value
boolean
Remarks
gridOriginHorizontal
Specifies the horizontal origin point for the invisible grid.
gridOriginHorizontal: number;
Property Value
number
Remarks
gridOriginVertical
Specifies the vertical origin point for the invisible grid.
gridOriginVertical: number;
Property Value
number
Remarks
gridSpaceBetweenHorizontalLines
Specifies the interval for horizontal character gridlines in print layout view.
gridSpaceBetweenHorizontalLines: number;
Property Value
number
Remarks
gridSpaceBetweenVerticalLines
Specifies the interval for vertical character gridlines in print layout view.
gridSpaceBetweenVerticalLines: number;
Property Value
number
Remarks
hasPassword
Gets whether a password is required to open the document.
readonly hasPassword: boolean;
Property Value
boolean
Remarks
hasVbProject
Gets whether the document has an attached Microsoft Visual Basic for Applications project.
readonly hasVbProject: boolean;
Property Value
boolean
Remarks
hyperlinks
Returns a HyperlinkCollection object that represents all the hyperlinks in the document.
readonly hyperlinks: Word.HyperlinkCollection;
Property Value
Remarks
hyphenateCaps
Specifies whether words in all capital letters can be hyphenated.
hyphenateCaps: boolean;
Property Value
boolean
Remarks
hyphenationZone
Specifies the width of the hyphenation zone, in points.
hyphenationZone: number;
Property Value
number
Remarks
indexes
Returns an IndexCollection object that represents all the indexes in the document.
readonly indexes: Word.IndexCollection;
Property Value
Remarks
isAutoFormatOverrideOn
Specifies whether automatic formatting options override formatting restrictions.
isAutoFormatOverrideOn: boolean;
Property Value
boolean
Remarks
isChartDataPointTracked
Specifies whether charts in the active document use cell-reference data-point tracking.
isChartDataPointTracked: boolean;
Property Value
boolean
Remarks
isCompatible
Specifies whether the compatibility option specified by the type property is enabled.
isCompatible: boolean;
Property Value
boolean
Remarks
isFinal
Specifies whether the document is final.
isFinal: boolean;
Property Value
boolean
Remarks
isFontsSubsetSaved
Specifies whether Microsoft Word saves a subset of the embedded TrueType fonts with the document.
isFontsSubsetSaved: boolean;
Property Value
boolean
Remarks
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
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
isGrammarChecked
Specifies whether a grammar check has been run on the document.
isGrammarChecked: boolean;
Property Value
boolean
Remarks
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
isInFormsDesign
Gets whether the document is in form design mode.
readonly isInFormsDesign: boolean;
Property Value
boolean
Remarks
isKerningByAlgorithm
Specifies whether Word kerns half-width Latin characters and punctuation marks.
isKerningByAlgorithm: boolean;
Property Value
boolean
Remarks
isLinguisticDataEmbedded
Specifies whether to embed speech and handwriting data.
isLinguisticDataEmbedded: boolean;
Property Value
boolean
Remarks
isMasterDocument
Gets whether this document is a master document.
readonly isMasterDocument: boolean;
Property Value
boolean
Remarks
isOptimizedForWord97
Specifies whether Word optimizes the document for Word 97.
isOptimizedForWord97: boolean;
Property Value
boolean
Remarks
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
isQuickStyleSetLocked
Specifies whether users can change the Quick Style set.
isQuickStyleSetLocked: boolean;
Property Value
boolean
Remarks
isReadOnly
Gets whether changes to the document cannot be saved to the original document.
readonly isReadOnly: boolean;
Property Value
boolean
Remarks
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
isSnappedToGrid
Specifies whether AutoShapes or East Asian characters are automatically aligned with an invisible grid.
isSnappedToGrid: boolean;
Property Value
boolean
Remarks
isSnappedToShapes
Specifies whether AutoShapes or East Asian characters align with invisible gridlines through other shapes.
isSnappedToShapes: boolean;
Property Value
boolean
Remarks
isSpellingChecked
Specifies whether spelling has been checked throughout the document.
isSpellingChecked: boolean;
Property Value
boolean
Remarks
isStyleEnforced
Specifies whether formatting restrictions are enforced in a protected document.
isStyleEnforced: boolean;
Property Value
boolean
Remarks
isSubdocument
Gets whether this document is a subdocument of a master document.
readonly isSubdocument: boolean;
Property Value
boolean
Remarks
isThemeLocked
Specifies whether users can change the document theme.
isThemeLocked: boolean;
Property Value
boolean
Remarks
isUserControl
Specifies whether the document was created or opened by the user.
isUserControl: boolean;
Property Value
boolean
Remarks
isVbaSigned
Gets whether the VBA project is digitally signed.
readonly isVbaSigned: boolean;
Property Value
boolean
Remarks
isWriteReserved
Gets whether the document is protected with a write password.
readonly isWriteReserved: boolean;
Property Value
boolean
Remarks
justificationMode
Specifies the character spacing adjustment.
justificationMode: Word.JustificationMode | "Expand" | "Compress" | "CompressKana";
Property Value
Word.JustificationMode | "Expand" | "Compress" | "CompressKana"
Remarks
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
languageDetected
Specifies whether Microsoft Word has detected the language of the document text.
languageDetected: boolean;
Property Value
boolean
Remarks
listParagraphs
Gets a ParagraphCollection object that represents all the numbered paragraphs in the document.
readonly listParagraphs: Word.ParagraphCollection;
Property Value
Remarks
lists
Gets a ListCollection object that contains all the formatted lists in the document.
readonly lists: Word.ListCollection;
Property Value
Remarks
listTemplates
Returns a ListTemplateCollection object that represents all the list templates in the document.
readonly listTemplates: Word.ListTemplateCollection;
Property Value
Remarks
noLineBreakAfter
Specifies the kinsoku characters after which Word will not break a line.
noLineBreakAfter: string;
Property Value
string
Remarks
noLineBreakBefore
Specifies the kinsoku characters before which Word will not break a line.
noLineBreakBefore: string;
Property Value
string
Remarks
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
originalDocumentTitle
Gets the title of the original document after legal-blackline comparison.
readonly originalDocumentTitle: string;
Property Value
string
Remarks
pageSetup
Returns a PageSetup object that's associated with the document.
readonly pageSetup: Word.PageSetup;
Property Value
Remarks
paragraphs
Gets a ParagraphCollection object that represents all the paragraphs in the document.
readonly paragraphs: Word.ParagraphCollection;
Property Value
Remarks
password
Sets a password that must be supplied to open the document.
password: string;
Property Value
string
Remarks
passwordEncryptionAlgorithm
Gets the algorithm used for password encryption.
readonly passwordEncryptionAlgorithm: string;
Property Value
string
Remarks
passwordEncryptionKeyLength
Gets the key length used for password encryption.
readonly passwordEncryptionKeyLength: number;
Property Value
number
Remarks
passwordEncryptionProvider
Gets the name of the password encryption provider.
readonly passwordEncryptionProvider: string;
Property Value
string
Remarks
path
Gets the disk or the web path to the document (excludes the document name).
readonly path: string;
Property Value
string
Remarks
printRevisions
Specifies whether revision marks are printed with the document.
printRevisions: boolean;
Property Value
boolean
Remarks
properties
Gets the properties of the document.
readonly properties: Word.DocumentProperties;
Property Value
Remarks
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
readabilityStatistics
Gets a ReadabilityStatisticCollection object that represents the readability statistics for the document.
readonly readabilityStatistics: Word.ReadabilityStatisticCollection;
Property Value
Remarks
readingLayoutSizeX
Specifies the width of pages in reading layout view when frozen.
readingLayoutSizeX: number;
Property Value
number
Remarks
readingLayoutSizeY
Specifies the height of pages in reading layout view when frozen.
readingLayoutSizeY: number;
Property Value
number
Remarks
readingModeIsLayoutFrozen
Specifies whether pages in reading layout view are frozen for handwritten markup.
readingModeIsLayoutFrozen: boolean;
Property Value
boolean
Remarks
removePersonalInformationOnSave
Specifies whether Word removes user information upon saving.
removePersonalInformationOnSave: boolean;
Property Value
boolean
Remarks
revisedDocumentTitle
Gets the title of the revised document after legal-blackline comparison.
readonly revisedDocumentTitle: string;
Property Value
string
Remarks
revisions
Gets the collection of revisions that represents the tracked changes in the document.
readonly revisions: Word.RevisionCollection;
Property Value
Remarks
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
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
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
sections
Gets the collection of Section objects in the document.
readonly sections: Word.SectionCollection;
Property Value
Remarks
selection
Returns a Selection object that represents the current selection in the document.
readonly selection: Word.Selection;
Property Value
Remarks
sentences
Gets the RangeScopedCollection object that represents all the sentences in the document.
readonly sentences: Word.RangeScopedCollection;
Property Value
Remarks
settings
Gets the add-in's settings in the document.
readonly settings: Word.SettingCollection;
Property Value
Remarks
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
storyRanges
Gets a RangeCollection object that represents all the stories in the document.
readonly storyRanges: Word.RangeCollection;
Property Value
Remarks
styles
Gets a StyleCollection for the document.
readonly styles: Word.StyleCollection;
Property Value
Remarks
tableOfAuthoritiesCategories
Returns a TableOfAuthoritiesCategoryCollection object that represents the available table of authorities categories in the document.
readonly tableOfAuthoritiesCategories: Word.TableOfAuthoritiesCategoryCollection;
Property Value
Remarks
tables
Gets a TableCollection object that represents all the tables in the document.
readonly tables: Word.TableCollection;
Property Value
Remarks
tablesOfAuthorities
Returns a TableOfAuthoritiesCollection object that represents all the tables of authorities in the document.
readonly tablesOfAuthorities: Word.TableOfAuthoritiesCollection;
Property Value
Remarks
tablesOfContents
Returns a TableOfContentsCollection object that represents all the tables of contents in the document.
readonly tablesOfContents: Word.TableOfContentsCollection;
Property Value
Remarks
tablesOfFigures
Returns a TableOfFiguresCollection object that represents all the tables of figures in the document.
readonly tablesOfFigures: Word.TableOfFiguresCollection;
Property Value
Remarks
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
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
trackedChangesAreDateAndTimeRemoved
Specifies whether to remove or store date and time metadata for tracked changes.
trackedChangesAreDateAndTimeRemoved: boolean;
Property Value
boolean
Remarks
trackFormatting
Specifies whether to track formatting changes when change tracking is on.
trackFormatting: boolean;
Property Value
boolean
Remarks
trackMoves
Specifies whether to mark moved text when Track Changes is on.
trackMoves: boolean;
Property Value
boolean
Remarks
trackRevisions
Specifies whether changes are tracked in the document.
trackRevisions: boolean;
Property Value
boolean
Remarks
type
Gets the document type (template or document).
readonly type: Word.DocumentType | "Document" | "Template" | "Frameset";
Property Value
Word.DocumentType | "Document" | "Template" | "Frameset"
Remarks
webSettings
Gets the WebSettings object for webpage-related attributes.
readonly webSettings: Word.WebSettings;
Property Value
Remarks
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
writePassword
Sets a password for saving changes to the document.
writePassword: string;
Property Value
string
Remarks
xmlAreAdvancedErrorsShown
Specifies whether error messages are generated from built-in Word messages or MSXML (Microsoft XML).
xmlAreAdvancedErrorsShown: boolean;
Property Value
boolean
Remarks
xmlIsXsltUsedWhenSaving
Specifies whether to save a document through an Extensible Stylesheet Language Transformation (XSLT).
xmlIsXsltUsedWhenSaving: boolean;
Property Value
boolean
Remarks
xmlSaveThroughXslt
Specifies the path and file name for the XSLT to apply when saving a document.
xmlSaveThroughXslt: string;
Property Value
string
Remarks
Method Details
acceptAllRevisions()
Accepts all tracked changes in the document.
acceptAllRevisions(): void;
Returns
void
Remarks
acceptAllRevisionsShown()
Accepts all revisions in the document that are displayed on the screen.
acceptAllRevisionsShown(): void;
Returns
void
Remarks
activate()
Activates the document so that it becomes the active document.
activate(): void;
Returns
void
Remarks
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
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
addToFavorites()
Creates a shortcut to the document or hyperlink and adds it to the Favorites folder.
addToFavorites(): void;
Returns
void
Remarks
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
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
applyTheme(name)
Applies the specified theme to this document.
applyTheme(name: string): void;
Parameters
- name
-
string
The name of the theme.
Returns
void
Remarks
autoFormat()
Automatically formats the document.
autoFormat(): void;
Returns
void
Remarks
canCheckin()
Returns true if Microsoft Word can check in the document to a server.
canCheckin(): OfficeExtension.ClientResult<boolean>;
Returns
OfficeExtension.ClientResult<boolean>
true if the document can be checked in; otherwise, false.
Remarks
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
checkGrammar()
Begins a spelling and grammar check for the document.
checkGrammar(): void;
Returns
void
Remarks
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
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
Optional. Configuration options for checking in the document with version control.
Returns
void
Remarks
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
Optional. Configuration options for the spell checking operation.
Returns
void
Remarks
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
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
closePrintPreview()
Switches the document from print preview to the previous view.
closePrintPreview(): void;
Returns
void
Remarks
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
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
OfficeExtension.ClientResult<number>
Remarks
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
OfficeExtension.ClientResult<number>
Remarks
convert()
Converts the file to the newest format and enables all features.
convert(): void;
Returns
void
Remarks
convertAutoHyphens()
Converts automatic hyphens to manual hyphens.
convertAutoHyphens(): void;
Returns
void
Remarks
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
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
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
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
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
Optional. Configuration options for counting numbered items.
Returns
OfficeExtension.ClientResult<number>
The count of numbered items.
Remarks
deleteAllComments()
Deletes all comments from the document.
deleteAllComments(): void;
Returns
void
Remarks
deleteAllCommentsShown()
Deletes all revisions in the document that are displayed on the screen.
deleteAllCommentsShown(): void;
Returns
void
Remarks
deleteAllInkAnnotations()
Deletes all handwritten ink annotations in the document.
deleteAllInkAnnotations(): void;
Returns
void
Remarks
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
detectLanguage()
Analyzes the document text to determine the language.
detectLanguage(): void;
Returns
void
Remarks
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
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.
Optional. Configuration options for the export operation.
Returns
void
Remarks
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.
Optional. Configuration options for the export operation.
Returns
void
Remarks
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).
Optional. Configuration options for the export operation.
Returns
void
Remarks
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).
Optional. Configuration options for the export operation.
Returns
void
Remarks
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).
Optional. Configuration options for the export operation.
Returns
void
Remarks
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).
Optional. Configuration options for the export operation.
Returns
void
Remarks
fitToPages()
Decreases the font size of text just enough so that the document page count drops by one.
fitToPages(): void;
Returns
void
Remarks
followHyperlink(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.
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
Optional. Configuration options for following the hyperlink.
Returns
void
Remarks
freezeLayout()
Fixes the layout of the document in Web view.
freezeLayout(): void;
Returns
void
Remarks
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
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
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
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
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
OfficeExtension.ClientResult<string[]>
Remarks
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
OfficeExtension.ClientResult<string[]>
Remarks
getEndnoteBody()
Gets the document's endnotes in a single body.
getEndnoteBody(): Word.Body;
Returns
Remarks
getFootnoteBody()
Gets the document's footnotes in a single body.
getFootnoteBody(): Word.Body;
Returns
Remarks
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
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
getSelection()
Gets the current selection of the document. Multiple selections aren't supported.
getSelection(): Word.Range;
Returns
Remarks
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
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
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
OfficeExtension.ClientResult<string[]>
Remarks
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
OfficeExtension.ClientResult<string[]>
Remarks
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.
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
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
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
makeCompatibilityDefault()
Sets the compatibility options.
makeCompatibilityDefault(): void;
Returns
void
Remarks
manualHyphenation()
Initiates manual hyphenation of a document, one line at a time.
manualHyphenation(): void;
Returns
void
Remarks
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
post()
Posts the document to a public folder in Microsoft Exchange.
post(): void;
Returns
void
Remarks
presentIt()
Opens PowerPoint with the Word document loaded.
presentIt(): void;
Returns
void
Remarks
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
printPreview()
Switches the view to print preview.
printPreview(): void;
Returns
void
Remarks
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
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
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
OfficeExtension.ClientResult<boolean>
true if the actions were redone successfully; otherwise, false.
Remarks
rejectAllRevisions()
Rejects all tracked changes in the document.
rejectAllRevisions(): void;
Returns
void
Remarks
rejectAllRevisionsShown()
Rejects all revisions in the document that are displayed on the screen.
rejectAllRevisionsShown(): void;
Returns
void
Remarks
reload()
Reloads a cached document by resolving the hyperlink to the document and downloading it.
reload(): void;
Returns
void
Remarks
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
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
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
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
removeLockedStyles()
Purges the document of locked styles when formatting restrictions have been applied in the document.
removeLockedStyles(): void;
Returns
void
Remarks
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
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
removeTheme()
Removes the active theme from the current document.
removeTheme(): void;
Returns
void
Remarks
repaginate()
Repaginates the entire document.
repaginate(): void;
Returns
void
Remarks
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
Optional. Configuration options for replying with changes.
Returns
void
Remarks
resetFormFields()
Clears all form fields in the document, preparing the form to be filled in again.
resetFormFields(): void;
Returns
void
Remarks
returnToLastReadPosition()
Returns the document to the last saved reading position.
returnToLastReadPosition(): OfficeExtension.ClientResult<number>;
Returns
OfficeExtension.ClientResult<number>
Remarks
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
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
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
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
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
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
select()
Selects the contents of the document.
select(): void;
Returns
void
Remarks
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
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
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
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
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
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
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
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
Optional. Configuration options for sending the fax over the internet.
Returns
void
Remarks
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
Optional. Configuration options for sending the document for review.
Returns
void
Remarks
sendMail()
Opens a message window for sending the document through Microsoft Exchange.
sendMail(): void;
Returns
void
Remarks
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
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
toggleFormsDesign()
Switches form design mode on or off.
toggleFormsDesign(): void;
Returns
void
Remarks
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
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
OfficeExtension.ClientResult<boolean>
true if the actions were undone successfully; otherwise, false.
Remarks
undoClear()
Clears the list of actions that can be undone in the document.
undoClear(): void;
Returns
void
Remarks
unprotect(password)
Removes protection from the document.
unprotect(password?: string): void;
Parameters
- password
-
string
Optional. The password to unprotect the document.
Returns
void
Remarks
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
viewCode()
Displays the code window for the selected Microsoft ActiveX control in the document.
viewCode(): void;
Returns
void
Remarks
viewPropertyBrowser()
Displays the property window for the selected Microsoft ActiveX control in the document.
viewPropertyBrowser(): void;
Returns
void
Remarks
webPagePreview()
Displays a preview of the current document as it would look if saved as a webpage.
webPagePreview(): void;
Returns
void
Remarks
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
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
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
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
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
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
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
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
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
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);
});
}