首页 > 解决方案 > 使用python在PPT上“发送回”一个形状

问题描述

我有一个脚本,它在现有的 PPT 上添加了一个带有一些文本的文本框。现在文本框颜色变为白色以覆盖幻灯片母版中存在的现有文本。

问题在于文本框的一小部分与应该在顶部的另一个形状重叠。是否可以选择python-pptx将形状发送到后面。以下是可以使用 powerpoint 的选项 在此处输入图像描述

是我可以做到这一点的一种方式python-pptx

这是我的脚本


for pptfile in addressList:
    prs = Presentation(pptfile)
    slides = prs.slides

    for i in range(2,len(slides)-1):
            textContent = ""
            slide = prs.slides[i]
            # Text position
            t_left = Inches(3.27)
            t_top = Inches(7.05)
            t_width = Inches(6.89)
            t_height = Inches(0.27)
            # Text
            txBox = slide.shapes.add_textbox(t_left, t_top, t_width, t_height)
            fill = txBox.fill
            fill.solid()
            fill.fore_color.rgb = RGBColor(255, 255, 255)

            tf = txBox.text_frame.paragraphs[0]
            tf.vertical_anchor = MSO_ANCHOR.TOP
            tf.word_wrap = True
            tf.margin_top = 0
            tf.auto_size = MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT
            run = tf.add_run()
            run.text = "This is new text."
            font = run.font
            font.name = 'Univers LT Std 47 Cn Lt'
            font.size = Pt(10)
            font.bold = None
            font.italic = None  # cause value to be inherited from theme
            font.color.rgb = RGBColor(157, 163, 163)
    prs.save(pptfile)
    print(pptfile," Done!")


标签: pythonpowerpointpython-pptx

解决方案


github中的这个讨论可能会对您有所帮助:

幻灯片上形状的 z 顺序仅由它们在幻灯片部分(例如 slide1.xml)中的文档顺序决定。因此,一般要点是重新排序该元素序列。幻灯片中的形状包含在幻灯片的“形状树”中,该元素的语法与组形状相同,只是名称不同。我希望您首先要查看的对象是 pptx.shapes.shapetree.SlideShapeTree 及其父 BaseShapeTree,这是您从 slide.shapes 中获得的。该对象的 _spTree 属性为您提供元素的 lxml 对象,这将允许您重新排序形状。

[...]

我相信 .addprevious() 和 .addnext() lxml 方法实际上会移动有问题的 XML 元素。

所以你可以做这样的事情来将形状从第九位移动到第四位:

# shape will be positioned relative to this one, hence the name "cursor"

cursor_sp = shapes[3]._element
cursor_sp.addprevious(shapes[8]._element)

见github问题


推荐阅读