首页 > 解决方案 > 是否可以使用 python-pptx 组合两个或多个 powerpoint?

问题描述

我正在尝试合并 powerpoint 幻灯片,但我不知道该怎么做。我发现了一个看起来很有希望的 python 模块 pptx。我尝试将幻灯片内容从 2 个 powerpoint 复制到一个新的 powerpoint。但是我遇到了很多问题,比如如何获取现有的幻灯片布局或形状(所有形状,包括图片、自动形状等)的高度、宽度、位置。我查看了 Python-pptx 上的 python-pptx 示例:复制幻灯片。我尝试做类似的事情,但这不起作用。

这是我的代码:

from pptx import Presentation

prs1 = Presentation("C:/Users/number/Documents/Test1.pptx")
prs2 = Presentation("C:/Users/number/Documents/Test2.pptx")

slidelst = []
for layout in prs2.slide_layouts:
    slidelst.append(prs1.slides.add_slide(layout))

index = 0
for slide in slidelst:
    for shape in prs2.slides[prs2.slides.index(slide)].shapes:
        slide.shapes._spTree.insert_element_before(shape.element, 'p:extLst')
    index+=1

prs1.save("C:/Users/I505168/Documents/newpresentation.pptx")

我得到错误:

Traceback (most recent call last):
  File "C:\Users\I505168\Desktop\testpptx.py", line 12, in <module>
    for shape in prs2.slides[prs2.slides.index(slide)].shapes:
  File "C:\Users\I505168\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pptx\slide.py", line 315, in index
    raise ValueError("%s is not in slide collection" % slide)
ValueError: <pptx.slide.Slide object at 0x03B53A50> is not in slide collection

预期结果是两张单独的幻灯片合并为一张幻灯片。

标签: pythonpython-pptx

解决方案


我能够通过使用 python 和 win32com.client 解决这个问题,也许它不是你需要的,因为它会启动 Microsoft Powerpoint 并将幻灯片从输入文件复制并粘贴到输出文件。然后关闭 PowerPoint 应用程序。如果此方法对您有用,这里是我对另一个问题的回答的链接。


推荐阅读