使用 PowerPoint 加载项,可以跨平台(包括 Windows、iPad、Mac 和浏览器)生成极具吸引力的解决方案,从而有效展示用户的演示文稿。 可以创建以下两种类型的 PowerPoint 加载项:
使用任务窗格加载项引入参考信息或通过服务将数据插入演示文稿。 有关示例,请参阅可用于在演示文稿中添加专业照片的 Pexels - 免费素材图片加载项。 若要创建自己的任务窗格加载项,可以从 生成第一个 PowerPoint 任务窗格加载项开始。
使用内容外接程序向演示文稿添加动态 HTML5 内容。 例如,请参阅 LucidChart Diagrams for PowerPoint 加载项,它将 LucidChart 中的交互式图表注入到你的幻灯片中。 若要创建自己的内容外接程序,请从 生成第一个 PowerPoint 内容加载项开始。
PowerPoint 加载项方案
本文中的代码示例演示了开发 PowerPoint 加载项时有用的一些基本任务。
添加新幻灯片,然后导航到该幻灯片
在以下代码示例中,函数 addAndNavigateToNewSlide
调用 SlideCollection.add 方法以向演示文稿添加新幻灯片。 然后,函数调用 Presentation.setSelectedSlides 方法以导航到新幻灯片。
async function addAndNavigateToNewSlide() {
// Adds a new slide then navigates to it.
await PowerPoint.run(async (context) => {
const slideCountResult = context.presentation.slides.getCount();
context.presentation.slides.add();
await context.sync();
const newSlide = context.presentation.slides.getItemAt(slideCountResult.value);
newSlide.load("id");
await context.sync();
console.log(`Added slide - ID: ${newSlide.id}`);
// Navigate to the new slide.
context.presentation.setSelectedSlides([newSlide.id]);
await context.sync();
});
}
转到演示文稿中的特定幻灯片
在以下代码示例中,函数 getSelectedSlides
调用 Presentation.getSelectedSlides 方法来获取所选幻灯片,然后记录其 ID。 然后,函数可以处理当前幻灯片 (或所选) 的第一张幻灯片。
async function getSelectedSlides() {
// Gets the ID of the current slide (or selected slides).
await PowerPoint.run(async (context) => {
const selectedSlides = context.presentation.getSelectedSlides();
selectedSlides.load("items/id");
await context.sync();
if (selectedSlides.items.length === 0) {
console.warn("No slides were selected.");
return;
}
console.log("IDs of selected slides:");
selectedSlides.items.forEach(item => {
console.log(item.id);
});
// Navigate to first selected slide.
const currentSlide = selectedSlides.items[0];
console.log(`Navigating to slide with ID ${currentSlide.id} ...`);
context.presentation.setSelectedSlides([currentSlide.id]);
// Perform actions on current slide...
});
}
在演示文稿的幻灯片之间导航
在以下代码示例中 goToSlideByIndex
,函数调用 Presentation.setSelectedSlides
方法以导航到演示文稿中的第一张幻灯片,该幻灯片的索引为 0。 在此示例中,可导航到的最大幻灯片索引为 slideCountResult.value - 1
。
async function goToSlideByIndex() {
await PowerPoint.run(async (context) => {
// Gets the number of slides in the presentation.
const slideCountResult = context.presentation.slides.getCount();
await context.sync();
if (slideCountResult.value === 0) {
console.warn("There are no slides.");
return;
}
const slide = context.presentation.slides.getItemAt(0); // First slide
//const slide = context.presentation.slides.getItemAt(slideCountResult.value - 1); // Last slide
slide.load("id");
await context.sync();
console.log(`Slide ID: ${slide.id}`);
// Navigate to the slide.
context.presentation.setSelectedSlides([slide.id]);
await context.sync();
});
}
获取演示文稿的 URL
在以下代码示例中 getFileUrl
,函数调用 Document.getFileProperties 方法以获取演示文稿文件的 URL。
function getFileUrl() {
// Gets the URL of the current file.
Office.context.document.getFilePropertiesAsync(function (asyncResult) {
const fileUrl = asyncResult.value.url;
if (fileUrl === "") {
console.warn("The file hasn't been saved yet. Save the file and try again.");
} else {
console.log(`File URL: ${fileUrl}`);
}
});
}
创建演示文稿
加载项可创建新的演示文稿,且与当前运行此加载项的 PowerPoint 实例分开。 PowerPoint 命名空间针对此目的提供了 createPresentation
方法。 调用此方法时,新的演示文稿将立即打开并在 PowerPoint 新实例中显示。 加载项保持打开状态,并随之前的演示文稿一起运行。
PowerPoint.createPresentation();
此外,createPresentation
方法还可创建现有演示文稿的副本。 方法接受 .pptx 文件的 Base64 编码字符串表示形式作为可选参数。 若字符串参数为有效的 .pptx 文件,则生成的演示文稿是该文件的副本。
FileReader 类可用于将文件转换为所需的 Base64 编码字符串,如以下示例所示。
const myFile = document.getElementById("file") as HTMLInputElement;
const reader = new FileReader();
reader.onload = function (event) {
// Strip off the metadata before the Base64-encoded string.
const startIndex = reader.result.toString().indexOf("base64,");
const 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]);
若要查看包含 HTML 实现的完整代码示例,请参阅 创建演示文稿。
检测演示文稿的活动视图并处理 ActiveViewChanged 事件
如果要生成内容加载项,则需要获取演示文稿的活动视图,并在 Office.onReady 调用过程中处理 Document.ActiveViewChanged 事件。
注意
在PowerPoint web 版中,该事件永远不会触发,Document.ActiveViewChanged
因为幻灯片放映模式被视为新会话。 在这种情况下,加载项必须在加载时提取活动视图,如下面的代码示例所述。
有关代码示例,请注意以下事项:
- 函数
getActiveFileView
调用 Document.getActiveViewAsync 方法,以返回演示文稿的当前视图是否 (可编辑幻灯片的任何视图(如“普通”、“幻灯片排序器”或“大纲) ”或“读取” (幻灯片放映或阅读视图) ,由 ActiveView 枚举表示)。 - 函数
registerActiveViewChanged
调用 Document.addHandlerAsync 方法来注册事件的处理程序Document.ActiveViewChanged
。 - 为了显示信息,此示例使用
showNotification
函数,该函数包含在 Visual Studio Office 外接程序项目模板中。 如果不使用 Visual Studio 开发加载项,则需要将 函数替换为showNotification
自己的代码。
// General Office.onReady function. Called after the add-in loads and Office JS is initialized.
Office.onReady(() => {
// Get whether the current view is edit or read.
const currentView = getActiveFileView();
// Register the active view changed handler.
registerActiveViewChanged();
// Render the content based off of the current view.
if (currentView === Office.ActiveView.Read) {
// Handle read view.
console.log('Current view is read.');
// You can add any specific logic for the read view here.
} else {
// Handle edit view.
console.log('Current view is edit.');
// You can add any specific logic for the edit view here.
}
});
// Gets the active file view.
function getActiveFileView() {
console.log('Getting active file view...');
Office.context.document.getActiveViewAsync(function (result) {
if (result.status === Office.AsyncResultStatus.Succeeded) {
console.log('Active view:', result.value);
return result.value;
} else {
console.error('Error getting active view:', result.error.message);
showNotification('Error:', result.error.message);
return null;
}
});
}
// Registers the ActiveViewChanged event.
function registerActiveViewChanged() {
console.log('Registering ActiveViewChanged event handler...');
Office.context.document.addHandlerAsync(
Office.EventType.ActiveViewChanged,
activeViewHandler,
function (result) {
if (result.status === Office.AsyncResultStatus.Failed) {
console.error('Failed to register active view changed handler:', result.error.message);
showNotification('Error:', result.error.message);
} else {
console.log('Active view changed handler registered successfully.');
}
});
}
// ActiveViewChanged event handler.
function activeViewHandler(eventArgs) {
console.log('Active view changed:', JSON.stringify(eventArgs));
showNotification('Active view changed', `The active view has changed to: ${eventArgs.activeView}`);
// You can add logic here based on the new active view.
}