Adding Content Controls into Word document using Office JS

Opcito Technologies
2 min readMar 15, 2021
content controls with OfficeJS

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 the 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 a straightforward prompt or detailed instructions to you. Let’s consider an example to understand this better:

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…read more.

--

--

Opcito Technologies

Product engineering experts specializing in DevOps, Containers, Cloud, Automation, Blockchain, Test Engineering, & Open Source Tech