Search code examples
pythonpython-3.xpowerpoint

Can't add image in picture placholder powerpoint with Python


I want to replace images in powerpoint automatically using picture placeholders

I made it dynamic using python, but I'm having trouble getting errors like this:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'LayoutPlaceholder' object has no attribute 'insert_picture'

The code that I use follows:

    from pptx import Presentation 
    from pptx.util import Inches
    from PIL import Image
    prs = Presentation(r'..\gambar\base_master_mod.pptx')
    slide = prs.slide_layouts[0]
    placeholder = slide.placeholders[1] # id key, not posisition 
    placeholder.name
    placeholder.placeholder_format.type
    picture = placeholder.insert_picture("..\output_graphics\image_res.png")

Here powerpoint that i use : here

how to solve the problem?


Solution

  • Change line 5 to:

    slide = prs.slides[0]
    

    and see if that doesn't get you closer. You may still have to play around with the placeholder ids to figure out what they are. You can do something like this to list them out.

    for ph in slide.placeholders:
        print("placeholder %d has name: %s" % (ph.placeholder_format.idx, ph.name)
    

    Layout placeholders are distinct from slide placeholders with different behaviors. The .insert_picture() method is only on a slide picture-placeholder. That's why it's saying LayoutPlaceholder has no attribute 'insert_picture'.