Prashant Kumar
Prashant Kumar

Reputation: 701

"Send to back" a shape on PPT using python

I have script which adds a textbox with some text on an existing PPT. Now the textbox colour is made white to overwrite the existing text present in the slidemaster.

The issue is than a small part of textbox overlaps with another shape which is supposed to be on top. Is there an option in python-pptx to send the shape to back. Below is the option which can be used using the powerpoint enter image description here

Is the a way I can do this using python-pptx

here is my script


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!")


Upvotes: 2

Views: 3295

Answers (1)

G. N. MS
G. N. MS

Reputation: 155

This discussion in github might help you:

The z-order of shapes on a slide is determined solely by their document order in the slide part (e.g. slide1.xml). So the general gist would be to re-order that sequence of elements. The shapes in a slide are contained in the slide's "shape tree", a element with the same syntax as the group shape, just the different name. The object I expect you'll want to look at first is pptx.shapes.shapetree.SlideShapeTree and its parent BaseShapeTree, which is what you get from slide.shapes. The _spTree attribute on that object gives you the lxml object for the element, which would allow you to reorder shapes.

[...]

I believe the .addprevious() and .addnext() lxml methods actually move the XML element in question.

So you could do something like this to move a shape from ninth position to fourth:

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

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

See github question

Upvotes: 2

Related Questions