Paragraphs


Writing Text

Write text to the current user selection

Office.context.document.setSelectedDataAsync("Hello World!", 
                                              function (asyncResult) {
  if (asyncResult.status == "failed") {
    showMessage("Action failed with error: " + asyncResult.error.message);
  }
});

Reading Text

Read text from the user current selection

Office.context.document.getSelectedDataAsync("text", 
                                             function (asyncResult) {
  if (asyncResult.status == "failed") {
    showMessage("Action failed with error: " + asyncResult.error.message);
  }
  else {
    showMessage("Selected data: " + asyncResult.value);
  }
});

insert a heading before some text

function doSomething() { 
Word.run(function (context) {
var selection = context.document.getSelection();
var paragraphs = selection.paragraphs.load('text');
var paragraph = range.insertParagraph("Customer", Word.InsertLocation.before);
paragraph.styleBuiltIn = "Heading1";

clear the contents of the body.

var body = ctx.document.body; 
body.clear();

load the text in document body.

var body = context.document.body; 
context.load(body, 'text');

wrap the body in a content control.

var body = ctx.document.body; 
body.insertContentControl();

insert HTML in to the beginning of the body.

var body = ctx.document.body; 
body.insertHtml('<strong>This is text inserted with body.insertHtml()</strong>', Word.InsertLocation.start);

insert OOXML in to the beginning of the body.

var body = ctx.document.body; 
body.insertOoxml("<w:p xmlns:w='http://schemas.microsoft.com/office/word/2003/wordml'><w:r><w:rPr><w:b/><w:b-cs/><w:color w:val='FF0000'/><w:sz w:val='28'/><w:sz-cs w:val='28'/></w:rPr><w:t>Hello world (this should be bold, red, size 14).</w:t></w:r></w:p>", Word.InsertLocation.start);

insert the paragraph at the end of the document body.

var body = ctx.document.body; 
body.insertParagraph('Content of a new paragraph', Word.InsertLocation.end);

insert text in to the beginning of the body.

var body = ctx.document.body; 
body.insertText('This is text inserted with body.insertText()', Word.InsertLocation.start);

load font and style information for the document body.

var body = ctx.document.body; 
context.load(body, 'font/size, font/name, font/color, style');

Searching

link - docs.microsoft.com/en-us/office/dev/add-ins/word/search-option-guidance

await Word.run(async (context) => { 
    var body = context.document.body;

    var options = Word.SearchOptions.newObject(context);
    options.matchCase = false
    var searchResults = context.document.body.search('video', options);
    var searchResults = context.document.body.search('video you', {ignorePunct: true});
    var searchResults = context.document.body.search('ly', {matchSuffix: true});
    var searchResults = context.document.body.search('to*n', {matchWildcards: true});

    context.load(searchResults, 'text, font');
    searchResults.load('font');

    await context.sync();

    console.log('Found count: ' + searchResults.items.length);

    for (var i = 0; i < searchResults.items.length; i++) {
       searchResults.items[i].font.color = '#FF0000' // Change color to Red, purple
       searchResults.items[i].font.highlightColor = '#FFFF00';
       searchResults.items[i].font.bold = true;
    }
        
    await context.sync();

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

inserting html into the selection

var htmlText = 
'<h1><strong>Insert Html</strong></h1>' +
'<h2><em>Office Extensibility Platform</em></h2>' +
'<p>This is an example of how the InsertHtml method works.</p>' +
'<table>' +
'<tr><td>Check</td><td>out</td></tr>' +
'<tr><td>this</td><td>table</td></tr>' +
'</table>';
var range = context.document.getSelection();
range.insertHtml(htmlText, Word.InsertLocation.end);

inserting text into the selection

var textSample = 'This is an example of the insert text method. This is a method ' + 
'which allows users to insert text into a selection.';
var range = context.document.getSelection();
range.insertText(textSample, Word.InsertLocation.end);

change the current selection's font name.

var selection = context.document.getSelection(); 
selection.font.name = 'Arial';
selection.font.bold = true;

Clear the contents of the first paragraph

Word.run(function (context) { 
    var paragraphs = context.document.body.paragraphs;
    context.load(paragraphs, 'style');
    
    return context.sync().then(function () {
        
        paragraphs._GetItem(0).clear();
        
        return context.sync().then(function () {
            console.log('Cleared the contents of the first paragraph.');
        });
    });
})

format line spacing

Word.run(function (context) { 
    var paragraphs = context.document.body.paragraphs;
    context.load(paragraphs, 'style');
    
    return context.sync().then(function () {
        var paragraph = paragraphs._GetItem(0);
        paragraph.linespacing = 36;
        
        return context.sync().then(function () {
            console.log('Changed the paragraph line spacing.');
        });
    });
})

Get Paragraph from Insertion Point

$("#get-paragraph").click(() => tryCatch(getParagraph)); 
$("#get-sentences").click(() => tryCatch(getSentences));
$("#setup").click(() => tryCatch(setup));

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

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

async function getSentences() {
  await Word.run(async (context) => {
    let sentences = context.document
      .getSelection()
      .getTextRanges(["."] /* Using the "." as delimiter */, false /*means without trimming spaces*/);
    sentences.load("$none");
    await context.sync();

    let sentencesToTheEndOfParagraph = sentences.items[0]
      .getRange()
      .expandTo(
        context.document
          .getSelection()
          .paragraphs.getFirst()
          .getRange("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);
    }
  });
}

async function setup() {
  await Word.run(async (context) => {
    context.document.body.clear();
    context.document.body.insertParagraph(
      "Video provides a powerful way to help you prove your point.",
      "Start"
    );
    context.document.body.paragraphs
      .getLast()
      .insertText(
        "To make your document look professionally produced.",
        "Replace"
      );
  });
}

async function tryCatch(callback) {
  try {
    await callback();
  } catch (error) {
    console.error(error);
  }
}

Insert Content at Different Locations

$("#setup").click(() => tryCatch(setup)); 
$("#before").click(() => tryCatch(before));
$("#start").click(() => tryCatch(start));
$("#end").click(() => tryCatch(end));
$("#after").click(() => tryCatch(after));
$("#replace").click(() => tryCatch(replace));

async function before() {
  await Word.run(async (context) => {
    let range = context.document.body.paragraphs.getFirst().insertParagraph("This is Before", "Before");
    range.font.highlightColor = "yellow";

    await context.sync();
  });
}

async function start() {
  await Word.run(async (context) => {
    // This button assumes before() ran.
    // Get the next paragraph and insert text at the beginning. Note that there are invalid locations depending on the object. For instance, insertParagraph and "before" on a paragraph object is not a valid combination.
    let range = context.document.body.paragraphs
      .getFirst()
      .getNext()
      .insertText("This is Start", "Start");
    range.font.highlightColor = "blue";
    range.font.color = "white";

    await context.sync();
  });
}

async function end() {
  await Word.run(async (context) => {
    let range = context.document.body.paragraphs
      .getFirst()
      .getNext()
      .insertText(" This is End", "End");
    range.font.highlightColor = "green";
    range.font.color = "white";

    await context.sync();
  });
}

async function after() {
  await Word.run(async (context) => {
    let range = context.document.body.paragraphs
      .getFirst()
      .getNext()
      .insertParagraph("This is After", "After");
    range.font.highlightColor = "red";
    range.font.color = "white";

    await context.sync();
  });
}

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

    await context.sync();
  });
}

async function setup() {
  await Word.run(async (context) => {
    context.document.body.clear();
    context.document.body.insertParagraph(
      "Video provides a powerful way to help you prove your point.",
      "Start"
    );
    context.document.body.paragraphs
      .getLast()
      .insertText(
        "To make your document look professionally produced.",
        "Replace"
      );
  });
}

async function tryCatch(callback) {
  try {
    await callback();
  } catch (error) {
    console.error(error);
  }
}

Paragraph Properties

$("#indent").click(() => tryCatch(indent)); 
$("#spacing").click(() => tryCatch(spacing));
$("#space-after").click(() => tryCatch(spaceAfter));
$("#align").click(() => tryCatch(align));
$("#setup").click(() => tryCatch(setup));

async function indent() {
  await Word.run(async (context) => {
    context.document.body.paragraphs.getFirst().leftIndent = 75; //units = points

    return context.sync();
  });
}

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

    await context.sync();
  });
}

