Skip to main content
Contact our team to know more about our services
select webform
By submitting, you acknowledge that you've read and agree to our privacy policies, and Opcito may use the information provided for business purposes.
Become a part of our team
select webform
One file only.
1.5 GB limit.
Allowed types: gif, jpg, jpeg, png, bmp, eps, tif, pict, psd, txt, rtf, html, odf, pdf, doc, docx, ppt, pptx, xls, xlsx, xml, avi, mov, mp3, mp4, ogg, wav, bz2, dmg, gz, jar, rar, sit, svg, tar, zip.
By submitting, you acknowledge that you've read and agree to our privacy policies, and Opcito may use the information provided for business purposes.
Adding Content Controls into Word document using Office JS
13 Mar 2021

Adding Content Controls into Word document using Office JS

Content controls are the defined regions within a document that are utilized for containing specific content. Multiple day-to-day applications use content controls. Consider an online form with a drop-down list containing particular options to choose from for the user. Here, content controls can give instructional text to users. Not only this, but you can also set the rules in a certain way that would instantly disappear when the users start entering their text. There are individual content controls comprised of contents like images, tables, or paragraphs of the formatted text. But why use content controls? Here are some of the significant benefits of content controls:

  • Content controls can be protected, so the user can read but not edit them.
  • Content controls are good at exposing the events you plan to handle to carry out the custom processing.
  • You can easily do document auto-generation and data binding with content controls.

With content controls, you can easily design documents and templates with features like a UI, such as a form with a controlled input. Some other notable features include data mapping and restricting users from editing your document's protected areas or the template. If you talk specifically about the UI provided by content controls, it can be optimized for both the user input and the print. So, whenever you add a content control to a document, then the control can be identified by a border, a title tab, and temporary text. It provides straightforward prompt or detailed instructions to you. Let's consider an example to understand this better:

 

Designing with content control in React

 

You should be aware that, while printing the document, the border and the title tab of the control will not appear on the paper or document.

How to add content controls?

You can add content control by using office.js API. Here is how you can do it:

await Word.run(async context => {  
        const range = context.document.getSelection();  
        range.clear();  
        const wordContentControl = range.insertContentControl();  
        wordContentControl.tag = "Name";  
        wordContentControl.title = "Naresh Patil";  
        wordContentControl.insertText(text.toString(), 'Replace');  
        wordContentControl.cannotEdit = false;  
        wordContentControl.appearance = 'BoundingBox';  
        wordContentControl.font.size = fontsize;  
        wordContentControl.font.highlightColor = highlightColor;  
        wordContentControl.font.color = 'red';  
        await context.sync()  
    }).catch((error) => {  
        console.log(error);  
    });  

How to nest content control within a content control?

Place a cursor inside a content control and use the same code given above to nest content control within a content control. Now, as convenient as it may look, most of the time, your cursor remains inside the content control, and without recognizing it, you may perform the add action, due to which your content control may get nested. Based on the cursor position, the output will vary, and it can be either nested content control if it is inside or added after the previous content control if it is outside.

The output will look like this if the cursor pointer is within the content control:

await Word.run(async (context) => {  
const wordContentControl = context.document.getSelection();  
wordContentControl.parentContentControl  
      context.load(wordContentControl.parentContentControl, 'id,title,tag,text')  
context.sync().then(() => {  
       // inside content control  
const title = wordContentControl.parentContentControl.title  
}).catch(() => {  
       // Outside content control  
});  
})  

Here is how you can add content control just after another content control:

await Word.run(async (context) => {  
        OfficeExtension.config.extendedErrorLogging = true;  
        let range = context.document.getSelection();  
        range.clear();  
// parentClauseTitle is a title of a content control in which cursor is placed  
        let contentControls = context.document.contentControls.getByTitle(parentClauseTitle);  
        context.load(contentControls, 'id,title,tag,text');  
        await context.sync().then(() => {  
            if (contentControls.items.length != 0) {  
                range = contentControls.items[0].getRange("After");  
            }  
        const wordContentControl = range.insertContentControl();  
      context.load(wordContentControl, 'id,text,font');  
wordContentControl.tag = 'fullName’  
       wordContentControl.title = 'Naresh Patil';  
wordContentControl.insertBreak('SectionContinuous', "End");  
wordContentControl.insertText(text, 'Replace');  
wordContentControl.cannotDelete = true;  
wordContentControl.cannotEdit = true;  
wordContentControl.appearance = 'BoundingBox';  
        });  
    }).catch(error => {  
        console.log(error);  
    });                                     

These are some simple steps to add and nest content controls. Compared to the legacy form fields, the content controls offer different opportunities and advantages to document the designers. The content controls in your documents can function both with and without document protection. Unlike form-filed drop-down lists, where the list is limited to 25 entries, you can add multiple entries without worrying about limitations in content control.

That’s all about the content control and the process of adding it to the document. Feel free to try content controls with the above procedure and share your experience or queries in the comments section. Till then, happy coding!

Subscribe to our feed

select webform