Dino van Deijzen
Dino van Deijzen

Reputation: 41

python-pptx change picture in layout

I try to enable automatically import pictures in order to prevent manually ad 100's of pictures each time. I seem to be unable to access the placeholders of the pictures and replace them with a new picture. some guide in the correct direction would be of great help.

code i start with:

import pptx
import pptx.util

from pptx import Presentation

prs = Presentation('prepare_2.pptx')

picture_runs = []


for slide in prs.slides:
    for shape in slide.shapes:
        if shape.shape_type == 13:

            slide.get.image('tree.jpg')
          >Picture_runs.append((shape.name,shape.shape_type,shape.id,shape.image))

information i gained are found : http://python-pptx.readthedocs.io/en/latest/user/quickstart.html

slide layout

Upvotes: 4

Views: 5684

Answers (1)

danieltellez
danieltellez

Reputation: 216

First of all, you have to analyze the layouts available in your template (prepare_2.pptx in your case).

To do that, it is as easy as to write a script that get all the layouts in the presentation and lists all the shapes and placeholders. Something like that:

prs = Presentation('template.pptx')
for idx, slide_layout in enumerate(prs.slide_layouts):
    slide = prs.add_slide(slide_layout)
    for shape in slide.placeholders:
        print idx, shape.placeholder_format.idx, shape.name

If you use this script as is, you must probably manage the exceptions if shape is not a placeholder. You can also know and design your layouts by editing your presentation masters on Powerpoint, but you will have to guess the idxs.

Once you know which layout have Picture Placeholder in it, you can select this kind of layout to create your new slide with Image.

Something like that:

slide = prs.slides.add_slide(THE_IDX_OF_YOUR_LAYOUT_WITH_PICTURE)
placeholder = slide.placeholders[THE_IDX_OF_YOUR_PICTURE_PLACEHOLDER]
placeholder.insert_picture(picture)

I recommend you to read this absolutely great article about that: http://pbpython.com/creating-powerpoint.html

Upvotes: 1

Related Questions