提取并再利用 PowerPoint 演示文稿中的各种元素,是跨平台内容共享演示文稿内容的重要方式之一。通过将幻灯片中的形状(包括文本框、图形、图片、表格等)转换为独立的图像文件,用户可以将这些形状无缝嵌入到文档、网页或设计项目中,同时保留其原有的格式和视觉效果。而借助 Python,用户可以灵活高效地实现这一过程。本文将介绍如何使用 Spire.Presentation for Python,通过 Python 代码将 PowerPoint 演示文稿中的形状保存为图像文件。
安装 Spire.Presentation for Python
本教程需要用到 Spire.Presentation for Python 和 plum-dispatch v1.7.4。可以通过以下 pip 命令将它们轻松安装到 Windows 中。
pip install Spire.Presentation
如果您不确定如何安装,请参考:如何在 Windows 中安装 Spire.Presentation for Python
用 Python 将幻灯片中的形状保存为图像文件
Spire.Presentation for Python 提供了 Slide.Shapes.SaveAsImage(shapIndex: int, dpiX: int, dpiY: int) 方法来将演示文稿中的形状保存为指定 DPI(可选)的图像。使用此方法,开发者可以选择保存特定形状或整个 PowerPoint 演示文稿中的所有形状为图像文件。具体步骤如下:
- 创建 Presentation 类的实例。
- 使用 Presentation.LoadFromFile() 方法加载 PowerPoint 演示文稿。
- 使用 Presentation.Slides.get_Item() 方法获取幻灯片。
- 遍历幻灯片中的形状:
- 使用 Slide.Shapes.SaveAsImage() 方法将每个形状保存为图像流。
- 使用 Stream.Save() 方法将图像流保存为图像文件。
- Python
from spire.presentation import *
# 创建一个 Presentation 实例
presentation = Presentation()
# 加载一个 PowerPoint 文件
presentation.LoadFromFile("示例.pptx")
# 获取第四张幻灯片(索引从0开始)
slide = presentation.Slides.get_Item(4)
# 将形状保存为图片流
for i in range(slide.Shapes.Count):
# 保存当前形状为指定大小的图片流
imageStream = slide.Shapes.SaveAsImage(i, 256, 256)
# 保存图片到文件
imageStream.Save(f"output/Shapes/ShapeToImage{i}.png")
# 释放资源
presentation.Dispose()
将幻灯片中带格式设置的图片保存为图像文件
借助 Spire.Presentation for Python 提供的方法,开发者可以将幻灯片中的图片保存为图像文件,同时保留其编辑和格式。这需要先检查形状是否是 SlidePicture 类的对象,如果是,则使用 Slide.Shapes.SaveAsImage() 方法将其保存为图像。具体步骤如下:
- 创建一个 Presentation 类的实例。
- 使用 Presentation.LoadFromFile() 方法加载 PowerPoint 演示文稿。
- 使用 Presentation.Slides.get_Item() 方法获取幻灯片。
- 遍历幻灯片中的形状:
- 检查每个形状是否是 SlidePicture 类的对象。
- 如果是,则使用 Slide.Shapes.SaveAsImage() 方法将形状保存为图像流。
- 使用 Stream.Save() 方法将图像流保存为文件。
- Python
from spire.presentation import *
# 创建一个 Presentation 实例
presentation = Presentation()
# 加载一个 PowerPoint 文件
presentation.LoadFromFile("示例.pptx")
# 获取第五张幻灯片(索引从0开始)
slide = presentation.Slides.get_Item(1)
# 遍历幻灯片中的所有形状
i = 0
for shape in slide.Shapes:
# 检查形状是否是 SlidePicture 类型的对象
if isinstance(shape, SlidePicture):
# 保存形状为图片流
shape = shape if isinstance(shape, SlidePicture) else None
image = slide.Shapes.SaveAsImage(slide.Shapes.IndexOf(shape), 256, 256)
# 保存图片到文件
image.Save(f"output/Images/ImageShape{i}.png")
i += 1
# 释放资源
presentation.Dispose()
申请临时 License
如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。