Search code examples
pythonpython-pptx

python-pptx insert picture in PlaceholderPicture


I'm trying to insert a picture in a pptx Placeholder

for shape in presentation.slides[(len(presentation.slides) - 1)].placeholders:
    print(shape.name)
    print(shape.shape_type)
    print(shape.placeholder_format.type)
    
    if "Bild" in shape.name:
        shape.insert_picture(os.path.join(self.image_folder, "media_value.png"))

my output:

Bildplatzhalter 17
PLACEHOLDER (14)
PICTURE (18)

the error:

shape.insert_picture(os.path.join(self.image_folder, "media_value.png"))
AttributeError: 'PlaceholderPicture' object has no attribute 'insert_picture'

From the Documentation, it should work like this. what i'm doing wrong?

python3.9
python-pptx0.6.21


Solution

  • The placeholder you are inserting into needs to be a picture placeholder rather than a text one.

    from pptx import Presentation
    from pptx.util import Inches
    
    # Create a new presentation object
    presentation = Presentation()
    
    # Specify the slide layout. Slide layouts 8 has a picture placeholder
    slide_layout = presentation.slide_layouts[8]
    
    # Add a slide with the specified layout to the presentation
    slide = presentation.slides.add_slide(slide_layout)
    
    # Specify the placeholder. Placeholder 1 is the picture placeholder.
    # Choosing another placeholder will return an error
    placeholder = slide.placeholders[1]
    
    # Specify the path to the image file
    img_path = "Animal 1.jpg"
    
    # Add the image to the placeholder
    placeholder = placeholder.insert_picture(img_path)
    
    # Save the presentation
    presentation.save('image.pptx')