如何在 Python 中加载演示文稿

如何在 Python 中加载演示文稿

Aspose.Slides FOSS for Python lets you open any .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:读取形状文本

遍历形状并读取具有 a 的形状文本。 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 吗??

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

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

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

是否支持从内存流加载??

直接从 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)

另请参阅

 中文