Word.Paragraph class

Represents a single paragraph in a selection, range, content control, or document body.

Extends

Remarks

[ API set: WordApi 1.1 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/get-paragraph-on-insertion-point.yaml

await Word.run(async (context) => {
  // The collection of paragraphs of the current selection returns the full paragraphs contained in it.
  const paragraph: Word.Paragraph = context.document.getSelection().paragraphs.getFirst();
  paragraph.load("text");

  await context.sync();
  console.log(paragraph.text);
});

Properties

alignment

Specifies the alignment for a paragraph. The value can be 'left', 'centered', 'right', or 'justified'.

contentControls

Gets the collection of content control objects in the paragraph.

context

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

firstLineIndent

Specifies the value, in points, for a first line or hanging indent. Use a positive value to set a first-line indent, and use a negative value to set a hanging indent.

font

Gets the text format of the paragraph. Use this to get and set font name, size, color, and other properties.

inlinePictures

Gets the collection of InlinePicture objects in the paragraph. The collection doesn't include floating images.

leftIndent

Specifies the left indent value, in points, for the paragraph.

lineSpacing

Specifies the line spacing, in points, for the specified paragraph. In the Word UI, this value is divided by 12.

lineUnitAfter

Specifies the amount of spacing, in grid lines, after the paragraph.

lineUnitBefore

Specifies the amount of spacing, in grid lines, before the paragraph.

outlineLevel

Specifies the outline level for the paragraph.

parentContentControl

Gets the content control that contains the paragraph. Throws an ItemNotFound error if there isn't a parent content control.

rightIndent

Specifies the right indent value, in points, for the paragraph.

spaceAfter

Specifies the spacing, in points, after the paragraph.

spaceBefore

Specifies the spacing, in points, before the paragraph.

style

Specifies the style name for the paragraph. 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.

text

Gets the text of the paragraph.

Methods

clear()

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

delete()

Deletes the paragraph and its content from the document.

getHtml()

Gets an HTML representation of the paragraph 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 doesn't return the exact same HTML for the same document on different platforms (Windows, Mac, Word on the web, etc.). If you need exact fidelity, or consistency across platforms, use Paragraph.getOoxml() and convert the returned XML to HTML.

getOoxml()

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

insertBreak(breakType, insertLocation)

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

insertContentControl(contentControlType)

Wraps the Paragraph object with a content control.

insertFileFromBase64(base64File, insertLocation)

Inserts a document into the paragraph at the specified location.

insertHtml(html, insertLocation)

Inserts HTML into the paragraph at the specified location.

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Inserts a picture into the paragraph at the specified location.

insertOoxml(ooxml, insertLocation)

Inserts OOXML into the paragraph at the specified location.

insertParagraph(paragraphText, insertLocation)

Inserts a paragraph at the specified location.

insertText(text, insertLocation)

Inserts text into the paragraph at the specified location.

load(options)

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

load(propertyNames)

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

load(propertyNamesAndPaths)

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

search(searchText, searchOptions)

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

select(selectionMode)

Selects and navigates the Word UI to the paragraph.

select(selectionModeString)

Selects and navigates the Word UI to the paragraph.

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's passed to it.) Whereas the original Word.Paragraph object is an API object, the toJSON method returns a plain JavaScript object (typed as Word.Interfaces.ParagraphData) that contains shallow copies of any loaded child properties from the original object.

track()

Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you're using this object across .sync calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you need to add the object to the tracked object collection when the object was first created. If this object is part of a collection, you should also track the parent collection.

untrack()

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

Property Details

alignment

Specifies the alignment for a paragraph. The value can be 'left', 'centered', 'right', or 'justified'.

alignment: Word.Alignment | "Mixed" | "Unknown" | "Left" | "Centered" | "Right" | "Justified";

Property Value

Word.Alignment | "Mixed" | "Unknown" | "Left" | "Centered" | "Right" | "Justified"

Remarks

[ API set: WordApi 1.1 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/paragraph-properties.yaml

await Word.run(async (context) => {
  // Center last paragraph alignment.
  context.document.body.paragraphs.getLast().alignment = "Centered";

  await context.sync();
});

contentControls

Gets the collection of content control objects in the paragraph.

readonly contentControls: Word.ContentControlCollection;

Property Value

Remarks

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

context: RequestContext;

Property Value

firstLineIndent

Specifies the value, in points, for a first line or hanging indent. Use a positive value to set a first-line indent, and use a negative value to set a hanging indent.

firstLineIndent: number;

Property Value

number

Remarks

[ API set: WordApi 1.1 ]

font

Gets the text format of the paragraph. Use this to get and set font name, size, color, and other properties.

readonly font: Word.Font;

Property Value

Remarks

[ API set: WordApi 1.1 ]

inlinePictures

Gets the collection of InlinePicture objects in the paragraph. The collection doesn't include floating images.

readonly inlinePictures: Word.InlinePictureCollection;

Property Value

Remarks

[ API set: WordApi 1.1 ]

leftIndent

Specifies the left indent value, in points, for the paragraph.

leftIndent: number;

Property Value

number

Remarks

[ API set: WordApi 1.1 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/paragraph-properties.yaml

await Word.run(async (context) => {
  // Indent the first paragraph.
  context.document.body.paragraphs.getFirst().leftIndent = 75; //units = points

  return context.sync();
});

lineSpacing

Specifies the line spacing, in points, for the specified paragraph. In the Word UI, this value is divided by 12.

lineSpacing: number;

Property Value

number

Remarks

[ API set: WordApi 1.1 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/paragraph-properties.yaml

await Word.run(async (context) => {
  // Adjust line spacing.
  context.document.body.paragraphs.getFirst().lineSpacing = 20;

  await context.sync();
});

lineUnitAfter

Specifies the amount of spacing, in grid lines, after the paragraph.

lineUnitAfter: number;

Property Value

number

Remarks

[ API set: WordApi 1.1 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/paragraph-properties.yaml

await Word.run(async (context) => {
  // Set the space (in line units) after the first paragraph.
  context.document.body.paragraphs.getFirst().lineUnitAfter = 1;

  await context.sync();
});

lineUnitBefore

Specifies the amount of spacing, in grid lines, before the paragraph.

lineUnitBefore: number;

Property Value

number

Remarks

[ API set: WordApi 1.1 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/paragraph-properties.yaml

await Word.run(async (context) => {
  // Set the space (in line units) before the first paragraph.
  context.document.body.paragraphs.getFirst().lineUnitBefore = 1;

  await context.sync();
});

outlineLevel

Specifies the outline level for the paragraph.

outlineLevel: number;

Property Value

number

Remarks

[ API set: WordApi 1.1 ]

parentContentControl

Gets the content control that contains the paragraph. Throws an ItemNotFound error if there isn't a parent content control.

readonly parentContentControl: Word.ContentControl;

Property Value

Remarks

[ API set: WordApi 1.1 ]

rightIndent

Specifies the right indent value, in points, for the paragraph.

rightIndent: number;

Property Value

number

Remarks

[ API set: WordApi 1.1 ]

spaceAfter

Specifies the spacing, in points, after the paragraph.

spaceAfter: number;

Property Value

number

Remarks

[ API set: WordApi 1.1 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/paragraph-properties.yaml

await Word.run(async (context) => {
  // Set the space (in points) after the first paragraph.
  context.document.body.paragraphs.getFirst().spaceAfter = 20;

  await context.sync();
});

spaceBefore

Specifies the spacing, in points, before the paragraph.

spaceBefore: number;

Property Value

number

Remarks

[ API set: WordApi 1.1 ]

style

Specifies the style name for the paragraph. 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.

style: string;

Property Value

string

Remarks

[ API set: WordApi 1.1 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-styles.yaml

// Applies the specified style to a paragraph.
await Word.run(async (context) => {
  const styleName = $("#style-name-to-use").val() as string;
  if (styleName == "") {
    console.warn("Enter a style name to apply.");
    return;
  }

  const style: Word.Style = context.document.getStyles().getByNameOrNullObject(styleName);
  style.load();
  await context.sync();

  if (style.isNullObject) {
    console.warn(`There's no existing style with the name '${styleName}'.`);
  } else if (style.type != Word.StyleType.paragraph) {
    console.log(`The '${styleName}' style isn't a paragraph style.`);
  } else {
    const body: Word.Body = context.document.body;
    body.clear();
    body.insertParagraph(
      "Do you want to create a solution that extends the functionality of Word? You can use the Office Add-ins platform to extend Word clients running on the web, on a Windows desktop, or on a Mac.",
      "Start"
    );
    const paragraph: Word.Paragraph = body.paragraphs.getFirst();
    paragraph.style = style.nameLocal;
    console.log(`'${styleName}' style applied to first paragraph.`);
  }
});

text

Gets the text of the paragraph.

readonly text: string;

Property Value

string

Remarks

[ API set: WordApi 1.1 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/get-paragraph-on-insertion-point.yaml

await Word.run(async (context) => {
  // The collection of paragraphs of the current selection returns the full paragraphs contained in it.
  const paragraph: Word.Paragraph = context.document.getSelection().paragraphs.getFirst();
  paragraph.load("text");

  await context.sync();
  console.log(paragraph.text);
});

Method Details

clear()

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

clear(): void;

Returns

void

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the paragraphs collection.
    const paragraphs = context.document.body.paragraphs;

    // Queue a command to load the style property for all of the paragraphs.
    paragraphs.load('style');

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();

    // Queue a command to clear the contents of the first paragraph.
    paragraphs.items[0].clear();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Cleared the contents of the first paragraph.');
});

delete()

Deletes the paragraph and its content from the document.

delete(): void;

Returns

void

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the paragraphs collection.
    const paragraphs = context.document.body.paragraphs;

    // Queue a command to load the text property for all of the paragraphs.
    paragraphs.load('text');

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();

    // Queue a command to delete the first paragraph.
    paragraphs.items[0].delete();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Deleted the first paragraph.');
});

getHtml()

Gets an HTML representation of the paragraph 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 doesn't return the exact same HTML for the same document on different platforms (Windows, Mac, Word on the web, etc.). If you need exact fidelity, or consistency across platforms, use Paragraph.getOoxml() and convert the returned XML to HTML.

getHtml(): OfficeExtension.ClientResult<string>;

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the paragraphs collection.
    const paragraphs = context.document.body.paragraphs;

    // Queue a command to load the style property for all of the paragraphs.
    paragraphs.load('style');

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();

    // Queue a set of commands to get the HTML of the first paragraph.
    const html = paragraphs.items[0].getHtml();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Paragraph HTML: ' + html.value);
});

getOoxml()

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

getOoxml(): OfficeExtension.ClientResult<string>;

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the paragraphs collection.
    const paragraphs = context.document.body.paragraphs;

    // Queue a command to load the style property for the top 2 paragraphs.
    paragraphs.load({select: 'style', top: 2} );

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();

    // Queue a set of commands to get the OOXML of the first paragraph.
    const ooxml = paragraphs.items[0].getOoxml();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Paragraph OOXML: ' + ooxml.value);
});

insertBreak(breakType, insertLocation)

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

insertBreak(breakType: Word.BreakType | "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line", insertLocation: Word.InsertLocation.before | Word.InsertLocation.after | "Before" | "After"): void;

Parameters

breakType

Word.BreakType | "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line"

Required. The break type to add to the document.

insertLocation

before | after | "Before" | "After"

Required. The value must be 'Before' or 'After'.

Returns

void

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the paragraphs collection.
    const paragraphs = context.document.body.paragraphs;

    // Queue a command to load the style property for the top 2 paragraphs.
    // We never perform an empty load. We always must request a property.
    paragraphs.load({select: 'style', top: 2} );

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();

    // Queue a command to get the first paragraph.
    const paragraph = paragraphs.items[0];

    // Queue a command to insert a page break after the first paragraph.
    paragraph.insertBreak(Word.BreakType.page, Word.InsertLocation.after);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Inserted a page break after the paragraph.');
});
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/insert-line-and-page-breaks.yaml

