Word.Body class

Represents the body of a document or a section.

[ API set: WordApi 1.1 ]

Extends
OfficeExtension.ClientObject

Properties

contentControls

Gets the collection of rich text content control objects in the body. Read-only.

[ API set: WordApi 1.1 ]

context

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

font

Gets the text format of the body. Use this to get and set font name, size, color and other properties. Read-only.

[ API set: WordApi 1.1 ]

inlinePictures

Gets the collection of InlinePicture objects in the body. The collection does not include floating images. Read-only.

[ API set: WordApi 1.1 ]

lists

Gets the collection of list objects in the body. Read-only.

[ API set: WordApi 1.3 ]

paragraphs

Gets the collection of paragraph objects in the body. Read-only.

[ API set: WordApi 1.1 ]

parentBody

Gets the parent body of the body. For example, a table cell body's parent body could be a header. Throws an error if there isn't a parent body. Read-only.

[ API set: WordApi 1.3 ]

parentBodyOrNullObject

Gets the parent body of the body. For example, a table cell body's parent body could be a header. Returns a null object if there isn't a parent body. Read-only.

[ API set: WordApi 1.3 ]

parentContentControl

Gets the content control that contains the body. Throws an error if there isn't a parent content control. Read-only.

[ API set: WordApi 1.1 ]

parentContentControlOrNullObject

Gets the content control that contains the body. Returns a null object if there isn't a parent content control. Read-only.

[ API set: WordApi 1.3 ]

parentSection

Gets the parent section of the body. Throws an error if there isn't a parent section. Read-only.

[ API set: WordApi 1.3 ]

parentSectionOrNullObject

Gets the parent section of the body. Returns a null object if there isn't a parent section. Read-only.

[ API set: WordApi 1.3 ]

style

Gets or sets the style name for the body. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property.

[ API set: WordApi 1.1 ]

styleBuiltIn

Gets or sets the built-in style name for the body. Use this property for built-in styles that are portable between locales. To use custom styles or localized style names, see the "style" property.

[ API set: WordApi 1.3 ]

tables

Gets the collection of table objects in the body. Read-only.

[ API set: WordApi 1.3 ]

text

Gets the text of the body. Use the insertText method to insert text. Read-only.

[ API set: WordApi 1.1 ]

type

Gets the type of the body. The type can be 'MainDoc', 'Section', 'Header', 'Footer', or 'TableCell'. Read-only.

[ API set: WordApi 1.3 ]

Methods

clear()

Clears the contents of the body object. The user can perform the undo operation on the cleared content.

[ API set: WordApi 1.1 ]

getHtml()

Gets an HTML representation of the body object. When rendered in a web page or HTML viewer, the formatting will be a close, but not exact, match for of the formatting of the document. This method does not return the exact same HTML for the same document on different platforms (Windows, Mac, Word for the web, etc.). If you need exact fidelity, or consistency across platforms, use Body.getOoxml() and convert the returned XML to HTML.

[ API set: WordApi 1.1 ]

getOoxml()

Gets the OOXML (Office Open XML) representation of the body object.

[ API set: WordApi 1.1 ]

getRange(rangeLocation)

Gets the whole body, or the starting or ending point of the body, as a range.

[ API set: WordApi 1.3 ]

getRange(rangeLocationString)

Gets the whole body, or the starting or ending point of the body, as a range.

[ API set: WordApi 1.3 ]

insertBreak(breakType, insertLocation)

Inserts a break at the specified location in the main document.

[ API set: WordApi 1.1 ]

insertBreak(breakTypeString, insertLocation)

Inserts a break at the specified location in the main document.

[ API set: WordApi 1.1 ]

insertContentControl()

Wraps the body object with a Rich Text content control.

[ API set: WordApi 1.1 ]

insertFileFromBase64(base64File, insertLocation)

Inserts a document into the body at the specified location.

[ API set: WordApi 1.1 ]

insertFileFromBase64(base64File, insertLocationString)

Inserts a document into the body at the specified location.

[ API set: WordApi 1.1 ]

insertHtml(html, insertLocation)

Inserts HTML at the specified location.

[ API set: WordApi 1.1 ]

insertHtml(html, insertLocationString)

Inserts HTML at the specified location.

[ API set: WordApi 1.1 ]

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Inserts a picture into the body at the specified location.

[ API set: WordApi 1.2 ]

insertInlinePictureFromBase64(base64EncodedImage, insertLocationString)

Inserts a picture into the body at the specified location.

[ API set: WordApi 1.2 ]

insertOoxml(ooxml, insertLocation)

Inserts OOXML at the specified location.

[ API set: WordApi 1.1 ]

insertOoxml(ooxml, insertLocationString)

Inserts OOXML at the specified location.

[ API set: WordApi 1.1 ]

insertParagraph(paragraphText, insertLocation)

Inserts a paragraph at the specified location.

[ API set: WordApi 1.1 ]

insertParagraph(paragraphText, insertLocationString)

Inserts a paragraph at the specified location.

[ API set: WordApi 1.1 ]

insertTable(rowCount, columnCount, insertLocation, values)

