Erin
Erin

Reputation: 1

Use python to find text in PowerPoint and replace with image?

Right now I have to add various images/icons next to names in PowerPoint corresponding to the sector in which they work. I found code to find and replace text, but I want to find text (e.g. "Health", "Water", etc.) throughout the powerpoint and replace with the corresponding image. Is there a direct way to do this? The code below replaces 'Health' with the ReplaceList string:

from pptx import Presentation    
ppt = Presentation('Powerpoint.pptx')    
TextList = 'Health'
ReplaceList = r'C:\Users\E\Desktop\Icons\Health.png'

for slide in ppt.slides:
    for shape in slide.shapes:
        if shape.has_text_frame:
            shape.text = shape.text.replace(TextList,ReplaceList)

ppt.save('New_Powerpoint.pptx')

If not, is there a way to locate the text locations (left, top) to then insert the image using the code below?

pic = slide.shapes.add_picture(image, left, top)

Upvotes: 0

Views: 1674

Answers (1)

BigBen
BigBen

Reputation: 49998

Perhaps something like this is what you're looking for, though I'm not exactly sure where you want the image to be placed relative to the text(box). You can also control the width and height with add_picture.

from pptx import Presentation    
ppt = Presentation('Powerpoint.pptx')    
search_str = 'Health'
image_link = r'C:\Users\E\Desktop\Icons\Health.png'

for slide in ppt.slides:
    for shape in slide.shapes:
        if shape.has_text_frame:
            if(shape.text.find(search_str))!=-1:
                pic = slide.shapes.add_picture(image_link, shape.left, shape.top)

ppt.save('NewPresentation.pptx')

Upvotes: 1

Related Questions