async function spaceAfter() {
  await Word.run(async (context) => {
    context.document.body.paragraphs.getFirst().spaceAfter = 20;

    await context.sync();
  });
}

async function align() {
  await Word.run(async (context) => {
    context.document.body.paragraphs.getLast().alignment = "Centered";

    await context.sync();
  });
}

async function setup() {
  await Word.run(async (context) => {
    context.document.body.clear();
    context.document.body.insertParagraph(
      "Video provides a powerful way to help you prove your point",
      "Start"
    );
    context.document.body.paragraphs
      .getLast()
      .insertText(
        "To make your document look professionally produced.",
        "Replace"
      );
    context.document.body.paragraphs.getFirst().alignment = "Left";
    context.document.body.paragraphs.getLast().alignment = "Left";
  });
}

async function tryCatch(callback) {
  try {
    await callback();
  } catch (error) {
    console.error(error);
  }
}

Search

$("#setup").click(() => tryCatch(setup)); 
$("#basic-search").click(() => tryCatch(basicSearch));
$("#wildcard-search").click(() => tryCatch(wildcardSearch));

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

    await context.sync();

    for (let i = 0; i < results.items.length; i++) {
      results.items[i].font.highlightColor = "yellow";
    }

    await context.sync();
  });
}

async function wildcardSearch() {
  await Word.run(async (context) => {
    let results = context.document.body.search("$*.[0-9][0-9]", { matchWildcards: true });
    results.load("length");

    await context.sync();

    for (let i = 0; i < results.items.length; i++) {
      results.items[i].font.highlightColor = "red";
      results.items[i].font.color = "white";
    }

    await context.sync();
  });
}

