在日常工作中,我们经常需要把 PPT 转成图片用于博客、报告或者分享。Python 提供了一个非常方便的方式,通过 win32com 自动化 PowerPoint,实现批量导出幻灯片。
一、安装依赖
pip install pywin32
注意:该方法仅在 Windows 系统上有效,并且需要安装 MicrosoftPowerPoint
二、完整代码
python
import os
from pathlib import Path
import pythoncom
from win32com.client import Dispatch
def ppt_to_images(ppt_path, output_dir=None, image_format="PNG", width=1920, height=1080):
"""
将 PPT 每一页导出为图片
参数:
ppt_path: PPT 文件路径
output_dir: 输出文件夹,默认在 PPT 同目录下创建同名文件夹
image_format: 图片格式,可选 "PNG" / "JPG"
width: 导出宽度
height: 导出高度
"""
ppt_path = Path(ppt_path)
if not ppt_path.exists():
raise FileNotFoundError(f"找不到文件: {ppt_path}")
if output_dir is None:
output_dir = ppt_path.parent / f"{ppt_path.stem}_images"
else:
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
pythoncom.CoInitialize()
powerpoint = None
presentation = None
try:
powerpoint = Dispatch("PowerPoint.Application")
powerpoint.Visible = 1
presentation = powerpoint.Presentations.Open(
str(ppt_path),
WithWindow=False
)
# 导出全部幻灯片
presentation.Export(str(output_dir), image_format, width, height)
print(f"转换完成,图片已保存到: {output_dir}")
except Exception as e:
print(f"转换失败: {e}")
finally:
if presentation:
presentation.Close()
if powerpoint:
powerpoint.Quit()
pythoncom.CoUninitialize()
if __name__ == "__main__":
ppt_file = r"D:\目标文件.ppt"
ppt_to_images(ppt_file)
三、使用方法
- 修改
ppt_file为你的 PPT 路径。 - 运行脚本,会在同目录下生成
PPT文件名_images文件夹,里面是每一页的图片。3. 可通过参数调整图片格式和分辨率:ppt_to_images(ppt_file, image_format="JPG", width=2560, height=1440) - Windows 用户可以用 withWindow=True 看到转换过程,调试更方便。如果导出的图片有白边,可以考虑在 PPT 里调整幻灯片尺寸