提取并再利用 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 天的临时许可证。