Inserts a table with the specified number of rows and columns.

[ API set: WordApi 1.3 ]

insertTable(rowCount, columnCount, insertLocationString, values)

Inserts a table with the specified number of rows and columns.

[ API set: WordApi 1.3 ]

insertText(text, insertLocation)

Inserts text into the body at the specified location.

[ API set: WordApi 1.1 ]

insertText(text, insertLocationString)

Inserts text into the body at the specified location.

[ API set: WordApi 1.1 ]

load(option)

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

load(propertyNames)

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

load(propertyNamesAndPaths)

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

search(searchText, searchOptions)

Performs a search with the specified SearchOptions on the scope of the body object. The search results are a collection of range objects.

[ API set: WordApi 1.1 ]

select(selectionMode)

Selects the body and navigates the Word UI to it.

[ API set: WordApi 1.1 ]

select(selectionModeString)

Selects the body and navigates the Word UI to it.

[ API set: WordApi 1.1 ]

set(properties, options)

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

set(properties)

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

toJSON()

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

track()

Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are 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 needed to have added the object to the tracked object collection when the object was first created.

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 will need to call "context.sync()" before the memory release takes effect.

Property Details

contentControls

Gets the collection of rich text content control objects in the body. Read-only.

[ API set: WordApi 1.1 ]

readonly contentControls: Word.ContentControlCollection;

Property Value

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

font

Gets the text format of the body. Use this to get and set font name, size, color and other properties. Read-only.

[ API set: WordApi 1.1 ]

readonly font: Word.Font;

Property Value

Examples

// Get the style and the font size, font name, and font color properties on the body object.
// Run a batch operation against the Word object model.
Word.run(function (context) {

    // Create a proxy object for the document body.
    var body = context.document.body;

    // Queue a command to load font and style information for the document body.
    context.load(body, 'font/size, font/name, font/color, style');

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    return context.sync().then(function () {
        // Show the results of the load method. Here we show the
        // property values on the body object.
        var results = 'Font size: ' + body.font.size +
                      '; Font name: ' + body.font.name +
                      '; Font color: ' + body.font.color +
                      '; Body style: ' + body.style;

        console.log(results);
    });
})
.catch(function (error) {
    console.log('Error: ' + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
        console.log('Debug info: ' + JSON.stringify(error.debugInfo));
    }
});

inlinePictures

Gets the collection of InlinePicture objects in the body. The collection does not include floating images. Read-only.

[ API set: WordApi 1.1 ]

readonly inlinePictures: Word.InlinePictureCollection;

Property Value

lists

Gets the collection of list objects in the body. Read-only.

[ API set: WordApi 1.3 ]

readonly lists: Word.ListCollection;

Property Value

paragraphs

Gets the collection of paragraph objects in the body. Read-only.

[ API set: WordApi 1.1 ]

readonly paragraphs: Word.ParagraphCollection;

Property Value

Examples

await Word.run(async (context) => {
  let paragraphs = context.document.body.paragraphs;
  paragraphs.load("text");
  await context.sync();

  let text = [];
  paragraphs.items.forEach((item) => {
    let paragraph = item.text.trim();
    if (paragraph) {
      paragraph.split(" ").forEach((term) => {
        let currentTerm = term.trim();
        if (currentTerm) {
          text.push(currentTerm);
        }
      });
    }
  });

  let makeTextDistinct = new Set(text);
  let distinctText = Array.from(makeTextDistinct);
  let allSearchResults = [];

  for (let i = 0; i < distinctText.length; i++) {
    let results = context.document.body.search(distinctText[i], { matchCase: true, matchWholeWord: true });
    results.load("text");

    // Map search term with its results.
    let correlatedResults = {
      searchTerm: distinctText[i],
      hits: results
    };

    allSearchResults.push(correlatedResults);
  }

  await context.sync();

  // Display counts.
  allSearchResults.forEach((result) => {
    let length = result.hits.items.length;

    console.log("Search term: " + result.searchTerm + " => Count: " + length);
  });
});

parentBody

Gets the parent body of the body. For example, a table cell body's parent body could be a header. Throws an error if there isn't a parent body. Read-only.

[ API set: WordApi 1.3 ]

readonly parentBody: Word.Body;

Property Value

parentBodyOrNullObject

Gets the parent body of the body. For example, a table cell body's parent body could be a header. Returns a null object if there isn't a parent body. Read-only.

[ API set: WordApi 1.3 ]

readonly parentBodyOrNullObject: Word.Body;

Property Value

parentContentControl

Gets the content control that contains the body. Throws an error if there isn't a parent content control. Read-only.

[ API set: WordApi 1.1 ]

readonly parentContentControl: Word.ContentControl;

Property Value

parentContentControlOrNullObject

Gets the content control that contains the body. Returns a null object if there isn't a parent content control. Read-only.

[ API set: WordApi 1.3 ]

readonly parentContentControlOrNullObject: Word.ContentControl;

Property Value

parentSection

Gets the parent section of the body. Throws an error if there isn't a parent section. Read-only.

