Creating Your First Microsoft Word Addin Using JavaScript


Microsoft Word is used by over 1.2 Billion users worldwide. With this huge market to serve, Microsoft is constantly doing research and testing to improve its software and user experience. This is likely why Microsoft introduced custom add-ins which can be made by any developer to improve software features and user experience. To support developers, Microsoft also published a documentation and API reference on how to create add-ins for Office products which you can access from this link.

Microsoft Office add-ins are powerful tools that extend the functionality of Office applications such as Word, Excel, and PowerPoint. Whether it’s streamlining data analysis, enhancing document collaboration, or automating repetitive tasks, these add-ins empower users to customize their Office experience to suit their unique needs, ultimately boosting efficiency and effectiveness in their work.

The addins can be developed using different languages such as C#, VB.Net, C++, and JavaScript with HTML and CSS. In this article, we are going to focus on how you can create your first Word Addin using JavaScript.

Prerequisites

Before we get started, here are some prerequisites you should have to better understand this tutorial:

  • Basic Understanding of HTML, CSS, and JavaScript: Familiarity with the fundamental concepts of HTML for structuring web pages, CSS for styling, and JavaScript for adding interactivity is essential. This tutorial assumes a basic knowledge of these languages.
  • Node Js: You should have Node Js installed. You can download it from the official website.
  • Microsoft Word Product: You should have access to either an online or offline Microsoft Word Product. You can visit the official Microsoft Word page for more info.

Note: As you test the source files, ensure that you load them within a suitable environment such that all the files are loaded. We recommend that you use vscode to load the files.

Demo

Here is what we are going to create. We are going to create a simple add-in to select images in a Word document and change their size. We shall also add an option to delete the images.

Step 1: Setting Up Your Development Environment

First things first, let’s set up your development environment. You’ll need Visual Studio, Node.js, and the Yeoman generator for Office Add-ins. Here’s how to get started:

  1. Install Visual Studio if you haven’t already.
  2. Install Node.js from the official website.
  3. Open a command prompt and install the Yeoman generator by running:
npm install -g yo generator-office

Step 2: Creating Your Project

Now that your environment is set up, let’s create a project folder and add it to your vscode workspace as shown below:

 creating word addin using JavaScript

Right-click, and select “Open in integrated terminal” as shown below.

 creating word addin using JavaScript

Now run the command below in the terminal:

yo office

Using the Wizard, select your project type as “Office Addin Taskpane Project”

 creating word addin using JavaScript

Select the scripting language as JavaScript.

 creating word addin using JavaScript

Now type the name of your Word Addin:

 creating word addin using JavaScript

Finally, select the “word” option to target the word client application.

 creating word addin using JavaScript

After your project is setup, you can right-click and open it in the integrated terminal.

 creating word addin using JavaScript

In the integrated terminal, you can run the following command to test your plugin.

npm start

Step 3: Setup the Custom Frontend

For our Front end, we are going to use HTML and CSS. To start, let’s modify the HTML of our task pane add-in which is located in the “taskpane.html” file as shown below:

To modify our HTML, let’s modify the title, header and main tag to include our custom HTML as shown below. For this example, we are going to add some input boxes and buttons in the main tag. The input boxes will store the values of the width and height while the buttons will be used to execute the functions of the add-in via JavaScript.

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>My Word Addin</title>

    <!-- Office JavaScript API -->
    <script type="text/javascript" src="https://appsforoffice.microsoft.com/lib/1.1/hosted/office.js"></script>

    <!-- For more information on Fluent UI, visit https://developer.microsoft.com/fluentui#/. -->
    <link rel="stylesheet" href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-core/11.0.0/css/fabric.min.css"/>

    <!-- Template styles -->
    <link href="taskpane.css" rel="stylesheet" type="text/css" />     
</head>

<body class="ms-font-m ms-welcome ms-Fabric">
    <header class="ms-welcome__header ms-bgColor-neutralLighter">
        <span class="ms-font-su">My Word Addin</span>
    </header>
    <section id="sideload-msg" class="ms-welcome__main">
        <h2 class="ms-font-xl">Please <a target="_blank" href="https://learn.microsoft.com/office/dev/add-ins/testing/test-debug-office-add-ins#sideload-an-office-add-in-for-testing">sideload</a> your add-in to see app body.</h2>
    </section>
    <main id="app-body" class="ms-welcome__main" style="display: none;">
            <div class="app-view">
                <span class="app-input">
                   <span> <label>Width</label><input id="app-width" type="number" value="200"></input></span>
                   <span> <label>Height</label><input id="app-height" type="number" value="200"></input></span>
                </span>
                <span class="app-button" id="app-change-size">CHANGE SIZE</span>
                <span class="app-button" id="app-delete-all">DELETE ALL</span>
            </div>
            <a href="https://www.25scripts.com" target="_blank"> Visit 25scripts.com for more</a>
    </main>
