2

There are Text and Picture in one slide of PPT. I would like to set Picture to bottom layer/set Text to top layer and see Text content. How to do that?

text_frame = shape.text_frame
text_frame.vertical_anchor = MSO_ANCHOR.TOP

text_frame = shape.text_frame
text_frame.vertical_anchor = MSO_ANCHOR.TOP
text_frame.paragraphs[0].runs[0].text = "text"

left = Inches(5)
height = Inches(5.5)
pic = slide.shapes.add_picture(img_path, left, top, height=height)

Let Picture in bottom layer and Text in top layer in PPT.

scanny
  • 26,423
  • 5
  • 54
  • 80
Alex Ho
  • 23
  • 4

1 Answers1

3

The layers on the slide will appear as per the sequence in the code. It can be customized by defining the layer depth as per the requirement.

from pptx import Presentation, shapes, slide
from pptx.util import Inches

img_path = 'image.png'

prs = Presentation()
blank_slide_layout = prs.slide_layouts[0]
slide = prs.slides.add_slide(blank_slide_layout)

title = slide.shapes.title
subtitle = slide.placeholders[1]

title.text = "Hello, World!"
subtitle.text = "Welcome to python-pptx!"

left = Inches(1)
height = Inches(4)
width = Inches(6)
top = Inches(1)
picture = slide.shapes.add_picture(img_path, left, top, height=height)

# Using layer sequence number to customize the depth 
# sending the picture back in this case

slide.shapes._spTree.insert(2, picture._element)

prs.save('test.pptx')
MI Alam
  • 417
  • 3
  • 9
  • It works. Currently, I can set Picture to the bottom layer. Thanks. – Alex Ho Oct 29 '19 at 06:38
  • 1
    Very nice @MIAlam! :) Just a small detail, you can eliminate the `slide.shapes._spTree.remove()` line. In `lxml` when you insert an element somewhere, it comes out of it's old position to take the new position. This question of how to adjust z-order of shapes comes up a lot and this is a very helpful solution :) – scanny Oct 29 '19 at 16:44