能否使用PowerPoint JS API获取及操作图片的Alt Text?
PowerPoint 图片 Alt Text 操作API说明
目前官方公开的 Office JavaScript API 完全支持对 PowerPoint 中图片的 Alt Text 执行 CRUD 操作,具体使用规则及示例如下:
- 核心可读写属性:PowerPoint 中所有图片对应的Shape实例都提供
altTextTitle和altTextDescription两个属性,分别对应Alt Text的标题和描述内容,直接操作这两个属性即可完成对应需求。
1. 读取图片 Alt Text 示例
await PowerPoint.run(async (context) => { // 获取当前选中的所有形状 const selectedShapes = context.presentation.getSelectedShapes(); // 加载需要用到的属性 selectedShapes.load("items/type, items/altTextTitle, items/altTextDescription"); await context.sync(); // 筛选出图片类型的形状 const targetImage = selectedShapes.items.find(shape => shape.type === PowerPoint.ShapeType.image); if (targetImage) { const altTitle = targetImage.altTextTitle; const altDescription = targetImage.altTextDescription; // 此处可对读取到的Alt Text内容做业务处理 } });
2. 新增/修改图片 Alt Text 示例
await PowerPoint.run(async (context) => { const selectedShapes = context.presentation.getSelectedShapes(); selectedShapes.load("items/type"); await context.sync(); const targetImage = selectedShapes.items.find(shape => shape.type === PowerPoint.ShapeType.image); if (targetImage) { // 直接赋值即可完成新增或修改操作 targetImage.altTextTitle = "自定义Alt标题"; targetImage.altTextDescription = "自定义Alt描述内容,用于无障碍阅读识别"; await context.sync(); } });
3. 删除图片 Alt Text 示例
await PowerPoint.run(async (context) => { const selectedShapes = context.presentation.getSelectedShapes(); selectedShapes.load("items/type"); await context.sync(); const targetImage = selectedShapes.items.find(shape => shape.type === PowerPoint.ShapeType.image); if (targetImage) { // 赋值为空字符串即可删除原有Alt Text targetImage.altTextTitle = ""; targetImage.altTextDescription = ""; await context.sync(); } });
额外说明:如果你是通过setSelectedDataAsync方法插入base64格式的图片,可在插入操作完成后立即获取刚生成的图片Shape实例,再为其设置Alt Text属性,即可实现插入图片时附带Alt Text的需求。
内容的提问来源于stack exchange,提问作者bones.felipe
相关产品推荐
相关产品推荐

