### Load and display the current page orientation and margins of the active document Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.PageSetup.md This example shows how to get the page setup of the document body, load specific properties like orientation and margins, sync to read them, and then display them in the console. ```typescript await Word.run(async (context) => { // Get the page setup of the document body const pageSetup = context.document.body.pageSetup; // Load specific properties pageSetup.load("orientation, topMargin, bottomMargin, leftMargin, rightMargin"); // Sync to read the loaded properties await context.sync(); // Display the loaded properties console.log(`Orientation: ${pageSetup.orientation}`); console.log(`Top Margin: ${pageSetup.topMargin}`); console.log(`Bottom Margin: ${pageSetup.bottomMargin}`); console.log(`Left Margin: ${pageSetup.leftMargin}`); console.log(`Right Margin: ${pageSetup.rightMargin}`); }); ``` -------------------------------- ### Example: Get the application name and version information from the Word application Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.RequestContext.md This example demonstrates how to load and log the name and version of the Word application. ```typescript await Word.run(async (context: Word.RequestContext) => { const app = context.application; // Load the application properties app.load("name, version"); await context.sync(); console.log(`Application: ${app.name}`); console.log(`Version: ${app.version}`); }); ``` -------------------------------- ### Get the starting character position of a bookmark Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.Bookmark.md Retrieves the starting character position of a bookmark named 'Introduction' and logs it to the console. ```typescript await Word.run(async (context) => { const bookmark = context.document.getBookmarkByName("Introduction"); bookmark.load("start"); await context.sync(); console.log(`The bookmark starts at character position: ${bookmark.start}`); }); ``` -------------------------------- ### Example Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.WindowCollection.md Get and activate the first open Word window to bring it into focus ```typescript await Word.run(async (context) => { // Get the collection of all windows const windows = context.application.windows; // Get the first window in the collection const firstWindow = windows.getFirst(); // Activate the first window to bring it into focus firstWindow.activate(); await context.sync(); console.log("First window has been activated"); }); ``` -------------------------------- ### Example: Access the document body and insert text at the beginning of the Word document Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.RequestContext.md This example shows how to access the document body and insert text at the start of the document. ```typescript await Word.run(async (context: Word.RequestContext) => { // Access the document through the context const document = context.document; const body = document.body; // Insert text at the start of the document body.insertText("Hello from Word.js API!", Word.InsertLocation.start); await context.sync(); }); ``` -------------------------------- ### Get the starting character position of the first paragraph in the document and display it in the console Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.Range.md This example retrieves the starting character position of the first paragraph in a Word document and logs it to the console. ```typescript await Word.run(async (context) => { const firstParagraph = context.document.body.paragraphs.getFirst(); const range = firstParagraph.getRange(); range.load("start"); await context.sync(); console.log(`The paragraph starts at character position: ${range.start}`); }); ``` -------------------------------- ### Set the vertical alignment of the document to center so that text is vertically centered on each page Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.PageSetup.md This example demonstrates how to get the page setup of the first section and set its vertical alignment to center. ```typescript await Word.run(async (context) => { // Get the page setup of the first section const pageSetup = context.document.sections.getFirst().pageSetup; // Set vertical alignment to center pageSetup.verticalAlignment = Word.PageSetupVerticalAlignment.center; await context.sync(); }); ``` -------------------------------- ### Access the page setup's request context to verify the connection to the Word host application and log its diagnostic information Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.PageSetup.md This example shows how to access the request context associated with the page setup object to verify the connection to the Word host application and log diagnostic information. ```typescript await Word.run(async (context) => { // Get the page setup of the active document const pageSetup = context.document.body.pageSetup; // Access the request context associated with the page setup object const requestContext = pageSetup.context; // Use the context to verify connection and get diagnostic info console.log("Request context is connected:", requestContext !== null); console.log("Context debug info:", requestContext.debugInfo); // The context connects the add-in process to Word's process // and is used internally for all API operations await context.sync(); }); ``` -------------------------------- ### Set the footer distance to 36 points (0.5 inches) from the bottom of the page Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.PageSetup.md This example demonstrates how to get the page setup of the active document and set the footer distance to 36 points. ```typescript await Word.run(async (context) => { // Get the page setup of the active document const pageSetup = context.document.body.pageSetup; // Set the footer distance to 36 points (0.5 inches) pageSetup.footerDistance = 36; await context.sync(); console.log("Footer distance set to 36 points"); }); ``` -------------------------------- ### load(options) method Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.PageSetup.md Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties. ```typescript load(options?: Word.Interfaces.PageSetupLoadOptions): Word.PageSetup; ``` -------------------------------- ### Example: Get border details about the first row of the first table Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.TableRowCollection.md This example demonstrates how to get border details about the first row of the first table in the document using the `getFirst()` method. ```typescript // Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/40-tables/manage-formatting.yaml // Gets border details about the first row of the first table in the document. await Word.run(async (context) => { const firstTable: Word.Table = context.document.body.tables.getFirst(); const firstTableRow: Word.TableRow = firstTable.rows.getFirst(); const borderLocation = Word.BorderLocation.bottom; const border: Word.TableBorder = firstTableRow.getBorder(borderLocation); border.load(["type", "color", "width"]); await context.sync(); console.log( `Details about the ${borderLocation} border of the first table's first row`, `- Color: ${border.color}`, `- Type: ${border.type}`, `- Width: ${border.width} points` ); }); ``` -------------------------------- ### Set the section to start on a new page Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.PageSetup.md Sets the section to start on a new page. ```typescript await Word.run(async (context) => { // Get the first section of the document const section = context.document.sections.getFirst(); // Load the page setup section.load("pageSetup"); await context.sync(); // Set the section to start on a new page section.pageSetup.sectionStart = Word.SectionStart.newPage; await context.sync(); }); ``` -------------------------------- ### Get the text content from a bookmark named "Introduction" and display it in the console. Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.Bookmark.md This example retrieves a bookmark by name, accesses its range, loads the 'text' property of the range, synchronizes the context, and then logs the bookmark's text content. ```typescript await Word.run(async (context) => { // Get the bookmark by name const bookmark = context.document.bookmarks.getByName("Introduction"); // Get the range of the bookmark const bookmarkRange = bookmark.range; // Load the text property of the range bookmarkRange.load("text"); await context.sync(); // Display the bookmark's text content console.log("Bookmark text: " + bookmarkRange.text); }); ``` -------------------------------- ### Example: Get first comment's range and text Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.CommentCollection.md This example demonstrates how to get the range of the first comment in the selected content. It also shows how to handle cases where no comments are present. ```typescript // Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-comments.yaml // Gets the range of the first comment in the selected content. await Word.run(async (context) => { const comment: Word.Comment = context.document.getSelection().getComments().getFirstOrNullObject(); comment.load("contentRange"); const range: Word.Range = comment.getRange(); range.load("text"); await context.sync(); if (comment.isNullObject) { console.warn("No comments in the selection, so no range to get."); return; } console.log(`Comment location: ${range.text}`); const contentRange: Word.CommentContentRange = comment.contentRange; console.log("Comment content range:", contentRange); }); ``` -------------------------------- ### Example: Get all available templates and display their names in the console. Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.TemplateCollection.md Retrieves all available templates and logs their names to the console. ```typescript await Word.run(async (context) => { const templateCollection = context.application.templates; templateCollection.load("items"); await context.sync(); const templates = templateCollection.items; console.log(`Found ${templates.length} template(s):`); for (let i = 0; i < templates.length; i++) { templates[i].load("name"); } await context.sync(); templates.forEach((template, index) => { console.log(`${index + 1}. ${template.name}`); }); }); ``` -------------------------------- ### Get range of the picture Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.InlinePicture.md Gets the picture, or the starting or ending point of the picture, as a range. ```typescript getRange(rangeLocation?: Word.RangeLocation.whole | Word.RangeLocation.start | Word.RangeLocation.end | "Whole" | "Start" | "End"): Word.Range; ``` -------------------------------- ### Configure page setup for the document by setting multiple properties including orientation, margins, and paper size at once Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.PageSetup.md This example demonstrates how to set various page setup properties such as orientation, margins, and paper size simultaneously using the `set` method. ```typescript await Word.run(async (context) => { const pageSetup = context.document.body.pageSetup; pageSetup.set({ orientation: Word.PageOrientation.landscape, topMargin: 72, // 1 inch in points bottomMargin: 72, leftMargin: 54, // 0.75 inches rightMargin: 54, pageWidth: 792, // 11 inches (letter size) pageHeight: 612 // 8.5 inches (letter size) }); await context.sync(); console.log("Page setup configured successfully"); }); ``` -------------------------------- ### Example Usage of Field Methods Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.Field.md This example demonstrates how to get, update, and select a field in the document. ```typescript // Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-fields.yaml // Gets and updates the first field in the selection. await Word.run(async (context) => { let field = context.document.getSelection().fields.getFirstOrNullObject(); field.load(["code", "result", "type", "locked"]); await context.sync(); if (field.isNullObject) { console.log("No field in selection."); } else { console.log("Before updating:", "Code of first field: " + field.code, "Result of first field: " + JSON.stringify(field.result)); field.updateResult(); field.select(); await context.sync(); field.load(["code", "result"]); await context.sync(); console.log("After updating:", "Code of first field: " + field.code, "Result of first field: " + JSON.stringify(field.result)); } }); ``` -------------------------------- ### Get Base64 Image Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.Range.md This example demonstrates how to get the base64 representation of an image within a Word document. ```javascript const pictureBase64 = "DX5r3raF0nKqzHKtEyf1JDgD1d1+m7A8Asrqk47VyR29o3n9nbtd1im/CzMMLR1u/SUdAb/ar5aa7By0QV+HuTBVMXtl8GGGzezraxXXMQ3+96bGOru6bAnNf7D608EUBgNXWKGW0nJ8BsOCtY4or1Ise5f+FKCBa2HtqBUwujWK0LqbBXMfThqVFO56CbgUNtAulwa0uYK2wkHM9WtiOecHkqRcj7UEAqH+ZwkVq5fS0ctzRcPxSNhtzC5yUc5NO03pFABQWRFc/w5jWC7oSpgr4TJoDLB0JdCfdBfH7VSbh0UPbSqnj5XvxK2aXP4P485IkSZIkSZIkSZIkSZIkSZIkSZIk8Tv/B3bBREdOWYS3AAAAAElFTkSuQmCC"; return pictureBase64; ``` -------------------------------- ### Retrieve page setup settings as a plain JavaScript object and log them to the console for debugging or data export purposes. Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.PageSetup.md Overrides the JavaScript toJSON() method in order to provide more useful output when an API object is passed to JSON.stringify(). ```typescript await Word.run(async (context) => { // Get the page setup of the first section const firstSection = context.document.sections.getFirst(); const pageSetup = firstSection.pageSetup; // Load the properties we want to serialize pageSetup.load("orientation,pageWidth,pageHeight,topMargin,bottomMargin,leftMargin,rightMargin"); await context.sync(); // Convert the PageSetup object to a plain JavaScript object const pageSetupData = pageSetup.toJSON(); // Now we can use the plain object for logging, storage, or comparison console.log("Page Setup Data:", pageSetupData); console.log("Page Width:", pageSetupData.pageWidth); console.log("Page Height:", pageSetupData.pageHeight); console.log("Orientation:", pageSetupData.orientation); }); ``` -------------------------------- ### Example: Get all bookmarks in the document and log their names to the console Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.BookmarkCollection.md Get all bookmarks in the document and log their names to the console. ```typescript await Word.run(async (context) => { // Get the bookmark collection from the document const bookmarks = context.document.body.bookmarks; // Load the items property to access the array of bookmarks bookmarks.load("items"); await context.sync(); // Access the loaded bookmark items and log their names console.log(`Total bookmarks: ${bookmarks.items.length}`); bookmarks.items.forEach((bookmark, index) => { bookmark.load("name"); }); await context.sync(); bookmarks.items.forEach((bookmark, index) => { console.log(`Bookmark ${index + 1}: ${bookmark.name}`); }); }); ``` -------------------------------- ### load(propertyNamesAndPaths) method Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.PageSetup.md Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties. ```typescript load(propertyNamesAndPaths?: { select?: string; expand?: string; }): Word.PageSetup; ``` -------------------------------- ### Get the parent comment of a reply and display its content Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.CommentReply.md This example shows how to get the parent comment of a reply and display its content in the console. ```typescript await Word.run(async (context) => { // Get the first comment reply in the document const commentReplies = context.document.body.getComments().getFirstOrNullObject().replies; const firstReply = commentReplies.getFirstOrNullObject(); // Get the parent comment of this reply const parentComment = firstReply.parentComment; // Load the content of the parent comment parentComment.load("content"); await context.sync(); if (!firstReply.isNullObject) { console.log("Parent comment content: " + parentComment.content); } }); ``` -------------------------------- ### load(propertyNames) method Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.PageSetup.md Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties. ```typescript load(propertyNames?: string | string[]): Word.PageSetup; ``` -------------------------------- ### Select a bookmark named "Introduction" in the document to highlight its location for the user Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.Bookmark.md This example shows how to select a bookmark by its name, which highlights its location in the document. ```typescript await Word.run(async (context) => { // Get the bookmark named "Introduction" const bookmark = context.document.bookmarks.getByName("Introduction"); // Select the bookmark bookmark.select(); await context.sync(); }); ``` -------------------------------- ### Get the relative vertical position of a shape in the document and display it in the console. Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.Shape.md This example shows how to get and log the relative vertical position of a shape. ```typescript await Word.run(async (context) => { // Get the first shape in the document body const shapes = context.document.body.shapes; shapes.load("items"); await context.sync(); if (shapes.items.length > 0) { const shape = shapes.items[0]; shape.load("relativeVerticalPosition"); await context.sync(); console.log("Shape's relative vertical position: " + shape.relativeVerticalPosition); // Possible values: "margin", "page", "paragraph", "line", "topMargin", "bottomMargin", "insideMargin", "outsideMargin" } }); ``` -------------------------------- ### Configure the document to use a different header and footer on the first page Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.PageSetup.md This example demonstrates configuring the document to use a different header and footer on the first page. ```typescript await Word.run(async (context) => { // Get the page setup of the document body const pageSetup = context.document.body.pageSetup; // Enable different header/footer for the first page pageSetup.differentFirstPageHeaderFooter = true; await context.sync(); console.log("First page will now have different headers and footers"); }); ``` -------------------------------- ### Example: Get all shapes within a canvas Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.Canvas.md Get all shapes within a canvas and log their count and types to the console ```typescript await Word.run(async (context) => { // Get the first canvas in the document const canvases = context.document.body.inlinePictures.getFirst().getAsCanvasOrNullObject(); const canvas = context.document.body.canvases.getFirst(); // Get the shapes collection from the canvas const shapes = canvas.shapes; shapes.load("items"); await context.sync(); // Log the count and types of shapes console.log(`Total shapes in canvas: ${shapes.items.length}`); shapes.items.forEach((shape, index) => { shape.load("type"); }); await context.sync(); shapes.items.forEach((shape, index) => { console.log(`Shape ${index + 1}: ${shape.type}`); }); }); ``` -------------------------------- ### Example: Get the canvas identifier Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.Canvas.md Get the canvas identifier and display it in the console to track which canvas is being processed in the document. ```typescript await Word.run(async (context) => { const canvas = context.document.body.getCanvases().getFirst(); canvas.load("id"); await context.sync(); console.log(`Canvas ID: ${canvas.id}`); }); ``` -------------------------------- ### Load and display all custom document settings with their keys and values Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.SettingCollection.md This example demonstrates how to retrieve all custom settings from a document and log their keys and values to the console. ```typescript await Word.run(async (context) => { // Get the settings collection const settings = context.document.settings; // Load the settings collection with key and value properties settings.load("items"); await context.sync(); // Display all settings console.log(`Total settings: ${settings.items.length}`); settings.items.forEach(setting => { console.log(`Key: ${setting.key}, Value: ${setting.value}`); }); }); ``` -------------------------------- ### Get the first annotation in the document and display its ID in the console Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.AnnotationCollection.md This example shows how to get the first annotation in the document and display its ID in the console. ```typescript await Word.run(async (context) => { // Get the annotations collection from the document body const annotations = context.document.body.getAnnotations(); // Get the first annotation in the collection const firstAnnotation = annotations.getFirst(); // Load the ID property firstAnnotation.load("id"); // Sync to execute the queued commands await context.sync(); // Display the first annotation's ID console.log("First annotation ID:", firstAnnotation.id); }); ``` -------------------------------- ### Example: Load and display the names of all building block categories available in the document Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.BuildingBlockCategoryCollection.md This example demonstrates how to load the 'name' property for all building block categories in the collection and then display them. ```typescript await Word.run(async (context) => { // Get the building block categories collection const categories = context.document.buildingBlockCategories; // Load the 'name' property for all categories in the collection categories.load("name"); // Synchronize the document state await context.sync(); // Display the category names console.log("Building Block Categories:"); for (let i = 0; i < categories.items.length; i++) { console.log(`- ${categories.items[i].name}`); } }); ``` -------------------------------- ### Class Examples Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.RequestContext.md The *.run methods automatically create an OfficeExtension.ClientRequestContext object to work with the Office file. ```typescript await Word.run(async (context: Word.RequestContext) => { const document = context.document; // Interact with the Word document... }); ``` -------------------------------- ### showGrid Property Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.PageSetup.md Specifies whether to show the grid. This API is a preview and should not be used in production. ```typescript showGrid: boolean; ``` -------------------------------- ### Example for getPreviousOrNullObject() Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.Paragraph.md This example demonstrates how to use the getPreviousOrNullObject() method to get the preceding paragraph and log its text. ```typescript // 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); } }); ``` -------------------------------- ### Example Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.IndexCollection.md Get all indexes in the document and display their titles in the console. ```typescript await Word.run(async (context) => { // Get the index collection from the document const indexes = context.document.body.indexes; // Load the items property to access the array of Index objects indexes.load("items"); await context.sync(); // Access the loaded items array and display each index title console.log(`Found ${indexes.items.length} index(es) in the document`); indexes.items.forEach((index, i) => { index.load("type"); console.log(`Index ${i + 1}: ${index.type}`); }); await context.sync(); }); ``` -------------------------------- ### Show the document grid to help with alignment and layout Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.PageSetup.md Shows the document grid to assist with alignment and layout. ```typescript await Word.run(async (context) => { // Get the page setup of the document const pageSetup = context.document.body.pageSetup; // Show the grid pageSetup.showGrid = true; await context.sync(); }); ``` -------------------------------- ### Example of getFirstOrNullObject() Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.FieldCollection.md Gets the first field in the document. ```typescript // Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-fields.yaml // Gets the first field in the document. await Word.run(async (context) => { const field: Word.Field = context.document.body.fields.getFirstOrNullObject(); field.load({"code": true, "result": true, "locked": true, "type": true, "data": true, "kind": true}); await context.sync(); if (field.isNullObject) { console.log("This document has no fields."); } else { console.log( "Code of first field: " + field.code, "Result of first field: " + JSON.stringify(field.result), "Type of first field: " + field.type, "Is the first field locked? " + field.locked, "Kind of the first field: " + field.kind ); } }); ``` -------------------------------- ### Example for open() Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.DocumentCreated.md Create and open a new document in a new tab or window. ```typescript // Create and open a new document in a new tab or window. await Word.run(async (context) => { const externalDoc = context.application.createDocument(); await context.sync(); externalDoc.open(); await context.sync(); }); ``` -------------------------------- ### Example: Get the index position of the first column in a table and display it in the console. Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.TableColumn.md Gets the index position of the first column in a table and displays it in the console. ```typescript await Word.run(async (context) => { // Get the first table in the document const table = context.document.body.tables.getFirst(); // Get the first column const firstColumn = table.columns.getFirst(); // Load the columnIndex property firstColumn.load("columnIndex"); await context.sync(); // Display the column index console.log(`Column index: ${firstColumn.columnIndex}`); }); ``` -------------------------------- ### load(options) Method Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.Window.md Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. ```typescript load(options?: Word.Interfaces.WindowLoadOptions): Word.Window; ``` -------------------------------- ### Example: Get shadow formatting properties Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.ShadowFormat.md Gets the shadow formatting properties of the first shape in the document as a plain JavaScript object and logs it to the console. ```typescript await Word.run(async (context) => { // Get the first shape in the document const shapes = context.document.body.shapes; shapes.load("items"); await context.sync(); if (shapes.items.length > 0) { const shape = shapes.items[0]; const shadowFormat = shape.shadow; // Load shadow properties shadowFormat.load("blur,color,offsetX,offsetY,transparency,type"); await context.sync(); // Convert to plain JavaScript object const shadowData = shadowFormat.toJSON(); // Log the shadow properties console.log("Shadow Format Data:", shadowData); console.log("Shadow Type:", shadowData.type); console.log("Shadow Color:", shadowData.color); console.log("Shadow Blur:", shadowData.blur); } }); ``` -------------------------------- ### Track a page setup object across multiple sync calls to modify its margins and orientation without encountering InvalidObjectPath errors Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.PageSetup.md Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). ```typescript await Word.run(async (context) => { const pageSetup = context.document.body.pageSetup; pageSetup.load("topMargin,orientation"); // Track the object to use it across multiple sync calls pageSetup.track(); await context.sync(); console.log(`Current top margin: ${pageSetup.topMargin}`); // Modify properties after sync - tracking prevents InvalidObjectPath error pageSetup.topMargin = 72; // 1 inch pageSetup.orientation = Word.PageOrientation.landscape; await context.sync(); console.log("Page setup updated successfully"); // Untrack when done to free up memory pageSetup.untrack(); }); ``` -------------------------------- ### Example: Get all reviewers who have made changes to the document and display their names in the console. Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.RevisionsFilter.md Gets all reviewers who have made changes to the document and displays their names in the console. ```typescript await Word.run(async (context) => { // Get the revisions filter const revisionsFilter = context.document.getRevisionsFilter(); // Get the reviewers collection const reviewers = revisionsFilter.reviewers; // Load the reviewer names reviewers.load("items/name"); await context.sync(); // Display all reviewer names console.log("Document reviewers:"); for (let i = 0; i < reviewers.items.length; i++) { console.log(`- ${reviewers.items[i].name}`); } }); ``` -------------------------------- ### Configure a document to use different headers and footers for odd and even pages Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.PageSetup.md This example shows how to configure the document to use distinct headers and footers for odd and even pages. ```typescript await Word.run(async (context) => { const pageSetup = context.document.body.pageSetup; // Enable different headers/footers for odd and even pages pageSetup.oddAndEvenPagesHeaderFooter = true; await context.sync(); console.log("Odd and even pages will now have different headers and footers"); }); ``` -------------------------------- ### Match Prefix Example Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.SearchOptions.md Finds all words in the document that begin with the specified prefix. ```typescript await Word.run(async (context) => { const searchOptions = { matchPrefix: true }; const searchResults = context.document.body.search("micro", searchOptions); searchResults.load("text"); await context.sync(); console.log(`Found ${searchResults.items.length} words starting with "micro"`); searchResults.items.forEach(result => { console.log(result.text); }); }); ``` -------------------------------- ### Example: Get the list object from a selected range and display its ID in the console. Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.ListFormat.md Get the list object from a selected range and display its ID in the console. ```typescript await Word.run(async (context) => { const range = context.document.getSelection(); const listFormat = range.listFormat; const list = listFormat.list; list.load("id"); await context.sync(); console.log("List ID: " + list.id); }); ``` -------------------------------- ### Get the first pane in the document and activate it to bring it into focus. Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.PaneCollection.md This example demonstrates how to get the first pane in the document using the `getFirst()` method and then activate it. ```typescript await Word.run(async (context) => { const panes = context.document.panes; const firstPane = panes.getFirst(); firstPane.activate(); await context.sync(); console.log("First pane has been activated"); }); ``` -------------------------------- ### Set the document to display 44 lines per page in the document grid Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.PageSetup.md This example shows how to set the number of lines that will be displayed per page within the document grid. ```typescript await Word.run(async (context) => { // Get the page setup of the document const pageSetup = context.document.body.pageSetup; // Set the number of lines per page to 44 pageSetup.linesPage = 44; await context.sync(); }); ``` -------------------------------- ### Get the first list in the document and highlight it in yellow Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.ListCollection.md This example demonstrates how to get the first list in the document, load its paragraphs, and then highlight each paragraph in yellow. ```typescript await Word.run(async (context) => { // Get the first list in the document const firstList = context.document.body.lists.getFirst(); // Load the list's paragraphs to apply formatting firstList.load("paragraphs"); await context.sync(); // Highlight all paragraphs in the first list for (let i = 0; i < firstList.paragraphs.items.length; i++) { firstList.paragraphs.items[i].font.highlightColor = "yellow"; } await context.sync(); }); ``` -------------------------------- ### Example: Get the distance between the drop cap and the paragraph text and display it to the user. Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.DropCap.md Gets the distance between the drop cap and the paragraph text and displays it to the user. ```typescript await Word.run(async (context) => { const firstParagraph = context.document.body.paragraphs.getFirst(); const dropCap = firstParagraph.dropCap; dropCap.load("distanceFromText"); await context.sync(); const distance = dropCap.distanceFromText; console.log(`Distance from text: ${distance} points`); }); ``` -------------------------------- ### set(properties) Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.PageSetup.md Sets multiple properties on the object at the same time, based on an existing loaded object. ```typescript set(properties: Word.PageSetup): void; ``` -------------------------------- ### Get and display the ID of the first reply to the first comment Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.CommentReply.md This example demonstrates how to get and display the ID of the first reply to the first comment in the document. ```typescript await Word.run(async (context) => { // Get the first comment in the document const firstComment = context.document.body.getComments().getFirst(); // Get the first reply to that comment const firstReply = firstComment.replies.getFirst(); // Load the ID property firstReply.load("id"); await context.sync(); // Display the comment reply ID console.log("Comment Reply ID: " + firstReply.id); }); ``` -------------------------------- ### Example: Import all building blocks from available templates into Word to make them accessible for use in the current document. Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.TemplateCollection.md Imports building blocks from all available templates into Word, making them accessible for use in the current document. ```typescript await Word.run(async (context) => { // Get the template collection const templates = context.application.templates; // Import building blocks from all templates templates.importBuildingBlocks(); // Sync to execute the import operation await context.sync(); console.log("Building blocks imported successfully from all templates."); }); ``` -------------------------------- ### Examples Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.RequestContext.md The *.run methods automatically create an OfficeExtension.ClientRequestContext object to work with the Office file. ```typescript // *.run methods automatically create an OfficeExtension.ClientRequestContext // object to work with the Office file. await Word.run(async (context: Word.RequestContext) => { const document = context.document; // Interact with the Word document... }); ``` -------------------------------- ### Get the ID of the first comment in the document and display it in the console. Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.Comment.md This example shows how to get the ID of the first comment in a Word document and log it to the console. ```typescript await Word.run(async (context) => { const comments = context.document.body.getComments(); comments.load("items"); await context.sync(); if (comments.items.length > 0) { const firstComment = comments.items[0]; firstComment.load("id"); await context.sync(); console.log("Comment ID: " + firstComment.id); } }); ``` -------------------------------- ### load(options) Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.WindowCollection.md Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. ```typescript load(options?: Word.Interfaces.WindowCollectionLoadOptions & Word.Interfaces.CollectionLoadOptions): Word.WindowCollection; ``` -------------------------------- ### Get the third building block entry and insert it Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.BuildingBlockEntryCollection.md This example gets the third building block entry from a collection and inserts it into the document at the current selection. ```typescript await Word.run(async (context) => { // Get the building blocks from the first template const template = context.document.getTemplate(); const buildingBlockEntries = template.buildingBlockEntries; // Get the building block at index 2 (third item) const buildingBlock = buildingBlockEntries.getItemAt(2); buildingBlock.load("name"); // Insert the building block at the current selection const range = context.document.getSelection(); buildingBlock.insertContent(range, Word.InsertLocation.replace); await context.sync(); console.log(`Inserted building block: ${buildingBlock.name}`); }); ``` -------------------------------- ### Load and display building block properties Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.BuildingBlock.md This example shows how to load and display the 'name' and 'type' properties of a building block from the gallery. ```typescript await Word.run(async (context) => { // Get the first building block from the first gallery const gallery = context.document.buildingBlockGalleries.getFirst(); const buildingBlock = gallery.buildingBlocks.getFirst(); // Load specific properties of the building block buildingBlock.load("name, type"); // Sync to execute the load command await context.sync(); // Now we can read the loaded properties console.log("Building Block Name: " + buildingBlock.name); console.log("Building Block Type: " + buildingBlock.type); }); ``` -------------------------------- ### Example: Get the top border of the first paragraph and set its color to red Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.BorderUniversalCollection.md Gets the top border of the first paragraph and sets its color to red. ```typescript await Word.run(async (context) => { const paragraph = context.document.body.paragraphs.getFirst(); const borders = paragraph.getBorders(); // Get the top border (index 0) from the collection const topBorder = borders.getItem(0); topBorder.color = "red"; await context.sync(); }); ``` -------------------------------- ### Example: Get the content of the first cell in the first table. Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.Body.md Gets the content of the first cell in the first table. ```TypeScript // Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/40-tables/table-cell-access.yaml // Gets the content of the first cell in the first table. await Word.run(async (context) => { const firstCell: Word.Body = context.document.body.tables.getFirst().getCell(0, 0).body; firstCell.load("text"); await context.sync(); console.log("First cell's text is: " + firstCell.text); }); ``` -------------------------------- ### pageSetup Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.Interfaces.DocumentLoadOptions.md Returns a `PageSetup` object that's associated with the document. ```typescript pageSetup?: Word.Interfaces.PageSetupLoadOptions; ``` -------------------------------- ### Example: Get the location of a paragraph's bottom border and display it in the console Source: https://github.com/magician-blue/word-js-doc/blob/main/Word.Border.md Get the location of a paragraph's bottom border and display it in the console ```typescript await Word.run(async (context) => { // Get the first paragraph in the document const paragraph = context.document.body.paragraphs.getFirst(); // Get the bottom border of the paragraph const border = paragraph.getBorder(Word.BorderLocation.bottom); // Load the location property border.load("location"); await context.sync(); // Display the border location console.log("Border location: " + border.location); }); ``` -------------------------------- ### set(properties, options) method Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.PageSetup.md 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. ```typescript set(properties: Interfaces.PageSetupUpdateData, options?: OfficeExtension.UpdateOptions): void; ``` -------------------------------- ### Example Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.Comment.md Get and display the author name of the first comment in the document ```typescript await Word.run(async (context) => { const comments = context.document.body.getComments(); comments.load("items"); await context.sync(); if (comments.items.length > 0) { const firstComment = comments.items[0]; firstComment.load("authorName"); await context.sync(); console.log("Comment author: " + firstComment.authorName); } }); ``` -------------------------------- ### Example: Access the request context from a window pane to verify the connection between the add-in and Word, then use it to load and log the pane's index property. Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.Pane.md Access the request context from a window pane to verify the connection between the add-in and Word, then use it to load and log the pane's index property. ```typescript await Word.run(async (context) => { // Get the active pane const activePane = context.document.getActiveWindow().panes.getFirst(); // Access the request context from the pane object const paneContext = activePane.context; // Use the context to load properties activePane.load("index"); await paneContext.sync(); console.log(`Pane index: ${activePane.index}`); console.log("Request context successfully accessed from pane object"); }); ``` -------------------------------- ### load(options) Method Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.BuildingBlock.md Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties. ```typescript load(options?: Word.Interfaces.BuildingBlockLoadOptions): Word.BuildingBlock; ``` -------------------------------- ### Examples Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.Field.md Gets the parent body of the first field in the document. ```typescript // Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-fields.yaml // Gets the parent body of the first field in the document. await Word.run(async (context) => { const field: Word.Field = context.document.body.fields.getFirstOrNullObject(); field.load("parentBody/text"); await context.sync(); if (field.isNullObject) { console.log("This document has no fields."); } else { const parentBody: Word.Body = field.parentBody; console.log("Text of first field's parent body: " + JSON.stringify(parentBody.text)); } }); ``` -------------------------------- ### Example: Access the request context from SearchOptions Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.SearchOptions.md This example shows how to access the request context from a SearchOptions object. It creates search options, retrieves the context, and then uses the context to load document properties and synchronize the state. ```typescript await Word.run(async (context) => { // Create search options const searchOptions = context.document.body.search("example", { matchCase: false }).getFirst().searchOptions; // Access the request context from the SearchOptions object const requestContext = searchOptions.context; // Verify the context is valid by using it to load properties requestContext.document.load("saved"); await requestContext.sync(); console.log("Request context is active and connected to Word"); }); ``` -------------------------------- ### Example: Get the type of the first shape in the document and display it to the user Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.Shape.md Gets all shapes in the document body, loads their items, synchronizes, gets the first shape, loads its type, synchronizes again, and logs the shape type to the console. ```typescript await Word.run(async (context) => { const shapes = context.document.body.shapes; shapes.load("items"); await context.sync(); if (shapes.items.length > 0) { const firstShape = shapes.items[0]; firstShape.load("type"); await context.sync(); console.log(`Shape type: ${firstShape.type}`); // Type will be one of: "TextBox", "GeometricShape", "Group", "Picture", or "Canvas" } }); ``` -------------------------------- ### load (options) Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.Bookmark.md Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. ```typescript load(options?: Word.Interfaces.BookmarkLoadOptions): Word.Bookmark; ``` -------------------------------- ### load(options) Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.BuildingBlockGalleryContentControl.md Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties. ```typescript load(options?: Word.Interfaces.BuildingBlockGalleryContentControlLoadOptions): Word.BuildingBlockGalleryContentControl; ``` -------------------------------- ### Get and display the text content of the currently selected range in a Word document Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.Range.md This example shows how to get the currently selected text in a Word document and display it. ```typescript await Word.run(async (context) => { // Get the current selection const range = context.document.getSelection(); // Load the text property of the range range.load("text"); // Sync to execute the load command await context.sync(); // Now we can read the loaded property console.log("Selected text: " + range.text); }); ``` -------------------------------- ### load(options) method Source: https://github.com/magician-blue/word-js-doc/blob/main/api_docs/Word.TabStop.md Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties. ```typescript load(options?: Word.Interfaces.TabStopLoadOptions): Word.TabStop; ``` -------------------------------- ### Get the count of table columns that intersect with the selected range and display it in the console. Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.Range.md This example demonstrates how to get the count of table columns that intersect with the selected range. ```typescript await Word.run(async (context) => { // Get the selected range const range = context.document.getSelection(); // Get the table columns that intersect with this range const tableColumns = range.tableColumns; tableColumns.load("count"); await context.sync(); console.log(`Number of table columns in range: ${tableColumns.count}`); }); ``` -------------------------------- ### Get the previous paragraph from the current paragraph and highlight it in yellow Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.Paragraph.md This example demonstrates how to get the previous paragraph relative to the current one and apply a yellow highlight to it. ```typescript await Word.run(async (context) => { // Get the current paragraph (e.g., the first paragraph in the document) const paragraph = context.document.body.paragraphs.getFirst(); paragraph.load("text"); // Get the previous paragraph const previousParagraph = paragraph.getPrevious(); previousParagraph.load("text"); // Highlight the previous paragraph in yellow previousParagraph.font.highlightColor = "yellow"; await context.sync(); console.log("Previous paragraph text: " + previousParagraph.text); }); ``` -------------------------------- ### Activate a specific document window to bring it to the front and give it focus Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.Window.md This example demonstrates how to activate the current document window, bringing it to the front and giving it focus. ```typescript await Word.run(async (context) => { // Get the active window const window = context.document.window; // Activate the window to bring it to the front window.activate(); await context.sync(); console.log("Window has been activated"); }); ``` -------------------------------- ### Example: Search for the text "API" in the document with case-sensitive matching enabled Source: https://github.com/magician-blue/word-js-doc/blob/main/markdown_output/Word.SearchOptions.md This example demonstrates how to perform a case-sensitive search. It sets the `matchCase` option to `true`, searches for "API", loads the text of the results, and logs the count of exact case matches. ```typescript await Word.run(async (context) => { const searchOptions = { matchCase: true }; const searchResults = context.document.body.search("API", searchOptions); searchResults.load("text"); await context.sync(); console.log(`Found ${searchResults.items.length} case-sensitive matches for "API"`); }); ```