[ API set: WordApi 1.3 ]

readonly parentSection: Word.Section;

Property Value

parentSectionOrNullObject

Gets the parent section of the body. Returns a null object if there isn't a parent section. Read-only.

[ API set: WordApi 1.3 ]

readonly parentSectionOrNullObject: Word.Section;

Property Value

style

Gets or sets the style name for the body. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property.

[ API set: WordApi 1.1 ]

style: string;

Property Value

string

styleBuiltIn

Gets or sets the built-in style name for the body. Use this property for built-in styles that are portable between locales. To use custom styles or localized style names, see the "style" property.

[ API set: WordApi 1.3 ]

styleBuiltIn: Word.Style | "Other" | "Normal" | "Heading1" | "Heading2" | "Heading3" | "Heading4" | "Heading5" | "Heading6" | "Heading7" | "Heading8" | "Heading9" | "Toc1" | "Toc2" | "Toc3" | "Toc4" | "Toc5" | "Toc6" | "Toc7" | "Toc8" | "Toc9" | "FootnoteText" | "Header" | "Footer" | "Caption" | "FootnoteReference" | "EndnoteReference" | "EndnoteText" | "Title" | "Subtitle" | "Hyperlink" | "Strong" | "Emphasis" | "NoSpacing" | "ListParagraph" | "Quote" | "IntenseQuote" | "SubtleEmphasis" | "IntenseEmphasis" | "SubtleReference" | "IntenseReference" | "BookTitle" | "Bibliography" | "TocHeading" | "TableGrid" | "PlainTable1" | "PlainTable2" | "PlainTable3" | "PlainTable4" | "PlainTable5" | "TableGridLight" | "GridTable1Light" | "GridTable1Light_Accent1" | "GridTable1Light_Accent2" | "GridTable1Light_Accent3" | "GridTable1Light_Accent4" | "GridTable1Light_Accent5" | "GridTable1Light_Accent6" | "GridTable2" | "GridTable2_Accent1" | "GridTable2_Accent2" | "GridTable2_Accent3" | "GridTable2_Accent4" | "GridTable2_Accent5" | "GridTable2_Accent6" | "GridTable3" | "GridTable3_Accent1" | "GridTable3_Accent2" | "GridTable3_Accent3" | "GridTable3_Accent4" | "GridTable3_Accent5" | "GridTable3_Accent6" | "GridTable4" | "GridTable4_Accent1" | "GridTable4_Accent2" | "GridTable4_Accent3" | "GridTable4_Accent4" | "GridTable4_Accent5" | "GridTable4_Accent6" | "GridTable5Dark" | "GridTable5Dark_Accent1" | "GridTable5Dark_Accent2" | "GridTable5Dark_Accent3" | "GridTable5Dark_Accent4" | "GridTable5Dark_Accent5" | "GridTable5Dark_Accent6" | "GridTable6Colorful" | "GridTable6Colorful_Accent1" | "GridTable6Colorful_Accent2" | "GridTable6Colorful_Accent3" | "GridTable6Colorful_Accent4" | "GridTable6Colorful_Accent5" | "GridTable6Colorful_Accent6" | "GridTable7Colorful" | "GridTable7Colorful_Accent1" | "GridTable7Colorful_Accent2" | "GridTable7Colorful_Accent3" | "GridTable7Colorful_Accent4" | "GridTable7Colorful_Accent5" | "GridTable7Colorful_Accent6" | "ListTable1Light" | "ListTable1Light_Accent1" | "ListTable1Light_Accent2" | "ListTable1Light_Accent3" | "ListTable1Light_Accent4" | "ListTable1Light_Accent5" | "ListTable1Light_Accent6" | "ListTable2" | "ListTable2_Accent1" | "ListTable2_Accent2" | "ListTable2_Accent3" | "ListTable2_Accent4" | "ListTable2_Accent5" | "ListTable2_Accent6" | "ListTable3" | "ListTable3_Accent1" | "ListTable3_Accent2" | "ListTable3_Accent3" | "ListTable3_Accent4" | "ListTable3_Accent5" | "ListTable3_Accent6" | "ListTable4" | "ListTable4_Accent1" | "ListTable4_Accent2" | "ListTable4_Accent3" | "ListTable4_Accent4" | "ListTable4_Accent5" | "ListTable4_Accent6" | "ListTable5Dark" | "ListTable5Dark_Accent1" | "ListTable5Dark_Accent2" | "ListTable5Dark_Accent3" | "ListTable5Dark_Accent4" | "ListTable5Dark_Accent5" | "ListTable5Dark_Accent6" | "ListTable6Colorful" | "ListTable6Colorful_Accent1" | "ListTable6Colorful_Accent2" | "ListTable6Colorful_Accent3" | "ListTable6Colorful_Accent4" | "ListTable6Colorful_Accent5" | "ListTable6Colorful_Accent6" | "ListTable7Colorful" | "ListTable7Colorful_Accent1" | "ListTable7Colorful_Accent2" | "ListTable7Colorful_Accent3" | "ListTable7Colorful_Accent4" | "ListTable7Colorful_Accent5" | "ListTable7Colorful_Accent6";