Word.run(async (context) => {
  context.document.body.paragraphs.getFirst().insertBreak(Word.BreakType.line, "After");

  await context.sync();
  console.log("success");
});

insertContentControl(contentControlType)

Wraps the Paragraph object with a content control.

insertContentControl(contentControlType?: Word.ContentControlType.richText | Word.ContentControlType.plainText | Word.ContentControlType.checkBox | Word.ContentControlType.dropDownList | Word.ContentControlType.comboBox | "RichText" | "PlainText" | "CheckBox" | "DropDownList" | "ComboBox"): Word.ContentControl;

Parameters

contentControlType

richText | plainText | checkBox | dropDownList | comboBox | "RichText" | "PlainText" | "CheckBox" | "DropDownList" | "ComboBox"

Optional. Content control type to insert. Must be 'RichText', 'PlainText', 'CheckBox', 'DropDownList', or 'ComboBox'. The default is 'RichText'.

Returns

Remarks

[ API set: WordApi 1.1 ]

Note: The contentControlType parameter was introduced in WordApi 1.5. PlainText support was added in WordApi 1.5. CheckBox support was added in WordApi 1.7. DropDownList and ComboBox support was added in WordApi 1.9.

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the paragraphs collection.
    const paragraphs = context.document.body.paragraphs;

    // Queue a command to load the style property for the top 2 paragraphs.
    // We never perform an empty load. We always must request a property.
    paragraphs.load({select: 'style', top: 2} );

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();

    // Queue a command to get the first paragraph.
    const paragraph = paragraphs.items[0];

    // Queue a command to wrap the first paragraph in a rich text content control.
    paragraph.insertContentControl();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Wrapped the first paragraph in a content control.');
});
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/insert-and-change-content-controls.yaml

