Word.Body class

Represents the body of a document or a section.

[ API set: WordApi 1.1 ]

Extends

Properties

contentControls

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

[ API set: WordApi 1.1 ]

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 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 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 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 the HTML representation of the body object.

[ 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 ]

insertBreak(breakType, insertLocation)

Inserts a break at the specified location in the main document. The insertLocation value can be 'Start' or 'End'.

[ 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. The insertLocation value can be 'Replace', 'Start', or 'End'.

[ API set: WordApi 1.1 ]

insertHtml(html, insertLocation)

Inserts HTML at the specified location. The insertLocation value can be 'Replace', 'Start', or 'End'.

[ API set: WordApi 1.1 ]

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Inserts a picture into the body at the specified location. The insertLocation value can be 'Start' or 'End'.

[ API set: WordApi 1.2 ]

insertOoxml(ooxml, insertLocation)

Inserts OOXML at the specified location. The insertLocation value can be 'Replace', 'Start', or 'End'.

[ API set: WordApi 1.1 ]

insertParagraph(paragraphText, insertLocation)

Inserts a paragraph at the specified location. The insertLocation value can be 'Start' or 'End'.

[ API set: WordApi 1.1 ]

insertTable(rowCount, columnCount, insertLocation, values)

Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Start' or 'End'.

[ API set: WordApi 1.3 ]

insertText(text, insertLocation)

Inserts text into the body at the specified location. The insertLocation value can be 'Replace', 'Start', or 'End'.

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

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 ]

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

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

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

Word.ParagraphCollection

parentBody

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

[ API set: WordApi 1.3 ]

readonly parentBody: Word.Body;

Property Value

Word.Body

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

Word.Body

parentContentControl

Gets the content control that contains the body. Throws 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 if there isn't a parent section. Read-only.

[ API set: WordApi 1.3 ]

readonly parentSection: Word.Section;

Property Value

Word.Section

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

Word.Section

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

Word.TableCollection

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

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 commmand 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 the HTML representation of the body object.

[ 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 commmand 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 commmand 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

Word.Range

insertBreak(breakType, insertLocation)

Inserts a break at the specified location in the main document. The insertLocation value can be 'Start' or 'End'.

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

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 commmand 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. The insertLocation value can be 'Replace', 'Start', or 'End'.

[ 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

Word.Range

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

insertHtml(html, insertLocation)

Inserts HTML at the specified location. The insertLocation value can be 'Replace', 'Start', or 'End'.

[ 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

Word.Range

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

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Inserts a picture into the body at the specified location. The insertLocation value can be 'Start' or 'End'.

[ 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 commmand 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

insertOoxml(ooxml, insertLocation)

Inserts OOXML at the specified location. The insertLocation value can be 'Replace', 'Start', or 'End'.

[ 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

Word.Range

insertParagraph(paragraphText, insertLocation)

Inserts a paragraph at the specified location. The insertLocation value can be 'Start' or 'End'.

[ 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

Word.Paragraph

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 commmand 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
await Word.run(async (context) => {
    let paragraph = context.document.body.insertParagraph("Timeline", "End");
    paragraph.style = "Heading 2";
    let paragraph2 = context.document.body.insertParagraph("The Services shall commence on July 31, 2015, and shall continue through July 29, 2015.", "End");
    paragraph2.style = "Normal";
    let paragraph3 = context.document.body.insertParagraph("Project Costs by Phase", "End");
    paragraph3.style = "Heading 2";
    // Note a content control with the title of "ProjectCosts" is added. Content will be replaced later.
    let paragraph4 = context.document.body.insertParagraph("<Add Project Costs Here>", "End");
    paragraph4.style = "Normal";
    paragraph4.font.highlightColor = "#FFFF00";
    let contentControl = paragraph4.insertContentControl();
    contentControl.title = "ProjectCosts";
    let paragraph5 = context.document.body.insertParagraph("Project Team", "End");
    paragraph5.style = "Heading 2";
    paragraph5.font.highlightColor = "#FFFFFF";
    let paragraph6 = context.document.body.insertParagraph("Terms of Work", "End");
    paragraph6.style = "Heading 1";
    let paragraph7 = context.document.body.insertParagraph("Contractor shall provide the Services and Deliverable(s) as follows:", "End");
    paragraph7.style = "Normal";
    let paragraph8 = context.document.body.insertParagraph("Out-of-Pocket Expenses / Invoice Procedures", "End");
    paragraph8.style = "Heading 2";
    let paragraph9 = context.document.body.insertParagraph("Client will be invoiced monthly for the consulting services and T&L expenses. Standard Contractor invoicing is assumed to be acceptable. Invoices are due upon receipt. client will be invoiced all costs associated with out-of-pocket expenses (including, without limitation, costs and expenses associated with meals, lodging, local transportation and any other applicable business expenses) listed on the invoice as a separate line item. Reimbursement for out-of-pocket expenses in connection with performance of this SOW, when authorized and up to the limits set forth in this SOW, shall be in accordance with Client's then-current published policies governing travel and associated business expenses, which information shall be provided by the Client Project Manager.", "End");
    paragraph9.style = "Normal";
    // Insert a page break at the end of the document.
    context.document.body.insertBreak("Page", "End");

    await context.sync();
});

insertTable(rowCount, columnCount, insertLocation, values)

Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Start' or 'End'.

[ 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

Word.Table

Examples

await Word.run(async (context) => {
  // We need a 2D 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();
});

insertText(text, insertLocation)

Inserts text into the body at the specified location. The insertLocation value can be 'Replace', 'Start', or 'End'.

[ 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

Word.Range

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

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?: string | string[]): Word.Body;

Parameters

option
string | string[]

A comma-delimited string or an array of strings that specify the properties to load.

Returns

Word.Body

Remarks

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

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.

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

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

// 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 commmand to search the document.
    var searchResults = context.document.body.search('video', {matchCase: false});

    // Queue a commmand to load the results.
    context.load(searchResults, 'text, font');

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    return context.sync().then(function () {
        var results = 'Found count: ' + searchResults.items.length +
                      '; we highlighted the results.';

        // Queue a command to change the font for each found item.
        for (var i = 0; i < searchResults.items.length; i++) {
          searchResults.items[i].font.color = '#FF0000'    // Change color to Red
          searchResults.items[i].font.highlightColor = '#FFFF00';
          searchResults.items[i].font.bold = true;
        }

        // Synchronize the document state by executing the queued commands,
        // and return a promise to indicate task completion.
        return context.sync().then(function () {
            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));
    }
});

// The Word-Add-in-DocumentAssembly sample provides another example of how to search a document.
// https://github.com/OfficeDev/Word-Add-in-DocumentAssembly
await Word.run(async (context) => {
    let results = context.document.body.search("Online");
    results.load("font/highlightColor");

    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. we are using wildcards).
    let results = context.document.body.search("$*.[0-9][0-9]", { matchWildcards: true });
    results.load("font/highlightColor, font/color");

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

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

toJSON()

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

Word.Body

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

Word.Body