Property Value

Word.Style | "Other" | "Normal" | "Heading1" | "Heading2" | "Heading3" | "Heading4" | "Heading5" | "Heading6" | "Heading7" | "Heading8" | "Heading9" | "Toc1" | "Toc2" | "Toc3" | "Toc4" | "Toc5" | "Toc6" | "Toc7" | "Toc8" | "Toc9" | "FootnoteText" | "Header" | "Footer" | "Caption" | "FootnoteReference" | "EndnoteReference" | "EndnoteText" | "Title" | "Subtitle" | "Hyperlink" | "Strong" | "Emphasis" | "NoSpacing" | "ListParagraph" | "Quote" | "IntenseQuote" | "SubtleEmphasis" | "IntenseEmphasis" | "SubtleReference" | "IntenseReference" | "BookTitle" | "Bibliography" | "TocHeading" | "TableGrid" | "PlainTable1" | "PlainTable2" | "PlainTable3" | "PlainTable4" | "PlainTable5" | "TableGridLight" | "GridTable1Light" | "GridTable1Light_Accent1" | "GridTable1Light_Accent2" | "GridTable1Light_Accent3" | "GridTable1Light_Accent4" | "GridTable1Light_Accent5" | "GridTable1Light_Accent6" | "GridTable2" | "GridTable2_Accent1" | "GridTable2_Accent2" | "GridTable2_Accent3" | "GridTable2_Accent4" | "GridTable2_Accent5" | "GridTable2_Accent6" | "GridTable3" | "GridTable3_Accent1" | "GridTable3_Accent2" | "GridTable3_Accent3" | "GridTable3_Accent4" | "GridTable3_Accent5" | "GridTable3_Accent6" | "GridTable4" | "GridTable4_Accent1" | "GridTable4_Accent2" | "GridTable4_Accent3" | "GridTable4_Accent4" | "GridTable4_Accent5" | "GridTable4_Accent6" | "GridTable5Dark" | "GridTable5Dark_Accent1" | "GridTable5Dark_Accent2" | "GridTable5Dark_Accent3" | "GridTable5Dark_Accent4" | "GridTable5Dark_Accent5" | "GridTable5Dark_Accent6" | "GridTable6Colorful" | "GridTable6Colorful_Accent1" | "GridTable6Colorful_Accent2" | "GridTable6Colorful_Accent3" | "GridTable6Colorful_Accent4" | "GridTable6Colorful_Accent5" | "GridTable6Colorful_Accent6" | "GridTable7Colorful" | "GridTable7Colorful_Accent1" | "GridTable7Colorful_Accent2" | "GridTable7Colorful_Accent3" | "GridTable7Colorful_Accent4" | "GridTable7Colorful_Accent5" | "GridTable7Colorful_Accent6" | "ListTable1Light" | "ListTable1Light_Accent1" | "ListTable1Light_Accent2" | "ListTable1Light_Accent3" | "ListTable1Light_Accent4" | "ListTable1Light_Accent5" | "ListTable1Light_Accent6" | "ListTable2" | "ListTable2_Accent1" | "ListTable2_Accent2" | "ListTable2_Accent3" | "ListTable2_Accent4" | "ListTable2_Accent5" | "ListTable2_Accent6" | "ListTable3" | "ListTable3_Accent1" | "ListTable3_Accent2" | "ListTable3_Accent3" | "ListTable3_Accent4" | "ListTable3_Accent5" | "ListTable3_Accent6" | "ListTable4" | "ListTable4_Accent1" | "ListTable4_Accent2" | "ListTable4_Accent3" | "ListTable4_Accent4" | "ListTable4_Accent5" | "ListTable4_Accent6" | "ListTable5Dark" | "ListTable5Dark_Accent1" | "ListTable5Dark_Accent2" | "ListTable5Dark_Accent3" | "ListTable5Dark_Accent4" | "ListTable5Dark_Accent5" | "ListTable5Dark_Accent6" | "ListTable6Colorful" | "ListTable6Colorful_Accent1" | "ListTable6Colorful_Accent2" | "ListTable6Colorful_Accent3" | "ListTable6Colorful_Accent4" | "ListTable6Colorful_Accent5" | "ListTable6Colorful_Accent6" | "ListTable7Colorful" | "ListTable7Colorful_Accent1" | "ListTable7Colorful_Accent2" | "ListTable7Colorful_Accent3" | "ListTable7Colorful_Accent4" | "ListTable7Colorful_Accent5" | "ListTable7Colorful_Accent6"

tables

Gets the collection of table objects in the body. Read-only.

[ API set: WordApi 1.3 ]

readonly tables: Word.TableCollection;

Property Value

text

Gets the text of the body. Use the insertText method to insert text. Read-only.

[ API set: WordApi 1.1 ]

readonly text: string;

Property Value

string

Examples