</body>

</html>

In the “taskpane.css” file, let’s add some custom CSS to style our HTML code.

/*CUSTOM CSS HERE*/
.app-view{
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    gap:10px;
}
.app-button{
    padding: 10px;
    background: #0078d7;
    text-align: center;
    color:#fff;
    cursor: pointer;
}
/*when the mouse is over the button*/
.app-button:hover{
    background: #42a2f1;
    border:3px solid #2e395c;
}
body{
    background:#eee;
}
a{
    text-align: center;
    margin-top: 50px;
    text-decoration: none;
}
.app-input{
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    gap:10px;
}
.app-input>span{
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    gap:10px;
}
.app-input>span>label{
    color:rgb(43, 128, 226);
    font-size: 1em;
    font-weight: 500;
}

If you test the add-in at this point with the CSS loaded, the task pane add-in should look like what is shown below.

 creating word addin using JavaScript

Step 4: Adding Javascript Function

Finally, let’s add the javascript functionality in the “taskpane.js” file as shown below. In this code, we add the changeSize and deletePictures to be called when the buttons are clicked.

/*function to load our app display when the addin is ready*/
Office.onReady((info) => {
  
  if (info.host === Office.HostType.Word) {
   document.getElementById("sideload-msg").style.display = "none";
   document.getElementById("app-body").style.display = "flex";
   

   document.getElementById("app-change-size").onclick=function(){
 
   changeSize();
  };
   document.getElementById("app-delete-all").onclick=function(){deletePictures()};

   
  }
});
/*function to change size*/
export async function changeSize() {
  return Word.run(async (context) => {
    var body=context.document.body;
   
    var pictures=body.inlinePictures;
    pictures.load();
    await context.sync();
    var width=document.getElementById("app-width").value;
    var height=document.getElementById("app-height").value;
    
    for(let i=0;i<pictures.items.length;i++){
     var picture=pictures.items[i];
     picture.lockAspectRatio=false;
     picture.width=parseFloat(width);
     picture.height=parseFloat(height);
    }
 

  });
}

/**function delete the images */
export async function  deletePictures(){
  return Word.run(async (context) => {
    var body=context.document.body;
    var pictures=body.inlinePictures;
    pictures.load()
    await context.sync();
    for(let i=0;i<pictures.items.length;i++){
     var picture=pictures.items[i];
     picture.delete();
    }
   });
}

Change size function:

This function, changeSize, is responsible for resizing inline pictures in the Word document. It uses the Word JavaScript API (Word.run) to execute a series of operations on the document. First, it loads all the inline pictures (pictures.load()), then waits for the context to synchronize (await context.sync()). Next, it retrieves the desired width and height values from input fields in the HTML (app-width and app-height). Finally, it iterates through each inline picture item, sets lockAspectRatio to false to allow independent resizing of width and height, and then sets the width and height based on the user input.

deletePictures Function:

This deletePictures function is responsible for removing all inline pictures from the Word document. Similar to the changeSize function, it utilizes the Word JavaScript API to manipulate the document. It loads all the inline pictures, waits for synchronization, and then iterates through each picture item, deleting it from the document.

To summarize, this code demonstrate how to interact with the Word document using the Word JavaScript API within the context of an Office add-in. They showcase common tasks such as manipulating inline pictures and responding to user interactions, providing a solid foundation for building more complex functionality in your Word add-in.

Step 5: Deploying Your Add-In

Once you’re satisfied with your add-in, it’s time to deploy it for others to use. You can deploy your add-in to the Office Store or distribute it internally within your organization. Follow the instructions provided by Microsoft to package and submit your add-in to the Office Store.

Conclusion

Congratulations! You’ve successfully built and deployed your first Microsoft Word add-in. Keep exploring and learning different features to take your add-ins to the next level.

Leave a Reply

Your email address will not be published. Required fields are marked *