使用 Python pptx 更改幻灯片布局

Alter slide layout with Python pptx

我正在尝试更改布局上的一些文本,我将在几张幻灯片中使用这些文本。我将为许多不同的各方创建相同的 pptx 文档,并且我想根据 pptx 的对象更改布局上的文本。

我知道可以获得如下幻灯片布局。是否可以编辑布局上的形状?

import pptx

prs = pptx.Presentation(importPath)

layouts = prs.slide_layouts
layout1 = layouts[0]

## Edit layout1's shapes here...

幻灯片布局是幻灯片的一种特殊变体,因此它还有一个 .shapes 属性 可用于访问布局上的形状。其中许多将是占位符,但背景形状(如文本框或 pictures/logos)也将在那里。访问后,这些形状的操作方式与任何其他幻灯片上的形状相同。

这是一个脚本,可以修改其中一张布局幻灯片中标题形状的文本。它还包括列出该布局上所有占位符和形状的代码。这有助于确定如何访问要修改的形状。

from pptx import Presentation

prs = Presentation()                    # create a new blank presentation
idx_layout = 1
slide = prs.slide_layouts[idx_layout]   # reference a specific layout

print('Placeholder indices for template %d' % (idx_layout))
for shape in slide.placeholders:
        print('idx:{:>3d}   name: {}'.format(shape.placeholder_format.idx, shape.name))

print('\nList of shapes for template %d' % (idx_layout))
for shape in slide.shapes:
    print(shape.name)

slide.shapes[0].text = "New Title"      # set the text in the first shape
prs.save("test.pptx")