Python 编程实现 PPT 批量转图片(PNG/JPG)

在日常工作中,我们经常需要把 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)

三、使用方法

  1. 修改 ppt_file 为你的 PPT 路径。
  2. 运行脚本,会在同目录下生成 PPT文件名_images 文件夹,里面是每一页的图片。3. 可通过参数调整图片格式和分辨率:ppt_to_images(ppt_file, image_format="JPG", width=2560, height=1440)
  3. Windows 用户可以用 withWindow=True 看到转换过程,调试更方便。如果导出的图片有白边,可以考虑在 PPT 里调整幻灯片尺寸
相关推荐
卷无止境6 分钟前
Python 开发中的资源管理:统一生命周期,保留资源差异
后端·python
新*16 分钟前
520 万数据迁移实战:Elasticsearch 索引重建与"改名"的完整踩坑记录
python·mysql·elasticsearch·数据迁移
吴名氏.1 小时前
Java转AI Agent教程(第十五周)政策时效:过期政策不该被召回,也不能被删掉
java·人工智能·python·ai·ai agent
黑客笔记11 小时前
python小工具win7翻车事故现场
python
岁月宁静13 小时前
从零拆解 AI 语音模拟面试系统
人工智能·python·agent
benchmark_cc13 小时前
个人开发者接入五档盘口:用 QuantDash 读取单只股票的验收清单与易错点
python·数据分析·pandas·量化交易·股票数据·quantdash
ZhengEnCi14 小时前
项目越写越乱?先别改架构:用一次目录重排 + 一份可复算的体检脚本把乱治住
python·架构·ai编程
Dmz丶15 小时前
前端转 AI 100 天 Day 45:阶段复盘——从“会调 API”到“做出 AI 产品”
python
Sakura_j_h_15 小时前
MCP SDK 2.0 实战:用 MCPServer 搭本地笔记检索服务
开发语言·笔记·python·qt·ai工具·mcp·mcpserver
QuZhengRong16 小时前
【AI】Agent 全栈进阶|AgentScope 沙箱源码解析
python·学习·ai·agent·沙箱