Search code examples
javascriptms-wordoffice-jsadd-inoffice-addins

Create content controls using MS Word Add-In API while inserting text


I am inserting plain text paragraphs into my Word document using the Add-In, but I would like to place content controls on certain words of this paragraph while inserting this paragraph. Is there any way we can do that or do the content controls work only after the text is inserted?


Solution

  • Yes, it's possible, as demonstrated by the following code snippet, written in Script Lab by modifying a sample provided by that tool.

    The trick is to work with (at least) two ranges, one for the text the other for the content control(s), as demonstrated by the code snippet, below, and illustrated in the screen shot at the end.

    Explanation

    The starting point is a range corresponding to the target area (the example assumes the entire document). This is then "copied" to a new range object for the text to be inserted (the example assumes it should come at the end of existing content).

    The new text content, up to the point where a content control is required, is inserted in a new paragraph ("on a new line") - the \n at the start of the string.

    Then a new range is instantiated at the end of the text range for the content control. This is inserted, formatted and text assigned to it.

    The text target range is then set to after the content control range, and additional text "appended".

    Code

    await Word.run(async (context) => {
        let rngDoc = context.document.body.getRange("Content");
        let rngTarget = rngDoc.getRange("End");
        rngDoc.load("text"); 
    
        await context.sync();
    
        console.log(rngDoc.text);
    
        rngTarget.insertText("\nStart: ", "Start");
        let rngCC = rngTarget.getRange("End");
        let cc = rngCC.insertContentControl();
        cc.appearance = Word.ContentControlAppearance.boundingBox;
        cc.insertText("In content control", "Replace");
    
        rngTarget = rngCC.getRange("After");
        rngTarget.insertText(" End.", "After");
    
        await context.sync();
    
        console.log("Content controls inserted: " );
    
      });
    

    Result

    https://i.sstatic.net/gQb5Q.png