Word.Paragraph class
Represents a single paragraph in a selection, range, content control, or document body.
- Extends
Remarks
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'. |
content |
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. |
endnotes | Gets the collection of endnotes in the paragraph. |
fields | Gets the collection of fields in the paragraph. |
first |
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. |
footnotes | Gets the collection of footnotes in the paragraph. |
inline |
Gets the collection of InlinePicture objects in the paragraph. The collection doesn't include floating images. |
is |
Indicates the paragraph is the last one inside its parent body. |
is |
Checks whether the paragraph is a list item. |
left |
Specifies the left indent value, in points, for the paragraph. |
line |
Specifies the line spacing, in points, for the specified paragraph. In the Word UI, this value is divided by 12. |
line |
Specifies the amount of spacing, in grid lines, after the paragraph. |
line |
Specifies the amount of spacing, in grid lines, before the paragraph. |
list | Gets the List to which this paragraph belongs. Throws an |
list |
Gets the ListItem for the paragraph. Throws an |
list |
Gets the ListItem for the paragraph. If the paragraph isn't part of a list, then this method will return an object with its |
list |
Gets the List to which this paragraph belongs. If the paragraph isn't in a list, then this method will return an object with its |
outline |
Specifies the outline level for the paragraph. |
parent |
Gets the parent body of the paragraph. |
parent |
Gets the content control that contains the paragraph. Throws an |
parent |
Gets the content control that contains the paragraph. If there isn't a parent content control, then this method will return an object with its |
parent |
Gets the table that contains the paragraph. Throws an |
parent |
Gets the table cell that contains the paragraph. Throws an |
parent |
Gets the table cell that contains the paragraph. If it isn't contained in a table cell, then this method will return an object with its |
parent |
Gets the table that contains the paragraph. If it isn't contained in a table, then this method will return an object with its |
right |
Specifies the right indent value, in points, for the paragraph. |
space |
Specifies the spacing, in points, after the paragraph. |
space |
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. |
style |
Specifies the built-in style name for the paragraph. Use this property for built-in styles that are portable between locales. To use custom styles or localized style names, see the "style" property. |
table |
Gets the level of the paragraph's table. It returns 0 if the paragraph isn't in a table. |
text | Gets the text of the paragraph. |
unique |
Gets a string that represents the paragraph identifier in the current session. ID is in standard 8-4-4-4-12 GUID format without curly braces and differs across sessions and coauthors. |
Methods
attach |
Lets the paragraph join an existing list at the specified level. Fails if the paragraph cannot join the list or if the paragraph is already a list item. |
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. |
detach |
Moves this paragraph out of its list, if the paragraph is a list item. |
get |
Gets annotations set on this Paragraph object. |
get |
Gets comments associated with the paragraph. |
get |
Gets the currently supported content controls in the paragraph. |
get |
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 |
get |
Gets the next paragraph. Throws an |
get |
Gets the next paragraph. If the paragraph is the last one, then this method will return an object with its |
get |
Gets the Office Open XML (OOXML) representation of the paragraph object. |
get |
Gets the previous paragraph. Throws an |
get |
Gets the previous paragraph. If the paragraph is the first one, then this method will return an object with its |
get |
Gets the whole paragraph, or the starting or ending point of the paragraph, as a range. |
get |
Gets reviewed text based on ChangeTrackingVersion selection. |
get |
Gets reviewed text based on ChangeTrackingVersion selection. |
get |
Returns the text of the paragraph. This excludes equations, graphics (e.g., images, videos, drawings), and special characters that mark various content (e.g., for content controls, fields, comments, footnotes, endnotes). By default, hidden text and text marked as deleted are excluded. |
get |
Gets the text ranges in the paragraph by using punctuation marks and/or other ending marks. |
get |
Gets the collection of the TrackedChange objects in the paragraph. |
insert |
Inserts annotations on this Paragraph object. |
insert |
Inserts a break at the specified location in the main document. |
insert |
Wraps the Paragraph object with a content control. |
insert |
Inserts a document into the paragraph at the specified location. |
insert |
Inserts HTML into the paragraph at the specified location. |
insert |
Inserts a picture into the paragraph at the specified location. |
insert |
Inserts OOXML into the paragraph at the specified location. |
insert |
Inserts a paragraph at the specified location. |
insert |
Inserts a table with the specified number of rows and columns. |
insert |
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 |
load(property |
Queues up a command to load the specified properties of the object. You must call |
load(property |
Queues up a command to load the specified properties of the object. You must call |
search(search |
Performs a search with the specified SearchOptions on the scope of the paragraph object. The search results are a collection of range objects. |
select(selection |
Selects and navigates the Word UI to the paragraph. |
select(selection |
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. |
split(delimiters, trim |
Splits the paragraph into child ranges by using delimiters. |
start |
Starts a new list with this paragraph. Fails if the paragraph is already a list item. |
toJSON() | Overrides the JavaScript |
track() | Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you're using this object across |
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 |
Events
on |
Occurs when new comments are added. |
on |
Occurs when a comment or its reply is changed. |
on |
Occurs when comments are deleted. |
on |
Occurs when a comment is deselected. |
on |
Occurs when a comment is selected. |
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
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
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
endnotes
Gets the collection of endnotes in the paragraph.
readonly endnotes: Word.NoteItemCollection;
Property Value
Remarks
fields
Gets the collection of fields in the paragraph.
readonly fields: Word.FieldCollection;
Property Value
Remarks
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
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
footnotes
Gets the collection of footnotes in the paragraph.
readonly footnotes: Word.NoteItemCollection;
Property Value
Remarks
inlinePictures
Gets the collection of InlinePicture objects in the paragraph. The collection doesn't include floating images.
readonly inlinePictures: Word.InlinePictureCollection;
Property Value
Remarks
isLastParagraph
Indicates the paragraph is the last one inside its parent body.
readonly isLastParagraph: boolean;
Property Value
boolean
Remarks
isListItem
Checks whether the paragraph is a list item.
readonly isListItem: boolean;
Property Value
boolean
Remarks
leftIndent
Specifies the left indent value, in points, for the paragraph.
leftIndent: number;
Property Value
number
Remarks
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
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
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
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();
});
list
Gets the List to which this paragraph belongs. Throws an ItemNotFound
error if the paragraph isn't in a list.
readonly list: Word.List;
Property Value
Remarks
listItem
Gets the ListItem for the paragraph. Throws an ItemNotFound
error if the paragraph isn't part of a list.
readonly listItem: Word.ListItem;
Property Value
Remarks
listItemOrNullObject
Gets the ListItem for the paragraph. If the paragraph isn't part of a list, then this method will return an object with its isNullObject
property set to true
. For further information, see *OrNullObject methods and properties.
readonly listItemOrNullObject: Word.ListItem;
Property Value
Remarks
listOrNullObject
Gets the List to which this paragraph belongs. If the paragraph isn't in a list, then this method will return an object with its isNullObject
property set to true
. For further information, see *OrNullObject methods and properties.
readonly listOrNullObject: Word.List;
Property Value
Remarks
outlineLevel
Specifies the outline level for the paragraph.
outlineLevel: number;
Property Value
number
Remarks
parentBody
Gets the parent body of the paragraph.
readonly parentBody: Word.Body;
Property Value
Remarks
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
parentContentControlOrNullObject
Gets the content control that contains the paragraph. If there isn't a parent content control, then this method will return an object with its isNullObject
property set to true
. For further information, see *OrNullObject methods and properties.
readonly parentContentControlOrNullObject: Word.ContentControl;
Property Value
Remarks
parentTable
Gets the table that contains the paragraph. Throws an ItemNotFound
error if it isn't contained in a table.
readonly parentTable: Word.Table;
Property Value
Remarks
parentTableCell
Gets the table cell that contains the paragraph. Throws an ItemNotFound
error if it isn't contained in a table cell.
readonly parentTableCell: Word.TableCell;
Property Value
Remarks
parentTableCellOrNullObject
Gets the table cell that contains the paragraph. If it isn't contained in a table cell, then this method will return an object with its isNullObject
property set to true
. For further information, see *OrNullObject methods and properties.
readonly parentTableCellOrNullObject: Word.TableCell;
Property Value
Remarks
parentTableOrNullObject
Gets the table that contains the paragraph. If it isn't contained in a table, then this method will return an object with its isNullObject
property set to true
. For further information, see *OrNullObject methods and properties.
readonly parentTableOrNullObject: Word.Table;
Property Value
Remarks
rightIndent
Specifies the right indent value, in points, for the paragraph.
rightIndent: number;
Property Value
number
Remarks
spaceAfter
Specifies the spacing, in points, after the paragraph.
spaceAfter: number;
Property Value
number
Remarks
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
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
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.`);
}
});
styleBuiltIn
Specifies the built-in style name for the paragraph. Use this property for built-in styles that are portable between locales. To use custom styles or localized style names, see the "style" property.
styleBuiltIn: Word.BuiltInStyleName | "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.BuiltInStyleName | "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"
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/90-scenarios/doc-assembly.yaml
await Word.run(async (context) => {
const paragraph: Word.Paragraph = context.document.body.insertParagraph("Timeline", "End");
paragraph.styleBuiltIn = "Heading2";
const paragraph2: Word.Paragraph = context.document.body.insertParagraph("The Services shall commence on July 31, 2015, and shall continue through July 29, 2015.", "End");
paragraph2.styleBuiltIn = "Normal";
const paragraph3: Word.Paragraph = context.document.body.insertParagraph("Project Costs by Phase", "End");
paragraph3.styleBuiltIn = "Heading2";
// Note a content control with the title of "ProjectCosts" is added. Content will be replaced later.
const paragraph4: Word.Paragraph = context.document.body.insertParagraph("<Add Project Costs Here>", "End");
paragraph4.styleBuiltIn = "Normal";
paragraph4.font.highlightColor = "#FFFF00";
const contentControl: Word.ContentControl = paragraph4.insertContentControl();
contentControl.title = "ProjectCosts";
const paragraph5: Word.Paragraph = context.document.body.insertParagraph("Project Team", "End");
paragraph5.styleBuiltIn = "Heading2";
paragraph5.font.highlightColor = "#FFFFFF";
const paragraph6: Word.Paragraph = context.document.body.insertParagraph("Terms of Work", "End");
paragraph6.styleBuiltIn = "Heading1";
const paragraph7: Word.Paragraph = context.document.body.insertParagraph("Contractor shall provide the Services and Deliverable(s) as follows:", "End");
paragraph7.styleBuiltIn = "Normal";
const paragraph8: Word.Paragraph = context.document.body.insertParagraph("Out-of-Pocket Expenses / Invoice Procedures", "End");
paragraph8.styleBuiltIn = "Heading2";
const paragraph9 : Word.Paragraph= 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.styleBuiltIn = "Normal";
// Insert a page break at the end of the document.
context.document.body.insertBreak("Page", "End");
await context.sync();
});
tableNestingLevel
Gets the level of the paragraph's table. It returns 0 if the paragraph isn't in a table.
readonly tableNestingLevel: number;
Property Value
number
Remarks
text
Gets the text of the paragraph.
readonly text: string;
Property Value
string
Remarks
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);
});
uniqueLocalId
Gets a string that represents the paragraph identifier in the current session. ID is in standard 8-4-4-4-12 GUID format without curly braces and differs across sessions and coauthors.
readonly uniqueLocalId: string;
Property Value
string
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-annotations.yaml
// Registers event handlers.
await Word.run(async (context) => {
eventContexts[0] = context.document.onParagraphAdded.add(paragraphChanged);
eventContexts[1] = context.document.onParagraphChanged.add(paragraphChanged);
eventContexts[2] = context.document.onAnnotationClicked.add(onClickedHandler);
eventContexts[3] = context.document.onAnnotationHovered.add(onHoveredHandler);
eventContexts[4] = context.document.onAnnotationInserted.add(onInsertedHandler);
eventContexts[5] = context.document.onAnnotationRemoved.add(onRemovedHandler);
eventContexts[6] = context.document.onAnnotationPopupAction.add(onPopupActionHandler);
await context.sync();
console.log("Event handlers registered.");
});
...
async function paragraphChanged(args: Word.ParagraphChangedEventArgs) {
await Word.run(async (context) => {
const results = [];
for (let id of args.uniqueLocalIds) {
let para = context.document.getParagraphByUniqueLocalId(id);
para.load("uniqueLocalId");
results.push({ para: para, text: para.getText() });
}
await context.sync();
for (let result of results) {
console.log(`${args.type}: ID ${result.para.uniqueLocalId}:-`, result.text.value);
}
});
}
Method Details
attachToList(listId, level)
Lets the paragraph join an existing list at the specified level. Fails if the paragraph cannot join the list or if the paragraph is already a list item.
attachToList(listId: number, level: number): Word.List;
Parameters
- listId
-
number
Required. The ID of an existing list.
- level
-
number
Required. The level in the list.
Returns
Remarks
clear()
Clears the contents of the paragraph object. The user can perform the undo operation on the cleared content.
clear(): void;
Returns
void
Remarks
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
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.');
});
detachFromList()
Moves this paragraph out of its list, if the paragraph is a list item.
detachFromList(): void;
Returns
void
Remarks
getAnnotations()
Gets annotations set on this Paragraph object.
getAnnotations(): Word.AnnotationCollection;
Returns
Remarks
getComments()
Gets comments associated with the paragraph.
getComments(): Word.CommentCollection;
Returns
Remarks
getContentControls(options)
Gets the currently supported content controls in the paragraph.
getContentControls(options?: Word.ContentControlOptions): Word.ContentControlCollection;
Parameters
- options
- Word.ContentControlOptions
Optional. Options that define which content controls are returned.
Returns
Remarks
Important: If specific types are provided in the options parameter, only content controls of supported types are returned. Be aware that an exception will be thrown on using methods of a generic Word.ContentControl that aren't relevant for the specific type. With time, additional types of content controls may be supported. Therefore, your add-in should request and handle specific types of content controls.
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
OfficeExtension.ClientResult<string>
Remarks
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);
});
getNext()
Gets the next paragraph. Throws an ItemNotFound
error if the paragraph is the last one.
getNext(): Word.Paragraph;
Returns
Remarks
getNextOrNullObject()
Gets the next paragraph. If the paragraph is the last one, then this method will return an object with its isNullObject
property set to true
. For further information, see *OrNullObject methods and properties.
getNextOrNullObject(): Word.Paragraph;
Returns
Remarks
getOoxml()
Gets the Office Open XML (OOXML) representation of the paragraph object.
getOoxml(): OfficeExtension.ClientResult<string>;
Returns
OfficeExtension.ClientResult<string>
Remarks
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);
});
getPrevious()
Gets the previous paragraph. Throws an ItemNotFound
error if the paragraph is the first one.
getPrevious(): Word.Paragraph;
Returns
Remarks
getPreviousOrNullObject()
Gets the previous paragraph. If the paragraph is the first one, then this method will return an object with its isNullObject
property set to true
. For further information, see *OrNullObject methods and properties.
getPreviousOrNullObject(): Word.Paragraph;
Returns
Remarks
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 commands to create a proxy object for the next-to-last paragraph.
const indexOfLastParagraph = paragraphs.items.length - 1;
const precedingParagraph = paragraphs.items[indexOfLastParagraph].getPreviousOrNullObject();
// Queue a command to load the text of the preceding paragraph.
precedingParagraph.load('text');
// Synchronize the document state by executing the queued commands,
// and return a promise to indicate task completion.
await context.sync();
if (precedingParagraph.isNullObject) {
console.log('There are no paragraphs before the current one.');
} else {
console.log('The preceding paragraph is: ' + precedingParagraph.text);
}
});
getRange(rangeLocation)
Gets the whole paragraph, or the starting or ending point of the paragraph, as a range.
getRange(rangeLocation?: Word.RangeLocation.whole | Word.RangeLocation.start | Word.RangeLocation.end | Word.RangeLocation.after | Word.RangeLocation.content | "Whole" | "Start" | "End" | "After" | "Content"): Word.Range;
Parameters
- rangeLocation
-
whole | start | end | after | content | "Whole" | "Start" | "End" | "After" | "Content"
Optional. The range location must be 'Whole', 'Start', 'End', 'After', or 'Content'.
Returns
Remarks
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) => {
// Get the complete sentence (as range) associated with the insertion point.
const sentences: Word.RangeCollection = context.document
.getSelection()
.getTextRanges(["."] /* Using the "." as delimiter */, false /*means without trimming spaces*/);
sentences.load("$none");
await context.sync();
// Expand the range to the end of the paragraph to get all the complete sentences.
const sentencesToTheEndOfParagraph: Word.RangeCollection = sentences.items[0]
.getRange()
.expandTo(
context.document
.getSelection()
.paragraphs.getFirst()
.getRange(Word.RangeLocation.end)
)
.getTextRanges(["."], false /* Don't trim spaces*/);
sentencesToTheEndOfParagraph.load("text");
await context.sync();
for (let i = 0; i < sentencesToTheEndOfParagraph.items.length; i++) {
console.log(sentencesToTheEndOfParagraph.items[i].text);
}
});
getReviewedText(changeTrackingVersion)
Gets reviewed text based on ChangeTrackingVersion selection.
getReviewedText(changeTrackingVersion?: Word.ChangeTrackingVersion): OfficeExtension.ClientResult<string>;
Parameters
- changeTrackingVersion
- Word.ChangeTrackingVersion
Optional. The value must be 'Original' or 'Current'. The default is 'Current'.
Returns
OfficeExtension.ClientResult<string>
Remarks
getReviewedText(changeTrackingVersionString)
Gets reviewed text based on ChangeTrackingVersion selection.
getReviewedText(changeTrackingVersionString?: "Original" | "Current"): OfficeExtension.ClientResult<string>;
Parameters
- changeTrackingVersionString
-
"Original" | "Current"
Optional. The value must be 'Original' or 'Current'. The default is 'Current'.
Returns
OfficeExtension.ClientResult<string>
Remarks
getText(options)
Returns the text of the paragraph. This excludes equations, graphics (e.g., images, videos, drawings), and special characters that mark various content (e.g., for content controls, fields, comments, footnotes, endnotes). By default, hidden text and text marked as deleted are excluded.
getText(options?: Word.GetTextOptions | {
IncludeHiddenText?: boolean;
IncludeTextMarkedAsDeleted?: boolean;
}): OfficeExtension.ClientResult<string>;
Parameters
- options
-
Word.GetTextOptions | { IncludeHiddenText?: boolean; IncludeTextMarkedAsDeleted?: boolean; }
Optional. Options that define whether the final result should include hidden text and text marked as deleted.
Returns
OfficeExtension.ClientResult<string>
Remarks
getTextRanges(endingMarks, trimSpacing)
Gets the text ranges in the paragraph by using punctuation marks and/or other ending marks.
getTextRanges(endingMarks: string[], trimSpacing?: boolean): Word.RangeCollection;
Parameters
- endingMarks
-
string[]
Required. The punctuation marks and/or other ending marks as an array of strings.
- trimSpacing
-
boolean
Optional. Indicates whether to trim spacing characters (spaces, tabs, column breaks, and paragraph end marks) from the start and end of the ranges returned in the range collection. Default is false which indicates that spacing characters at the start and end of the ranges are included in the range collection.
Returns
Remarks
getTrackedChanges()
Gets the collection of the TrackedChange objects in the paragraph.
getTrackedChanges(): Word.TrackedChangeCollection;
Returns
Remarks
insertAnnotations(annotations)
Inserts annotations on this Paragraph object.
insertAnnotations(annotations: Word.AnnotationSet): OfficeExtension.ClientResult<string[]>;
Parameters
- annotations
- Word.AnnotationSet
Annotations to set.
Returns
OfficeExtension.ClientResult<string[]>
An array of the inserted annotations identifiers.
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-annotations.yaml
// Adds annotations to the selected paragraph.
await Word.run(async (context) => {
const paragraph: Word.Paragraph = context.document.getSelection().paragraphs.getFirst();
const options: Word.CritiquePopupOptions = {
brandingTextResourceId: "PG.TabLabel",
subtitleResourceId: "PG.HelpCommand.TipTitle",
titleResourceId: "PG.HelpCommand.Label",
suggestions: ["suggestion 1", "suggestion 2", "suggestion 3"]
};
const critique1: Word.Critique = {
colorScheme: Word.CritiqueColorScheme.red,
start: 1,
length: 3,
popupOptions: options
};
const critique2: Word.Critique = {
colorScheme: Word.CritiqueColorScheme.green,
start: 6,
length: 1,
popupOptions: options
};
const critique3: Word.Critique = {
colorScheme: Word.CritiqueColorScheme.blue,
start: 10,
length: 3,
popupOptions: options
};
const critique4: Word.Critique = {
colorScheme: Word.CritiqueColorScheme.lavender,
start: 14,
length: 3,
popupOptions: options
};
const critique5: Word.Critique = {
colorScheme: Word.CritiqueColorScheme.berry,
start: 18,
length: 10,
popupOptions: options
};
const annotationSet: Word.AnnotationSet = {
critiques: [critique1, critique2, critique3, critique4, critique5]
};
const annotationIds = paragraph.insertAnnotations(annotationSet);
await context.sync();
console.log("Annotations inserted:", annotationIds.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.
Returns
void
Remarks
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
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.
Required. The value must be 'Replace', 'Start', or 'End'.
Returns
Remarks
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.
Required. The value must be 'Replace', 'Start', or 'End'.
Returns
Remarks
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.
Required. The value must be 'Replace', 'Start', or 'End'.
Returns
Remarks
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.
Required. The value must be 'Replace', 'Start', or 'End'.
Returns
Remarks
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.
Returns
Remarks
insertTable(rowCount, columnCount, insertLocation, values)
Inserts a table with the specified number of rows and columns.
insertTable(rowCount: number, columnCount: number, insertLocation: Word.InsertLocation.before | Word.InsertLocation.after | "Before" | "After", 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.
- values
-
string[][]
Optional 2D array. Cells are filled if the corresponding strings are specified in the array.
Returns
Remarks
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.
Required. The value must be 'Replace', 'Start', or 'End'.
Returns
Remarks
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
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
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
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
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
split(delimiters, trimDelimiters, trimSpacing)
Splits the paragraph into child ranges by using delimiters.
split(delimiters: string[], trimDelimiters?: boolean, trimSpacing?: boolean): Word.RangeCollection;
Parameters
- delimiters
-
string[]
Required. The delimiters as an array of strings.
- trimDelimiters
-
boolean
Optional. Indicates whether to trim delimiters from the ranges in the range collection. Default is false which indicates that the delimiters are included in the ranges returned in the range collection.
- trimSpacing
-
boolean
Optional. Indicates whether to trim spacing characters (spaces, tabs, column breaks, and paragraph end marks) from the start and end of the ranges returned in the range collection. Default is false which indicates that spacing characters at the start and end of the ranges are included in the range collection.
Returns
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/split-words-of-first-paragraph.yaml
await Word.run(async (context) => {
const paragraph: Word.Paragraph = context.document.body.paragraphs.getFirst();
const words = paragraph.split([" "], true /* trimDelimiters*/, true /* trimSpaces */);
words.load("text");
await context.sync();
for (let i = 0; i < words.items.length; i++) {
if (i >= 1) {
words.items[i - 1].font.highlightColor = "#FFFFFF";
}
words.items[i].font.highlightColor = "#FFFF00";
await context.sync();
await pause(200);
}
});
startNewList()
Starts a new list with this paragraph. Fails if the paragraph is already a list item.
startNewList(): Word.List;
Returns
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/20-lists/insert-list.yaml
// This example starts a new list with the second paragraph.
await Word.run(async (context) => {
const paragraphs: Word.ParagraphCollection = context.document.body.paragraphs;
paragraphs.load("$none");
await context.sync();
// Start new list using the second paragraph.
const list: Word.List = paragraphs.items[1].startNewList();
list.load("$none");
await context.sync();
// To add new items to the list, use Start or End on the insertLocation parameter.
list.insertParagraph("New list item at the start of the list", "Start");
const paragraph: Word.Paragraph = list.insertParagraph("New list item at the end of the list (set to list level 5)", "End");
// Set up list level for the list item.
paragraph.listItem.level = 4;
// To add paragraphs outside the list, use Before or After.
list.insertParagraph("New paragraph goes after (not part of the list)", "After");
await context.sync();
});
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
Event Details
onCommentAdded
Note
This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.
Occurs when new comments are added.
readonly onCommentAdded: OfficeExtension.EventHandlers<Word.CommentEventArgs>;
Event Type
Remarks
onCommentChanged
Note
This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.
Occurs when a comment or its reply is changed.
readonly onCommentChanged: OfficeExtension.EventHandlers<Word.CommentEventArgs>;
Event Type
Remarks
onCommentDeleted
Note
This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.
Occurs when comments are deleted.
readonly onCommentDeleted: OfficeExtension.EventHandlers<Word.CommentEventArgs>;
Event Type
Remarks
onCommentDeselected
Note
This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.
Occurs when a comment is deselected.
readonly onCommentDeselected: OfficeExtension.EventHandlers<Word.CommentEventArgs>;
Event Type
Remarks
onCommentSelected
Note
This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.
Occurs when a comment is selected.
readonly onCommentSelected: OfficeExtension.EventHandlers<Word.CommentEventArgs>;
Event Type
Remarks
Office Add-ins