PowerPoint 加载项PowerPoint add-ins

使用 PowerPoint 加载项,可以跨平台(包括 Windows、iOS、Mac 和浏览器)生成极具吸引力的解决方案,从而有效展示用户的演示文稿。You can use PowerPoint add-ins to build engaging solutions for your users' presentations across platforms including Windows, iOS, Office Online, and Mac. 可以创建以下两种类型的 PowerPoint 加载项:You can create two types of PowerPoint add-ins:

  • 使用内容外接程序向演示文稿添加动态 HTML5 内容。有关示例,请参阅可用于将交互关系图从 LucidChart 插入面板的 PowerPoint 的 LucidChart 关系图外接程序。Use content add-ins to add dynamic HTML5 content to your presentations. For example, see the LucidChart Diagrams for PowerPoint add-in, which you can use to inject an interactive diagram from LucidChart into your deck.

  • 使用任务窗格加载项引入参考信息或通过服务将数据插入演示文稿。Use task pane add-ins to bring in reference information or insert data into the presentation via a service. 有关示例,请参阅可用于在演示文稿中添加专业照片的 Pixton 漫画人物加载项。For example, see the Pixton Comic Characters add-in, which you can use to add professional photos to your presentation.

PowerPoint 加载项方案PowerPoint add-in scenarios

本文中的代码示例展示了开发 PowerPoint 加载项涉及的一些基本任务。The code examples in this article demonstrate some basic tasks for developing add-ins for PowerPoint. 请注意以下几点:Please note the following:

  • 这些示例使用 app.showNotification 函数来显示信息,该函数包含在 Visual Studio Office 加载项项目模板中。To display information, these examples use the app.showNotification function, which is included in the Visual Studio Office Add-ins project templates. 如果你没打算使用 Visual Studio 开发加载项,则需要将 showNotification 函数替换为你自己的代码。If you aren't using Visual Studio to develop your add-in, you'll need replace the showNotification function with your own code.

  • 其中一些示例还使用在这些函数的作用域外声明的 Globals 对象:var Globals = {activeViewHandler:0, firstSlideId:0};Several of these examples also use a Globals object that is declared beyond the scope of these functions as: var Globals = {activeViewHandler:0, firstSlideId:0};

  • 若要使用这些示例,您的加载项项目必须引用 Office.js v1.1 库或更高版本To use these examples, your add-in project must reference Office.js v1.1 library or later.

检测演示文稿的活动视图并处理 ActiveViewChanged 事件Detect the presentation's active view and handle the ActiveViewChanged event

若要生成内容外接程序,则需要获取演示文稿的活动视图,并在 ActiveViewChanged 处理程序期间处理 Office.Initialize 事件。If you are building a content add-in, you will need to get the presentation's active view and handle the ActiveViewChanged event, as part of your Office.Initialize handler.

备注

在 PowerPoint 网页版中,Document.ActiveViewChanged 事件永远不会触发,因为幻灯片放映模式被视为新会话。In PowerPoint Online, the Document.ActiveViewChanged event will never fire as Slide Show mode is treated as a new session. 在这种情况下,加载项必须在加载时提取活动视图,如下面的代码示例所述。In this case, the add-in must fetch the active view on load, as shown in the following code sample.

在以下代码示例中:In the following code sample:

  • getActiveFileView 函数将调用 Document.getActiveViewAsync 方法,以返回演示文稿的当前视图是“编辑”(你可在其中编辑幻灯片的任何视图,如普通大纲视图)还是“阅读”(幻灯片放映阅读视图)。The getActiveFileView function calls the Document.getActiveViewAsync method to return whether the presentation's current view is "edit" (any of the views in which you can edit slides, such as Normal or Outline View) or "read" (Slide Show or Reading View).

  • registerActiveViewChanged 函数调用 addHandlerAsync 方法,以注册 Document.ActiveViewChanged 事件的处理程序。The registerActiveViewChanged function calls the addHandlerAsync method to register a handler for the Document.ActiveViewChanged event.

//general Office.initialize function. Fires on load of the add-in.
Office.initialize = function(){

    //Gets whether the current view is edit or read.
    var currentView = getActiveFileView();

    //register for the active view changed handler
    registerActiveViewChanged();

    //render the content based off of the currentView
    //....
}

function getActiveFileView()
{
    Office.context.document.getActiveViewAsync(function (asyncResult) {
        if (asyncResult.status == "failed") {
            app.showNotification("Action failed with error: " + asyncResult.error.message);
        }
        else {
            app.showNotification(asyncResult.value);
        }
    });

}

function registerActiveViewChanged() {
    Globals.activeViewHandler = function (args) {
        app.showNotification(JSON.stringify(args));
    }

    Office.context.document.addHandlerAsync(Office.EventType.ActiveViewChanged, Globals.activeViewHandler,
        function (asyncResult) {
            if (asyncResult.status == "failed") {
                app.showNotification("Action failed with error: " + asyncResult.error.message);
            }
            else {
                app.showNotification(asyncResult.status);
            }
        });
}