// Traverses each paragraph of the document and wraps a content control on each with either a even or odd tags.
await Word.run(async (context) => {
  let paragraphs = context.document.body.paragraphs;
  paragraphs.load("$none"); // Don't need any properties; just wrap each paragraph with a content control.

  await context.sync();

  for (let i = 0; i < paragraphs.items.length; i++) {
    let contentControl = paragraphs.items[i].insertContentControl();
    // For even, tag "even".
    if (i % 2 === 0) {
      contentControl.tag = "even";
    } else {
      contentControl.tag = "odd";
    }
  }
  console.log("Content controls inserted: " + paragraphs.items.length);

  await context.sync();
});

insertFileFromBase64(base64File, insertLocation)

Inserts a document into the paragraph at the specified location.

insertFileFromBase64(base64File: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

Parameters

base64File

string

Required. The Base64-encoded content of a .docx file.

insertLocation

replace | start | end | "Replace" | "Start" | "End"

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

Returns

Remarks

[ API set: WordApi 1.1 ]

Note: Insertion isn't supported if the document being inserted contains an ActiveX control (likely in a form field). Consider replacing such a form field with a content control or other option appropriate for your scenario.

insertHtml(html, insertLocation)

Inserts HTML into the paragraph at the specified location.

insertHtml(html: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

Parameters

html

string

Required. The HTML to be inserted in the paragraph.

insertLocation

replace | start | end | "Replace" | "Start" | "End"

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

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the paragraphs collection.
    const paragraphs = context.document.body.paragraphs;

    // Queue a command to load the style property for the top 2 paragraphs.
    // We never perform an empty load. We always must request a property.
    paragraphs.load({select: 'style', top: 2} );

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();

    // Queue a command to get the first paragraph.
    const paragraph = paragraphs.items[0];

    // Queue a command to insert HTML content at the end of the first paragraph.
    paragraph.insertHtml('<strong>Inserted HTML.</strong>', Word.InsertLocation.end);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Inserted HTML content at the end of the first paragraph.');
});

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Inserts a picture into the paragraph at the specified location.

insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.InlinePicture;

Parameters

base64EncodedImage

string

Required. The Base64-encoded image to be inserted.

insertLocation

replace | start | end | "Replace" | "Start" | "End"

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

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the paragraphs collection.
    const paragraphs = context.document.body.paragraphs;

    // Queue a command to load the style property for all of the paragraphs.
    paragraphs.load('style');

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();

    // Queue a command to get the first paragraph.
    const paragraph = paragraphs.items[0];

    const b64encodedImg = "iVBORw0KGgoAAAANSUhEUgAAAB4AAAANCAIAAAAxEEnAAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACFSURBVDhPtY1BEoQwDMP6/0+XgIMTBAeYoTqso9Rkx1zG+tNj1H94jgGzeNSjteO5vtQQuG2seO0av8LzGbe3anzRoJ4ybm/VeKEerAEbAUpW4aWQCmrGFWykRzGBCnYy2ha3oAIq2MloW9yCCqhgJ6NtcQsqoIKdjLbFLaiACnYyf2fODbrjZcXfr2F4AAAAAElFTkSuQmCC";

    // Queue a command to insert a base64 encoded image at the beginning of the first paragraph.
    paragraph.insertInlinePictureFromBase64(b64encodedImg, Word.InsertLocation.start);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Added an image to the first paragraph.');
});