// Get the text property on the body object
// Run a batch operation against the Word object model.
Word.run(function (context) {

    // Create a proxy object for the document body.
    var body = context.document.body;

    // Queue a command to load the text in document body.
    context.load(body, 'text');

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    return context.sync().then(function () {
        console.log("Body contents: " + body.text);
    });
})
.catch(function (error) {
    console.log("Error: " + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
        console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
});

type

Gets the type of the body. The type can be 'MainDoc', 'Section', 'Header', 'Footer', or 'TableCell'. Read-only.

[ API set: WordApi 1.3 ]

readonly type: Word.BodyType | "Unknown" | "MainDoc" | "Section" | "Header" | "Footer" | "TableCell";

Property Value

Word.BodyType | "Unknown" | "MainDoc" | "Section" | "Header" | "Footer" | "TableCell"

Method Details

clear()

Clears the contents of the body object. The user can perform the undo operation on the cleared content.

[ API set: WordApi 1.1 ]

clear(): void;

Returns

void

Examples

// Run a batch operation against the Word object model.
Word.run(function (context) {

    // Create a proxy object for the document body.
    var body = context.document.body;

    // Queue a command to clear the contents of the body.
    body.clear();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    return context.sync().then(function () {
        console.log('Cleared the body contents.');
    });
})
.catch(function (error) {
    console.log("Error: " + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
        console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
});

// The Silly stories add-in sample shows how the 
// clear method can be used to clear the contents of a document.
// https://aka.ms/sillystorywordaddin

getHtml()

Gets an HTML representation of the body object. When rendered in a web page or HTML viewer, the formatting will be a close, but not exact, match for of the formatting of the document. This method does not return the exact same HTML for the same document on different platforms (Windows, Mac, Word for the web, etc.). If you need exact fidelity, or consistency across platforms, use Body.getOoxml() and convert the returned XML to HTML.

[ API set: WordApi 1.1 ]

getHtml(): OfficeExtension.ClientResult<string>;

Returns

OfficeExtension.ClientResult<string>

Examples

// Run a batch operation against the Word object model.
Word.run(function (context) {

    // Create a proxy object for the document body.
    var body = context.document.body;

    // Queue a command to get the HTML contents of the body.
    var bodyHTML = body.getHtml();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    return context.sync().then(function () {
        console.log("Body HTML contents: " + bodyHTML.value);
    });
})
.catch(function (error) {
    console.log("Error: " + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
        console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
});

getOoxml()

Gets the OOXML (Office Open XML) representation of the body object.

[ API set: WordApi 1.1 ]

getOoxml(): OfficeExtension.ClientResult<string>;

Returns

OfficeExtension.ClientResult<string>

Examples

// Run a batch operation against the Word object model.
Word.run(function (context) {

    // Create a proxy object for the document body.
    var body = context.document.body;

    // Queue a command to get the OOXML contents of the body.
    var bodyOOXML = body.getOoxml();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    return context.sync().then(function () {
        console.log("Body OOXML contents: " + bodyOOXML.value);
    });
})
.catch(function (error) {
    console.log("Error: " + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
        console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
});

getRange(rangeLocation)

Gets the whole body, or the starting or ending point of the body, as a range.

[ API set: WordApi 1.3 ]

getRange(rangeLocation?: Word.RangeLocation): Word.Range;

Parameters

rangeLocation
Word.RangeLocation

Optional. The range location can be 'Whole', 'Start', 'End', 'After', or 'Content'.

Returns

getRange(rangeLocationString)

Gets the whole body, or the starting or ending point of the body, as a range.

[ API set: WordApi 1.3 ]

getRange(rangeLocationString?: "Whole" | "Start" | "End" | "Before" | "After" | "Content"): Word.Range;

Parameters

rangeLocationString
"Whole" | "Start" | "End" | "Before" | "After" | "Content"

Optional. The range location can be 'Whole', 'Start', 'End', 'After', or 'Content'.

Returns

insertBreak(breakType, insertLocation)

Inserts a break at the specified location in the main document.

[ API set: WordApi 1.1 ]

insertBreak(breakType: Word.BreakType, insertLocation: Word.InsertLocation): void;

Parameters

breakType
Word.BreakType

Required. The break type to add to the body.

insertLocation
Word.InsertLocation

Required. The value can be 'Start' or 'End'.

Returns

void

Examples

// Run a batch operation against the Word object model.
Word.run(function (ctx) {

    // Create a proxy object for the document body.
    var body = ctx.document.body;

    // Queue a command to insert a page break at the start of the document body.
    body.insertBreak(Word.BreakType.page, Word.InsertLocation.start);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    return ctx.sync().then(function () {
        console.log('Added a page break at the start of the document body.');
    });
})
.catch(function (error) {
    console.log("Error: " + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
        console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
});

insertBreak(breakTypeString, insertLocation)

Inserts a break at the specified location in the main document.

[ API set: WordApi 1.1 ]

insertBreak(breakTypeString: "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line", insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): void;

Parameters

breakTypeString
"Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line"

Required. The break type to add to the body.

insertLocation
"Before" | "After" | "Start" | "End" | "Replace"

Required. The value can be 'Start' or 'End'.

Returns

void

insertContentControl()

Wraps the body object with a Rich Text content control.

[ API set: WordApi 1.1 ]

insertContentControl(): Word.ContentControl;

Returns

Examples

// Run a batch operation against the Word object model.
Word.run(function (context) {

    // Create a proxy object for the document body.
    var body = context.document.body;

    // Queue a command to wrap the body in a content control.
    body.insertContentControl();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    return context.sync().then(function () {
        console.log('Wrapped the body in a content control.');
    });
})
.catch(function (error) {
    console.log('Error: ' + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
        console.log('Debug info: ' + JSON.stringify(error.debugInfo));
    }
});

insertFileFromBase64(base64File, insertLocation)

Inserts a document into the body at the specified location.

[ API set: WordApi 1.1 ]

insertFileFromBase64(base64File: string, insertLocation: Word.InsertLocation): Word.Range;

Parameters

base64File
string

Required. The base64 encoded content of a .docx file.

insertLocation
Word.InsertLocation

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

Returns

Examples

// Run a batch operation against the Word object model.
Word.run(function (context) {

    // Create a proxy object for the document body.
    var body = context.document.body;

    // Queue a command to insert base64 encoded .docx at the beginning of the content body.
    // You will need to implement getBase64() to pass in a string of a base64 encoded docx file.
    body.insertFileFromBase64(getBase64(), Word.InsertLocation.start);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    return context.sync().then(function () {
        console.log('Added base64 encoded text to the beginning of the document body.');
    });
})
.catch(function (error) {
    console.log('Error: ' + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
        console.log('Debug info: ' + JSON.stringify(error.debugInfo));
    }
});

insertFileFromBase64(base64File, insertLocationString)

Inserts a document into the body at the specified location.

[ API set: WordApi 1.1 ]

insertFileFromBase64(base64File: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range;

Parameters

base64File
string

Required. The base64 encoded content of a .docx file.

insertLocationString
"Before" | "After" | "Start" | "End" | "Replace"

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

Returns

insertHtml(html, insertLocation)

Inserts HTML at the specified location.

[ API set: WordApi 1.1 ]

insertHtml(html: string, insertLocation: Word.InsertLocation): Word.Range;

Parameters

html
string

Required. The HTML to be inserted in the document.

insertLocation
Word.InsertLocation

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

Returns

Examples

// Run a batch operation against the Word object model.
Word.run(function (context) {

    // Create a proxy object for the document body.
    var body = context.document.body;

    // Queue a command to insert HTML in to the beginning of the body.
    body.insertHtml(
        '<strong>This is text inserted with body.insertHtml()</strong>', Word.InsertLocation.start);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    return context.sync().then(function () {
        console.log('HTML added to the beginning of the document body.');
    });
})
.catch(function (error) {
    console.log('Error: ' + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
        console.log('Debug info: ' + JSON.stringify(error.debugInfo));
    }
});

insertHtml(html, insertLocationString)

Inserts HTML at the specified location.

[ API set: WordApi 1.1 ]

insertHtml(html: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range;

Parameters

html
string

Required. The HTML to be inserted in the document.

insertLocationString
"Before" | "After" | "Start" | "End" | "Replace"

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

Returns

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Inserts a picture into the body at the specified location.

[ API set: WordApi 1.2 ]

insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: Word.InsertLocation): Word.InlinePicture;

Parameters

base64EncodedImage
string

Required. The base64 encoded image to be inserted in the body.

insertLocation
Word.InsertLocation

Required. The value can be 'Start' or 'End'.

Returns

Examples

// Run a batch operation against the Word object model.
Word.run(function (context) {

    // Create a proxy object for the document body.
    var body = context.document.body;

    // Queue a command to insert OOXML in to the beginning of the body.
    body.insertOoxml("<pkg:package xmlns:pkg='http://schemas.microsoft.com/office/2006/xmlPackage'><pkg:part pkg:name='/_rels/.rels' pkg:contentType='application/vnd.openxmlformats-package.relationships+xml' pkg:padding='512'><pkg:xmlData><Relationships xmlns='http://schemas.openxmlformats.org/package/2006/relationships'><Relationship Id='rId1' Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument' Target='word/document.xml'/></Relationships></pkg:xmlData></pkg:part><pkg:part pkg:name='/word/document.xml' pkg:contentType='application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml'><pkg:xmlData><w:document xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' ><w:body><w:p><w:pPr><w:spacing w:before='360' w:after='0' w:line='480' w:lineRule='auto'/><w:rPr><w:color w:val='70AD47' w:themeColor='accent6'/><w:sz w:val='28'/></w:rPr></w:pPr><w:r><w:rPr><w:color w:val='70AD47' w:themeColor='accent6'/><w:sz w:val='28'/></w:rPr><w:t>This text has formatting directly applied to achieve its font size, color, line spacing, and paragraph spacing.</w:t></w:r></w:p></w:body></w:document></pkg:xmlData></pkg:part></pkg:package>", Word.InsertLocation.start);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    return context.sync().then(function () {
        console.log('OOXML added to the beginning of the document body.');
    });
})
.catch(function (error) {
    console.log('Error: ' + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
        console.log('Debug info: ' + JSON.stringify(error.debugInfo));
    }
});

// Read "Create better add-ins for Word with Office Open XML" for guidance on working with OOXML.
// https://docs.microsoft.com/office/dev/add-ins/word/create-better-add-ins-for-word-with-office-open-xml

// The Word-Add-in-DocumentAssembly sample shows how you can use this API to assemble a document.
// https://github.com/OfficeDev/Word-Add-in-DocumentAssembly

insertInlinePictureFromBase64(base64EncodedImage, insertLocationString)

Inserts a picture into the body at the specified location.

[ API set: WordApi 1.2 ]

insertInlinePictureFromBase64(base64EncodedImage: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.InlinePicture;

Parameters

base64EncodedImage
string

Required. The base64 encoded image to be inserted in the body.

insertLocationString
"Before" | "After" | "Start" | "End" | "Replace"

Required. The value can be 'Start' or 'End'.

Returns

insertOoxml(ooxml, insertLocation)

Inserts OOXML at the specified location.

[ API set: WordApi 1.1 ]

insertOoxml(ooxml: string, insertLocation: Word.InsertLocation): Word.Range;

Parameters

ooxml
string

Required. The OOXML to be inserted.

insertLocation
Word.InsertLocation

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

Returns

insertOoxml(ooxml, insertLocationString)

Inserts OOXML at the specified location.

[ API set: WordApi 1.1 ]

insertOoxml(ooxml: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range;

Parameters

ooxml
string

Required. The OOXML to be inserted.

insertLocationString
"Before" | "After" | "Start" | "End" | "Replace"

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

Returns

insertParagraph(paragraphText, insertLocation)

Inserts a paragraph at the specified location.

[ API set: WordApi 1.1 ]

insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation): Word.Paragraph;

Parameters

paragraphText
string

Required. The paragraph text to be inserted.

insertLocation
Word.InsertLocation

Required. The value can be 'Start' or 'End'.

Returns

Examples

// Run a batch operation against the Word object model.
Word.run(function (context) {

    // Create a proxy object for the document body.
    var body = context.document.body;

    // Queue a command to insert the paragraph at the end of the document body.
    body.insertParagraph('Content of a new paragraph', Word.InsertLocation.end);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    return context.sync().then(function () {
        console.log('Paragraph added at the end of the document body.');
    });
})
.catch(function (error) {
    console.log('Error: ' + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
        console.log('Debug info: ' + JSON.stringify(error.debugInfo));
    }
});

// The Word-Add-in-DocumentAssembly sample shows how you can use the insertParagraph method to assemble a document.
// https://github.com/OfficeDev/Word-Add-in-DocumentAssembly

insertParagraph(paragraphText, insertLocationString)

Inserts a paragraph at the specified location.

[ API set: WordApi 1.1 ]

insertParagraph(paragraphText: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Paragraph;

Parameters

paragraphText
string

Required. The paragraph text to be inserted.

insertLocationString
"Before" | "After" | "Start" | "End" | "Replace"

Required. The value can be 'Start' or 'End'.

Returns

insertTable(rowCount, columnCount, insertLocation, values)

Inserts a table with the specified number of rows and columns.

[ API set: WordApi 1.3 ]

insertTable(rowCount: number, columnCount: number, insertLocation: Word.InsertLocation, values?: string[][]): Word.Table;

Parameters

rowCount
number

Required. The number of rows in the table.

columnCount
number

Required. The number of columns in the table.

insertLocation
Word.InsertLocation

Required. The value can be 'Start' or 'End'.

values
string[][]

Optional 2D array. Cells are filled if the corresponding strings are specified in the array.

Returns

Examples

await Word.run(async (context) => {
  // Use a two-dimensional array to hold the initial table values.
  let data = [
    ["Tokyo", "Beijing", "Seattle"],
    ["Apple", "Orange", "Pineapple"]
  ];
  let table = context.document.body.insertTable(2, 3, "Start", data);
  table.styleBuiltIn = Word.Style.gridTable5Dark_Accent2;
  table.styleFirstColumn = false;

  await context.sync();
});

insertTable(rowCount, columnCount, insertLocationString, values)

Inserts a table with the specified number of rows and columns.

[ API set: WordApi 1.3 ]

insertTable(rowCount: number, columnCount: number, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace", values?: string[][]): Word.Table;

Parameters

rowCount
number

Required. The number of rows in the table.

columnCount
number

Required. The number of columns in the table.

insertLocationString
"Before" | "After" | "Start" | "End" | "Replace"

Required. The value can be 'Start' or 'End'.

values
string[][]

Optional 2D array. Cells are filled if the corresponding strings are specified in the array.

Returns

insertText(text, insertLocation)

Inserts text into the body at the specified location.

[ API set: WordApi 1.1 ]

insertText(text: string, insertLocation: Word.InsertLocation): Word.Range;

Parameters

text
string

Required. Text to be inserted.

insertLocation
Word.InsertLocation

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

Returns

Examples

// Run a batch operation against the Word object model.
Word.run(function (context) {

    // Create a proxy object for the document body.
    var body = context.document.body;

    // Queue a command to insert text in to the beginning of the body.
    body.insertText('This is text inserted with body.insertText()', Word.InsertLocation.start);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    return context.sync().then(function () {
        console.log('Text added to the beginning of the document body.');
    });
})
.catch(function (error) {
    console.log('Error: ' + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
        console.log('Debug info: ' + JSON.stringify(error.debugInfo));
    }
});

insertText(text, insertLocationString)

Inserts text into the body at the specified location.

[ API set: WordApi 1.1 ]

insertText(text: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range;

Parameters

text
string

Required. Text to be inserted.

insertLocationString
"Before" | "After" | "Start" | "End" | "Replace"

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

Returns

load(option)

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

load(option?: Word.Interfaces.BodyLoadOptions): Word.Body;

Parameters

Returns

Remarks

In addition to this signature, this method has the following signatures:

load(option?: string | string[]): Word.Body - Where option is a comma-delimited string or an array of strings that specify the properties to load.

load(option?: { select?: string; expand?: string; }): Word.Body - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load.

load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.Body - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items.

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.Body;

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.Body;

Parameters

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

Where 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

search(searchText, searchOptions)

Performs a search with the specified SearchOptions on the scope of the body object. The search results are a collection of range objects.

[ API set: WordApi 1.1 ]

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

Required. The search text. Can be a maximum of 255 characters.

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

Optional. Options for the search.

Returns

Examples

await Word.run(async (context) => {
  let results = context.document.body.search("Online");
  results.load("length");

  await context.sync();

  // Let's traverse the search results... and highlight...
  for (let i = 0; i < results.items.length; i++) {
    results.items[i].font.highlightColor = "yellow";
  }

  await context.sync();
});
await Word.run(async (context) => {
  // Check out how wildcard expression are built, also use the second parameter of the search method to include search modes
  // (i.e. use wildcards).
  let results = context.document.body.search("$*.[0-9][0-9]", { matchWildcards: true });
  results.load("length");

  await context.sync();

  // Let's traverse the search results... and highlight...
  for (let i = 0; i < results.items.length; i++) {
    results.items[i].font.highlightColor = "red";
    results.items[i].font.color = "white";
  }

  await context.sync();
});
await Word.run(async (context) => {
  let paragraphs = context.document.body.paragraphs;
  paragraphs.load("text");
  await context.sync();

  let text = [];
  paragraphs.items.forEach((item) => {
    let paragraph = item.text.trim();
    if (paragraph) {
      paragraph.split(" ").forEach((term) => {
        let currentTerm = term.trim();
        if (currentTerm) {
          text.push(currentTerm);
        }
      });
    }
  });

  let makeTextDistinct = new Set(text);
  let distinctText = Array.from(makeTextDistinct);
  let allSearchResults = [];

  for (let i = 0; i < distinctText.length; i++) {
    let results = context.document.body.search(distinctText[i], { matchCase: true, matchWholeWord: true });
    results.load("text");

    // Map search term with its results.
    let correlatedResults = {
      searchTerm: distinctText[i],
      hits: results
    };

    allSearchResults.push(correlatedResults);
  }

  await context.sync();

  // Display counts.
  allSearchResults.forEach((result) => {
    let length = result.hits.items.length;

    console.log("Search term: " + result.searchTerm + " => Count: " + length);
  });
});

select(selectionMode)

Selects the body and navigates the Word UI to it.

[ API set: WordApi 1.1 ]

select(selectionMode?: Word.SelectionMode): void;

Parameters

selectionMode
Word.SelectionMode

Optional. The selection mode can be 'Select', 'Start', or 'End'. 'Select' is the default.

Returns

void

Examples

// Run a batch operation against the Word object model.
Word.run(function (context) {

    // Create a proxy object for the document body.
    var body = context.document.body;

    // Queue a command to select the document body. The Word UI will
    // move to the selected document body.
    body.select();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    return context.sync().then(function () {
        console.log('Selected the document body.');
    });
})
.catch(function (error) {
    console.log('Error: ' + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
        console.log('Debug info: ' + JSON.stringify(error.debugInfo));
    }
});

select(selectionModeString)

Selects the body and navigates the Word UI to it.

[ API set: WordApi 1.1 ]

select(selectionModeString?: "Select" | "Start" | "End"): void;

Parameters

selectionModeString
"Select" | "Start" | "End"

Optional. The selection mode can be 'Select', 'Start', or 'End'. 'Select' is the default.

Returns

void

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.BodyUpdateData, options?: OfficeExtension.UpdateOptions): void;

Parameters

properties
Interfaces.BodyUpdateData

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

Remarks

This method has the following additional signature:

set(properties: Word.Body): void

set(properties)

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

set(properties: Word.Body): void;

Parameters

properties
Word.Body

Returns

void

toJSON()

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

toJSON(): Word.Interfaces.BodyData;

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 are 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 needed to have added the object to the tracked object collection when the object was first created.

track(): Word.Body;

Returns

untrack()

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

untrack(): Word.Body;

Returns