Creating Word ADD In Using Javascript(Part 4)
Insert image, html and table at cursor position.
Continuing our tutorial series on creating a word ADD In using Javascript, here is the final tutorial on creating word add-in using Javascript. In this tutorial, we learn how we can insert images, tables, and HTML content from our add-in to the word document.
Insert Image
Office Javascript API provides method insert Inline Picture into a word document using our Add-in. This method accepts two arguments: base64Encoded image and location to insert an image.
// Let us define a base64Encoded Image
const base64EncodeImage = "image in base 64 format";// Find Current Selection in the document
const currentSelection = context.document.getSelection();// Create an object to create image and insert on current selection
const image = currentSelection.insertInlinePictureFromBase64(base64EncodedImage, "After");
Insert HTML Content
Office Javascript API also allows inserting some HTML tags into word document through add-ins such as headers, paragraphs, anchors, and lists. Not only it allows us to add HTML tags, but it also styles it.
//Define html content as below
const htmlContent = '<div><h1 style ="font-family:verdena; color:red;">HTML Header</h1><p style="color:blue;">This is html paragraph written in word</p><a href="#">Anchor Tag</a><ul><li>List item 1</li><li>list item 2</li><li></li></ul></div>';// Find current selection in the document
const currentSelection = context.document.getSelection();// Create html object and insert into current selection
const htmlObj = currentSelection.insertHtml(htmlContent, Word.InsertLocation.after);
Insert Table.
Office Javascript API has introduced this feature in its latest version (i.e., Word API 1.3). The “insertTable” method accepts four parameters:
- The number of rows in the data.
- The number of columns in the data.
- Insert location.
- Data to show in the table. ( This must be a two-dimensional array of string).Number of rows in the data.
// Consider following data to be shown in table
const tableData = [
["Id", "Full Name", "Address"],
["1", "Bob Marley", "California"],
["2", "John Smith", "New York"]
];// Find current selection in the document
const currentSelection = context.document.getSelection();// Create table object and insert on current selection
const table = currentSelection.insertTable(tableData.length, tableData[0].length, Word.InsertLocation.after, tableHeader);
You can also add rows to the existing table as below:
//Add table datatable.addRows(Word.InsertLocation.end, lengthOfRowAdded, addedRowValues);
This tutorial is just an example of how you can start creating your word add-in using Javascript. For more, you can refer to the official documentation here.
You can view the complete code of the overall tutorial here.
Keep Reading. Thank you.