insertOoxml(ooxml, insertLocation)

Inserts OOXML into the paragraph at the specified location.

insertOoxml(ooxml: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

Parameters

ooxml

string

Required. The OOXML to be inserted in the paragraph.

insertLocation

replace | start | end | "Replace" | "Start" | "End"

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

Returns

Remarks

[ API set: WordApi 1.1 ]

insertParagraph(paragraphText, insertLocation)

Inserts a paragraph at the specified location.

insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation.before | Word.InsertLocation.after | "Before" | "After"): Word.Paragraph;

Parameters

paragraphText

string

Required. The paragraph text to be inserted.

insertLocation

before | after | "Before" | "After"

Required. The value must be 'Before' or 'After'.

Returns

Remarks

[ API set: WordApi 1.1 ]

insertText(text, insertLocation)

Inserts text into the paragraph at the specified location.

insertText(text: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

Parameters

text

string

Required. Text to be inserted.

insertLocation

replace | start | end | "Replace" | "Start" | "End"

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

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/insert-in-different-locations.yaml

await Word.run(async (context) => {
  // Replace the last paragraph.
  const range: Word.Range = context.document.body.paragraphs.getLast().insertText("Just replaced the last paragraph!", "Replace");
  range.font.highlightColor = "black";
  range.font.color = "white";

  await context.sync();
});

load(options)

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

load(options?: Word.Interfaces.ParagraphLoadOptions): Word.Paragraph;

Parameters

options
Word.Interfaces.ParagraphLoadOptions

Provides options for which properties of the object to load.

Returns

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

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

Parameters

propertyNamesAndPaths

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

propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load.

Returns

search(searchText, searchOptions)

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

search(searchText: string, searchOptions?: Word.SearchOptions | {
            ignorePunct?: boolean;
            ignoreSpace?: boolean;
            matchCase?: boolean;
            matchPrefix?: boolean;
            matchSuffix?: boolean;
            matchWholeWord?: boolean;
            matchWildcards?: boolean;
        }): Word.RangeCollection;

Parameters

searchText

string

Required. The search text.

searchOptions

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

Optional. Options for the search.

Returns

Remarks

[ API set: WordApi 1.1 ]

select(selectionMode)

Selects and navigates the Word UI to the paragraph.

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

Parameters

selectionMode
Word.SelectionMode

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

Returns

void

Remarks

[ API set: WordApi 1.1 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/scroll-to-range.yaml

await Word.run(async (context) => {
  // If select is called with no parameters, it selects the object.
  context.document.body.paragraphs.getLast().select();

  await context.sync();
});

...

await Word.run(async (context) => {
  // Select can be at the start or end of a range; this by definition moves the insertion point without selecting the range.
  context.document.body.paragraphs.getLast().select(Word.SelectionMode.end);

  await context.sync();
});

select(selectionModeString)

Selects and navigates the Word UI to the paragraph.

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

Parameters

selectionModeString

"Select" | "Start" | "End"

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

Returns

void

Remarks

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

Parameters

properties
Word.Interfaces.ParagraphUpdateData

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

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/90-scenarios/multiple-property-set.yaml

await Word.run(async (context) => {
  const paragraph: Word.Paragraph = context.document.body.paragraphs.getFirst();
  paragraph.set({
    leftIndent: 30,
    font: {
      bold: true,
      color: "red"
    }
  });

  await context.sync();
});

...

await Word.run(async (context) => {
  const firstParagraph: Word.Paragraph = context.document.body.paragraphs.getFirst();
  const secondParagraph: Word.Paragraph = firstParagraph.getNext();
  firstParagraph.load("text, font/color, font/bold, leftIndent");

  await context.sync();

  secondParagraph.set(firstParagraph);

  await context.sync();
});

set(properties)

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

set(properties: Word.Paragraph): void;

Parameters

properties
Word.Paragraph

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's passed to it.) Whereas the original Word.Paragraph object is an API object, the toJSON method returns a plain JavaScript object (typed as Word.Interfaces.ParagraphData) that contains shallow copies of any loaded child properties from the original object.

toJSON(): Word.Interfaces.ParagraphData;

Returns

track()

Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you're using this object across .sync calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you need to add the object to the tracked object collection when the object was first created. If this object is part of a collection, you should also track the parent collection.

track(): Word.Paragraph;

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

untrack(): Word.Paragraph;

Returns