在以下代码示例中,getSelectedRange 函数将调用 Document.getSelectedDataAsync 方法已获取 asyncResult.value 返回的 JSON 对象,其中包括一个名为 slides 的数组。In the following code sample, the getSelectedRange function calls the Document.getSelectedDataAsync method to get the JSON object returned by asyncResult.value, which contains an array named slides. slides 数组包含所选范围内的幻灯片(或当前幻灯片,如果未选择多张幻灯片)的 ID、标题和索引。The slides array contains the ids, titles, and indexes of selected range of slides (or of the current slide, if multiple slides are not selected). 此外,它会将所选范围内的第一张幻灯片的 ID 保存为全局变量。It also saves the id of the first slide in the selected range to a global variable.

function getSelectedRange() {
    // Get the id, title, and index of the current slide (or selected slides) and store the first slide id */
    Globals.firstSlideId = 0;

    Office.context.document.getSelectedDataAsync(Office.CoercionType.SlideRange, function (asyncResult) {
        if (asyncResult.status == "failed") {
            app.showNotification("Action failed with error: " + asyncResult.error.message);
        }
        else {
            Globals.firstSlideId = asyncResult.value.slides[0].id;
            app.showNotification(JSON.stringify(asyncResult.value));
        }
    });
}

在以下代码示例中,goToFirstSlide 函数将调用 Document.goToByIdAsync 方法,以导航至由之前显示的 getSelectedRange 函数标识的第一张幻灯片。In the following code sample, the goToFirstSlide function calls the Document.goToByIdAsync method to navigate to the first slide that was identified by the getSelectedRange function shown previously.

function goToFirstSlide() {
    Office.context.document.goToByIdAsync(Globals.firstSlideId, Office.GoToType.Slide, function (asyncResult) {
        if (asyncResult.status == "failed") {
            app.showNotification("Action failed with error: " + asyncResult.error.message);
        }
        else {
            app.showNotification("Navigation successful");
        }
    });
}

在以下代码示例中,goToSlideByIndex 函数将调用 Document.goToByIdAsync 方法,以导航至演示文稿中的下一张幻灯片。In the following code sample, the goToSlideByIndex function calls the Document.goToByIdAsync method to navigate to the next slide in the presentation.

function goToSlideByIndex() {
    var goToFirst = Office.Index.First;
    var goToLast = Office.Index.Last;
    var goToPrevious = Office.Index.Previous;
    var goToNext = Office.Index.Next;

    Office.context.document.goToByIdAsync(goToNext, Office.GoToType.Index, function (asyncResult) {
        if (asyncResult.status == "failed") {
            app.showNotification("Action failed with error: " + asyncResult.error.message);
        }
        else {
            app.showNotification("Navigation successful");
        }
    });
}

获取演示文稿的 URLGet the URL of the presentation

在以下代码实例中,getFileUrl 函数将调用 Document.getFileProperties 方法,以获取演示文稿文件的URL。In the following code sample, the getFileUrl function calls the Document.getFileProperties method to get the URL of the presentation file.

function getFileUrl() {
    //Get the URL of the current file.
    Office.context.document.getFilePropertiesAsync(function (asyncResult) {
        var fileUrl = asyncResult.value.url;
        if (fileUrl == "") {
            app.showNotification("The file hasn't been saved yet. Save the file and try again");
        }
        else {
            app.showNotification(fileUrl);
        }
    });
}

创建演示文稿Create a presentation

加载项可创建新的演示文稿,且与当前运行此加载项的 PowerPoint 实例分开。Your add-in can create a new presentation, separate from the PowerPoint instance in which the add-in is currently running. PowerPoint 命名空间针对此目的提供了 createPresentation 方法。The PowerPoint namespace has the createPresentation method for this purpose. 调用此方法时,新的演示文稿将立即打开并在 PowerPoint 新实例中显示。When this method is called, the new presentation is immediately opened and displayed in a new instance of PowerPoint. 加载项保持打开状态,并随之前的演示文稿一起运行。Your add-in remains open and running with the previous presentation.

PowerPoint.createPresentation();

此外,createPresentation 方法还可创建现有演示文稿的副本。The createPresentation method can also create a copy of an existing presentation. 此方法接受 .pptx 文件的 base64 编码字符串表示形式作为可选参数。The method accepts a base64-encoded string representation of an .pptx file as an optional parameter. 若字符串参数为有效的 .pptx 文件,则生成的演示文稿是该文件的副本。The resulting presentation will be a copy of that file, assuming the string argument is a valid .pptx file. 可以使用 FileReader 类将文件转换为所需的 base64 编码字符串,如以下示例所示。The FileReader class can be used to convert a file into the required base64-encoded string, as demonstrated in the following example.

var myFile = document.getElementById("file");
var reader = new FileReader();

reader.onload = function (event) {
    // strip off the metadata before the base64-encoded string
    var startIndex = reader.result.toString().indexOf("base64,");
    var copyBase64 = reader.result.toString().substr(startIndex + 7);

    PowerPoint.createPresentation(copyBase64);
};

// read in the file as a data URL so we can parse the base64-encoded string
reader.readAsDataURL(myFile.files[0]);

另请参阅See also