Complete the following steps to create a PowerPoint add-in project using Visual Studio.
Choose Create a new project.
Using the search box, enter add-in. Choose PowerPoint Web Add-in, then select Next.
Name the project HelloWorld, and select Create.
In the Create Office Add-in dialog window, choose Add new functionalities to PowerPoint, and then choose Finish to create the project.
Visual Studio creates a solution and its two projects appear in Solution Explorer. The Home.html file opens in Visual Studio.
The following NuGet packages must be installed. Install them on the HelloWorldWeb project using the NuGet Package Manager in Visual Studio. See Visual Studio help for instructions. The second of these may be installed automatically when you install the first.
Microsoft.AspNet.WebApi.WebHost
Microsoft.AspNet.WebApi.Core
هام
When you're using the NuGet Package Manager to install these packages, do not install the recommended update to jQuery. The jQuery version installed with your Visual Studio solution matches the jQuery call within the solution files.
Use the NuGet Package Manager to update the Newtonsoft.Json package to version 13.0.3 or later. Then delete the app.config file if it was added to the HelloWorld project.
Explore the Visual Studio solution
When you've completed the wizard, Visual Studio creates a solution that contains two projects.
Project
Description
Add-in project
Contains only an XML-formatted add-in only manifest file, which contains all the settings that describe your add-in. These settings help the Office application determine when your add-in should be activated and where the add-in should appear. Visual Studio generates the contents of this file for you so that you can run the project and use your add-in immediately. Change these settings any time by modifying the XML file.
Web application project
Contains the content pages of your add-in, including all the files and file references that you need to develop Office-aware HTML and JavaScript pages. While you develop your add-in, Visual Studio hosts the web application on your local IIS server. When you're ready to publish the add-in, you'll need to deploy this web application project to a web server.
Update code
Edit the add-in code as follows to create the framework that you'll use to implement add-in functionality in subsequent steps of this tutorial.
Home.html specifies the HTML that will be rendered in the add-in's task pane. In Home.html, find the div with id="content-main", replace that entire div with the following markup, and save the file.
HTML
<!-- TODO2: Create the content-header div. --><divid="content-main"><divclass="padding"><!-- TODO1: Create the insert-image button. --><!-- TODO3: Create the insert-text button. --><!-- TODO4: Create the get-slide-metadata button. --><!-- TODO5: Create the add-slides and go-to-slide buttons. --></div></div>
Open the file Home.js in the root of the web application project. This file specifies the script for the add-in. Replace the entire contents with the following code and save the file.
JavaScript
(function () {
"use strict";
let messageBanner;
Office.onReady(function () {
$(document).ready(function () {
// Initialize the FabricUI notification mechanism and hide it.const element = document.querySelector('.MessageBanner');
messageBanner = new components.MessageBanner(element);
messageBanner.hideBanner();
// TODO1: Assign event handler for insert-image button.// TODO4: Assign event handler for insert-text button.// TODO6: Assign event handler for get-slide-metadata button.// TODO8: Assign event handlers for add-slides and the four navigation buttons.
});
});
// TODO2: Define the insertImage function.// TODO3: Define the insertImageFromBase64String function.// TODO5: Define the insertText function.// TODO7: Define the getSlideMetadata function.// TODO9: Define the addSlides and navigation functions.// Helper function for displaying notifications.functionshowNotification(header, content) {
$("#notification-header").text(header);
$("#notification-body").text(content);
messageBanner.showBanner();
messageBanner.toggleExpansion();
}
})();
Insert an image
Complete the following steps to add code that retrieves the Bing photo of the day and inserts that image into a slide.
Using Solution Explorer, add a new folder named Controllers to the HelloWorldWeb project.
Right-click (or select and hold) the Controllers folder and select Add > New Scaffolded Item....
In the Add Scaffold dialog window, select Web API 2 Controller - Empty and choose the Add button.
In the Add Controller dialog window, enter PhotoController as the controller name and choose the Add button. Visual Studio creates and opens the PhotoController.cs file.
هام
The scaffolding process doesn't complete properly on some versions of Visual Studio after version 16.10.3. If you have the Global.asax and ./App_Start/WebApiConfig.cs files, then skip to step 6.
If you're missing scaffolding files from the HelloWorldWeb project, add them as follows.
Using Solution Explorer, add a new folder named App_Start to the HelloWorldWeb project.
Right-click (or select and hold) the App_Start folder and select Add > Class....
In the Add New Item dialog, name the file WebApiConfig.cs then choose the Add button.
Replace the entire contents of the WebApiConfig.cs file with the following code.
cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
namespaceHelloWorldWeb.App_Start
{
publicstaticclassWebApiConfig
{
publicstaticvoidRegister(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
In the Solution Explorer, right-click (or select and hold) the HelloWorldWeb project and select Add > New Item....
In the Add New Item dialog, search for "global", select Global Application Class, then choose the Add button. By default, the file is named Global.asax.
Replace the entire contents of the Global.asax.cs file with the following code.
cs
using HelloWorldWeb.App_Start;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Security;
using System.Web.SessionState;
namespaceHelloWorldWeb
{
publicclassWebApiApplication : System.Web.HttpApplication
{
protectedvoidApplication_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
}
In the Solution Explorer, right-click (or select and hold) the Global.asax file and choose View Markup.
Replace the entire contents of the Global.asax file with the following code.
Replace the entire contents of the PhotoController.cs file with the following code that calls the Bing service to retrieve the photo of the day as a Base64-encoded string. When you use the Office JavaScript API to insert an image into a document, the image data must be specified as a Base64-encoded string.
C#
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Http;
using System.Xml;
namespaceHelloWorldWeb.Controllers
{
publicclassPhotoController : ApiController
{
publicstringGet()
{
string url = "http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1";
// Create the request.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
// Process the result.
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
string result = reader.ReadToEnd();
// Parse the XML response and get the URL.
XmlDocument doc = new XmlDocument();
doc.LoadXml(result);
string photoURL = "http://bing.com" + doc.SelectSingleNode("/images/image/url").InnerText;
// Fetch the photo and return it as a Base64-encoded string.return getPhotoFromURL(photoURL);
}
}
privatestringgetPhotoFromURL(string imageURL)
{
var webClient = new WebClient();
byte[] imageBytes = webClient.DownloadData(imageURL);
return Convert.ToBase64String(imageBytes);
}
}
}
In the Home.html file, replace TODO1 with the following markup. This markup defines the Insert Image button that will appear within the add-in's task pane.
HTML
<buttonclass="Button Button--primary"id="insert-image"><spanclass="Button-icon"><iclass="ms-Icon ms-Icon--plus"></i></span><spanclass="Button-label">Insert Image</span><spanclass="Button-description">Gets the photo of the day that shows on the Bing home page and adds it to the slide.</span></button>
In the Home.js file, replace TODO1 with the following code to assign the event handler for the Insert Image button.
JavaScript
$('#insert-image').on("click", insertImage);
In the Home.js file, replace TODO2 with the following code to define the insertImage function. This function fetches the image from the Bing web service and then calls the insertImageFromBase64String function to insert that image into the document.
JavaScript
functioninsertImage() {
// Get image from web service (as a Base64-encoded string).
$.ajax({
url: "/api/photo/",
dataType: "text",
success: function (result) {
insertImageFromBase64String(result);
}, error: function (xhr, status, error) {
showNotification("Error", "Oops, something went wrong.");
}
});
}
In the Home.js file, replace TODO3 with the following code to define the insertImageFromBase64String function. This function uses the Office JavaScript API to insert the image into the document. Note:
The coercionType option that's specified as the second parameter of the setSelectedDataAsync request indicates the type of data being inserted.
The asyncResult object encapsulates the result of the setSelectedDataAsync request, including status and error information if the request failed.
JavaScript
functioninsertImageFromBase64String(image) {
// Call Office.js to insert the image into the document.
Office.context.document.setSelectedDataAsync(image, {
coercionType: Office.CoercionType.Image
},
function (asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
showNotification("Error", asyncResult.error.message);
}
});
}
Test the add-in
Using Visual Studio, test the newly created PowerPoint add-in by pressing F5 or choosing the Start button to launch PowerPoint with the Show Taskpane add-in button displayed on the ribbon. The add-in will be hosted locally on IIS.
If the add-in task pane isn't already open in PowerPoint, select the Show Taskpane button on the ribbon to open it.
In the task pane, choose the Insert Image button to add the Bing photo of the day to the current slide.
ملاحظة
If you get an error "Could not find file [...]\bin\roslyn\csc.exe", then do the following:
Open the .\Web.config file.
Find the <compiler> node for the .cs extension, then remove the type attribute and its value.
Save the file.
In Visual Studio, stop the add-in by pressing Shift+F5 or choosing the Stop button. PowerPoint will automatically close when the add-in is stopped.
Customize user interface (UI) elements
Complete the following steps to add markup that customizes the task pane UI.
In the Home.html file, replace TODO2 with the following markup to add a header section and title to the task pane. Note:
The styles that begin with ms- are defined by Fabric Core in Office Add-ins, a JavaScript front-end framework for building user experiences for Office. The Home.html file includes a reference to the Fabric Core stylesheet.
In the Home.html file, find the div with class="footer" and delete that entire div to remove the footer section from the task pane.
Test the add-in
Using Visual Studio, test the PowerPoint add-in by pressing F5 or choosing the Start button to launch PowerPoint with the Show Taskpane add-in button displayed on the ribbon. The add-in will be hosted locally on IIS.
If the add-in task pane isn't already open in PowerPoint, select the Show Taskpane button on the ribbon to open it.
Notice that the task pane now contains a header section and title, and no longer contains a footer section.
In Visual Studio, stop the add-in by pressing Shift+F5 or choosing the Stop button. PowerPoint will automatically close when the add-in is stopped.
Insert text
Complete the following steps to add code that inserts text into the title slide which contains the Bing photo of the day.
In the Home.html file, replace TODO3 with the following markup. This markup defines the Insert Text button that will appear within the add-in's task pane.
HTML
<br /><br /><buttonclass="Button Button--primary"id="insert-text"><spanclass="Button-icon"><iclass="ms-Icon ms-Icon--plus"></i></span><spanclass="Button-label">Insert Text</span><spanclass="Button-description">Inserts text into the slide.</span></button>
In the Home.js file, replace TODO4 with the following code to assign the event handler for the Insert Text button.
JavaScript
$('#insert-text').on("click", insertText);
In the Home.js file, replace TODO5 with the following code to define the insertText function. This function inserts text into the current slide.
JavaScript
functioninsertText() {
Office.context.document.setSelectedDataAsync('Hello World!',
function (asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
showNotification("Error", asyncResult.error.message);
}
});
}
Test the add-in
Using Visual Studio, test the add-in by pressing F5 or choosing the Start button to launch PowerPoint with the Show Taskpane add-in button displayed on the ribbon. The add-in will be hosted locally on IIS.
If the add-in task pane isn't already open in PowerPoint, select the Show Taskpane button on the ribbon to open it.
In the task pane, choose the Insert Image button to add the Bing photo of the day to the current slide and choose a design for the slide that contains a text box for the title.
Put your cursor in the text box on the title slide and then in the task pane, choose the Insert Text button to add text to the slide.
In Visual Studio, stop the add-in by pressing Shift+F5 or choosing the Stop button. PowerPoint will automatically close when the add-in is stopped.
Get slide metadata
Complete the following steps to add code that retrieves metadata for the selected slide.
In the Home.html file, replace TODO4 with the following markup. This markup defines the Get Slide Metadata button that will appear within the add-in's task pane.
HTML
<br /><br /><buttonclass="Button Button--primary"id="get-slide-metadata"><spanclass="Button-icon"><iclass="ms-Icon ms-Icon--plus"></i></span><spanclass="Button-label">Get Slide Metadata</span><spanclass="Button-description">Gets metadata for the selected slides.</span></button>
In the Home.js file, replace TODO6 with the following code to assign the event handler for the Get Slide Metadata button.
In the Home.js file, replace TODO7 with the following code to define the getSlideMetadata function. This function retrieves metadata for the selected slides and writes it to a popup dialog window within the add-in task pane.
JavaScript
functiongetSlideMetadata() {
Office.context.document.getSelectedDataAsync(Office.CoercionType.SlideRange,
function (asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
showNotification("Error", asyncResult.error.message);
} else {
showNotification("Metadata for selected slides:", JSON.stringify(asyncResult.value), null, 2);
}
}
);
}
Test the add-in
Using Visual Studio, test the add-in by pressing F5 or choosing the Start button to launch PowerPoint with the Show Taskpane add-in button displayed on the ribbon. The add-in will be hosted locally on IIS.
If the add-in task pane isn't already open in PowerPoint, select the Show Taskpane button on the ribbon to open it.
In the task pane, choose the Get Slide Metadata button to get the metadata for the selected slide. The slide metadata is written to the popup dialog window at the bottom of the task pane. In this case, the slides array within the JSON metadata contains one object that specifies the id, title, and index of the selected slide. If multiple slides had been selected when you retrieved slide metadata, the slides array within the JSON metadata would contain one object for each selected slide.
In Visual Studio, stop the add-in by pressing Shift+F5 or choosing the Stop button. PowerPoint will automatically close when the add-in is stopped.
Navigate between slides
Complete the following steps to add code that navigates between the slides of a document.
In the Home.html file, replace TODO5 with the following markup. This markup defines the four navigation buttons that will appear within the add-in's task pane.
HTML
<br /><br /><buttonclass="Button Button--primary"id="add-slides"><spanclass="Button-icon"><iclass="ms-Icon ms-Icon--plus"></i></span><spanclass="Button-label">Add Slides</span><spanclass="Button-description">Adds 2 slides.</span></button><br /><br /><buttonclass="Button Button--primary"id="go-to-first-slide"><spanclass="Button-icon"><iclass="ms-Icon ms-Icon--plus"></i></span><spanclass="Button-label">Go to First Slide</span><spanclass="Button-description">Go to the first slide.</span></button><br /><br /><buttonclass="Button Button--primary"id="go-to-next-slide"><spanclass="Button-icon"><iclass="ms-Icon ms-Icon--plus"></i></span><spanclass="Button-label">Go to Next Slide</span><spanclass="Button-description">Go to the next slide.</span></button><br /><br /><buttonclass="Button Button--primary"id="go-to-previous-slide"><spanclass="Button-icon"><iclass="ms-Icon ms-Icon--plus"></i></span><spanclass="Button-label">Go to Previous Slide</span><spanclass="Button-description">Go to the previous slide.</span></button><br /><br /><buttonclass="Button Button--primary"id="go-to-last-slide"><spanclass="Button-icon"><iclass="ms-Icon ms-Icon--plus"></i></span><spanclass="Button-label">Go to Last Slide</span><spanclass="Button-description">Go to the last slide.</span></button>
In the Home.js file, replace TODO8 with the following code to assign the event handlers for the Add Slides and four navigation buttons.
In the Home.js file, replace TODO9 with the following code to define the addSlides and navigation functions. Each of these functions uses the goToByIdAsync method to select a slide based upon its position in the document (first, last, previous, and next).
Using Visual Studio, test the add-in by pressing F5 or choosing the Start button to launch PowerPoint with the Show Taskpane add-in button displayed on the ribbon. The add-in will be hosted locally on IIS.
If the add-in task pane isn't already open in PowerPoint, select the Show Taskpane button on the ribbon to open it.
In the task pane, choose the Add Slides button. Two new slides are added to the document and the last slide in the document is selected and displayed.
In the task pane, choose the Go to First Slide button. The first slide in the document is selected and displayed.
In the task pane, choose the Go to Next Slide button. The next slide in the document is selected and displayed.
In the task pane, choose the Go to Previous Slide button. The previous slide in the document is selected and displayed.
In the task pane, choose the Go to Last Slide button. The last slide in the document is selected and displayed.
In Visual Studio, stop the add-in by pressing Shift+F5 or choosing the Stop button. PowerPoint will automatically close when the add-in is stopped.
In this tutorial, you created a PowerPoint add-in that inserts an image, inserts text, gets slide metadata, and navigates between slides. To learn more about building PowerPoint add-ins, continue to the following articles.