# -*- coding: utf-8 -*- """按照要求:复制副本 -> python-pptx 删除占位内容 -> win32com 导出 PNG 用法: python ppt_to_images.py <源PPT文件> [页数] - 页数不传则导出所有页,传 N 则只导出前 N 页 """ import argparse import shutil from pathlib import Path from pptx import Presentation from pptx.shapes.placeholder import PP_PLACEHOLDER # 首页删除:标题、副标题(SUBTITLE/BODY) FIRST_TYPES = {PP_PLACEHOLDER.TITLE, PP_PLACEHOLDER.SUBTITLE, PP_PLACEHOLDER.BODY} parser = argparse.ArgumentParser(description='PPT模版清理并导出PNG') parser.add_argument('src', help='源PPT文件路径') parser.add_argument('pages', type=int, nargs='?', default=None, help='需要导出为图片的页数,不传则导出所有页') args = parser.parse_args() SRC = Path(args.src).resolve() if not SRC.is_file(): raise SystemExit(f'源文件不存在: {SRC}') COPY = SRC.with_name(f'{SRC.stem}_副本.pptx') OUT_DIR = SRC.with_name(f'{SRC.stem}_导出') # 1. 复制副本 shutil.copy2(SRC, COPY) # 2. python-pptx 编辑副本 prs = Presentation(str(COPY)) total = len(prs.slides._sldIdLst) if args.pages is not None and not 1 <= args.pages <= total: raise SystemExit(f'页数需在 1~{total} 之间,收到: {args.pages}') for i, slide in enumerate(prs.slides): for sh in list(slide.shapes): if i == 0: # 首页:仅删除标题、副标题占位符 if sh.is_placeholder and sh.placeholder_format.type in FIRST_TYPES: el = sh._element el.getparent().remove(el) else: # 非首页:删除页面上所有形状(标题、正文、时间、页码等全部内容) el = sh._element el.getparent().remove(el) prs.save(str(COPY)) # 3. win32com.client 导出指定页为 PNG import win32com.client export_pages = total if args.pages is None else args.pages OUT_DIR.mkdir(exist_ok=True) for old in OUT_DIR.glob('slide_*.png'): old.unlink() app = win32com.client.Dispatch('PowerPoint.Application') pres = app.Presentations.Open(str(COPY), ReadOnly=True, WithWindow=False) try: w, h = pres.PageSetup.SlideWidth, pres.PageSetup.SlideHeight scale = 2 # 2 倍分辨率导出 for i in range(1, export_pages + 1): pres.Slides(i).Export(str(OUT_DIR / f'slide_{i:02d}.png'), 'PNG', int(w * scale), int(h * scale)) finally: pres.Close() app.Quit() print(f'完成,共 {total} 页,导出 {export_pages} 页 -> {OUT_DIR}')