async function setup() {
  await Word.run(async (context) => {
    context.document.body.clear();
    context.document.body.insertParagraph(
      "Video provides a powerful way to help you prove your point.",
      "Start"
    );
    context.document.body.paragraphs
      .getLast()
      .insertText(
        "To make your document look professionally produced.",
        "Replace"
      );

    await context.sync();
  });
}

async function tryCatch(callback) {
  try {
    await callback();
  } catch (error) {
    console.error(error);
  }
}

Get Word Count

$("#setup").click(() => tryCatch(setup)); 
$("#count").click(() => tryCatch(run));

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

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

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

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

      let correlatedResults = {
        searchTerm: distinctText[i],
        hits: results
      };

      allSearchResults.push(correlatedResults);
    }

    await context.sync();

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

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

async function setup() {
  await Word.run(async (context) => {
    context.document.body.clear();
    context.document.body.insertParagraph(
      "Video provides a powerful way to help you prove your point.",
      "Start"
    );
    context.document.body.insertParagraph(
      "To make your document look professionally produced.",
      "End"
    );
  });
}

/** Default helper for invoking an action and handling errors. */
async function tryCatch(callback) {
  try {
    await callback();
  } catch (error) {
    console.error(error);
  }
}

Scroll to a Range

$("#setup").click(() => tryCatch(setup)); 
$("#scroll").click(() => tryCatch(scroll));
$("#scroll-end").click(() => tryCatch(scrollEnd));

async function scroll() {
  await Word.run(async (context) => {
    context.document.body.paragraphs.getLast().select();

    await context.sync();
  });
}

async function scrollEnd() {
  await Word.run(async (context) => {
    context.document.body.paragraphs.getLast().select("End");

    await context.sync();
  });
}

async function setup() {
  await Word.run(async (context) => {
    context.document.body.clear();
    let firstSentence = context.document.body.insertParagraph(
      "Video provides a powerful way to help you prove your point.",
      "Start"
    );
    firstSentence.insertBreak(Word.BreakType.page, "After");
    context.document.body.paragraphs
      .getLast()
      .insertText(
        "To make your document look professionally produced.",
        "Replace"
      );
  });
}

async function tryCatch(callback) {
  try {
    await callback();
  } catch (error) {
    console.error(error);
  }
}

Split a Paragraph into Ranges

$("#setup").click(() => tryCatch(setup)); 
$("#highlight").click(() => tryCatch(highlightWords));

async function highlightWords() {
  await Word.run(async (context) => {
    let paragraph = context.document.body.paragraphs.getFirst();
    let 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);
    }
  });
}

function pause(milliseconds) {
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
}

async function setup() {
  await Word.run(async (context) => {
    context.document.body.clear();
    context.document.body.insertParagraph(
      "Video provides a powerful way to help you prove your point.",
      "Start"
    );
    context.document.body.paragraphs
      .getLast()
      .insertText(
        "To make your document look professionally produced",
        "Replace"
      );
  });
}

async function tryCatch(callback) {
  try {
    await callback();
  } catch (error) {
    console.error(error);
  }
}


© 2022 Better Solutions Limited. All Rights Reserved. © 2022 Better Solutions Limited TopPrevNext