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