如何在 Python 中加载演示文稿

如何在 Python 中加载演示文稿

Aspose.Slides FOSS for Python 允许您打开任何 .pptx 文件,检查其内容,并可以将其保存回 PPTX 或从中提取数据。本指南涵盖打开文件、遍历幻灯片、读取形状文本以及往返保存。

分步指南

步骤 1:安装软件包

pip install aspose-slides-foss

步骤 2:打开现有演示文稿

将文件路径传递给 slides.Presentation()。使用上下文管理器以确保清理。

import aspose.slides_foss as slides
from aspose.slides_foss.export import SaveFormat

with slides.Presentation("input.pptx") as prs:
    print(f"Slide count: {len(prs.slides)}")
    prs.save("output.pptx", SaveFormat.PPTX)

源文件中未知的 XML 部分会原样保留:库从不删除它尚未理解的内容。


步骤 3:检查幻灯片

遍历所有幻灯片并打印它们的索引:

import aspose.slides_foss as slides

with slides.Presentation("deck.pptx") as prs:
    for i, slide in enumerate(prs.slides):
        shape_count = len(slide.shapes)
        print(f"Slide {i}: {shape_count} shapes")

步骤 4:读取形状文本

遍历形状并读取具有 TextFrame 的形状中的文本:

import aspose.slides_foss as slides

with slides.Presentation("deck.pptx") as prs:
    for slide in prs.slides:
        for shape in slide.shapes:
            if hasattr(shape, "text_frame") and shape.text_frame is not None:
                text = shape.text_frame.text
                if text.strip():
                    print(f"  Shape text: {text!r}")

步骤 5:读取文档属性

prs.document_properties 访问核心文档属性:

import aspose.slides_foss as slides

with slides.Presentation("deck.pptx") as prs:
    props = prs.document_properties
    print(f"Title:   {props.title}")
    print(f"Author:  {props.author}")
    print(f"Subject: {props.subject}")

步骤 6:往返保存

检查或修改演示文稿后,将其保存回 PPTX:

prs.save("output.pptx", SaveFormat.PPTX)

保存到不同的路径会创建一个新文件。保存到相同的路径会覆盖原文件。


常见问题及解决方案

FileNotFoundError

检查相对于工作目录的 .pptx 文件路径是否正确。使用 pathlib.Path 进行稳健的路径构建:

from pathlib import Path
path = Path(__file__).parent / "assets" / "deck.pptx"
with slides.Presentation(str(path)) as prs:
    ...

Exception: File format is not supported

该库仅支持 .pptx(Office Open XML)。不支持旧版 .ppt(二进制 PowerPoint 97–2003)文件。

形状没有 text_frame 属性

某些形状(Connectors、PictureFrames、GroupShapes)没有 text_frame。在访问文本之前,请使用 hasattr(shape, "text_frame") and shape.text_frame is not None 进行防护。


常见问题

加载是否保留所有原始内容?

是的。未知的 XML 部分在往返保存时会原样保留。该库不会删除它尚未理解的任何 XML 内容。

我可以加载受密码保护的 PPTX 吗?

此版本不支持受密码保护(加密)的演示文稿。

我可以提取嵌入的图像吗?

访问图像集合:prs.images 返回 ImageCollection。每个图像都有 content_typebytes 属性,用于读取原始图像数据。

是否支持从内存流加载?

直接从 io.BytesIO 加载在当前 API 中未公开。请先将字节写入临时文件:

import tempfile, os
import aspose.slides_foss as slides

with tempfile.NamedTemporaryFile(suffix=".pptx", delete=False) as tmp:
    tmp.write(pptx_bytes)
    tmp_path = tmp.name

try:
    with slides.Presentation(tmp_path) as prs:
        print(f"Slides: {len(prs.slides)}")
finally:
    os.unlink(tmp_path)

另请参阅

 中文