Search code examples
pythonpowerpointshapespython-pptx

Python-pptx - How to delete all shapes in pptx slide in python?


I use this library : https://python-pptx.readthedocs.io/, and I'm looking for a method to delete all shapes of a slide (and to replace by shapes taken from another slide). Thanks.


Solution

  • It's possible, though it is a little tricky. I adapted the code from this answer and this answer.

    from pptx import Presentation
    import copy
    
    prs = Presentation("test169_presentation.pptx")
    def delete_shapes(prs, slide_index):
        for shape in prs.slides[slide_index].shapes:
            shape_element = shape.element
            shape_element.getparent().remove(shape_element)
    
    def copy_shapes(prs, source_slide_index, dest_slide_index):
        source_slide = prs.slides[source_slide_index]
        dest_slide = prs.slides[dest_slide_index]
        unused_shape_id = max(shape.shape_id for slide in prs.slides for shape in slide.shapes) + 1
        for shape in source_slide.shapes:
            new_shape = copy.deepcopy(shape.element)
            dest_slide.shapes._spTree.insert_element_before(new_shape, 'p:extLst')
            
    delete_shapes(prs, 1)
    copy_shapes(prs, 0, 1)
    
    prs.save("test169_presentation2.pptx")
    

    This program is deleting the shapes from slide 2, then copying the shapes from slide 1 to slide 2.

    Before:

    two different slides

    After:

    the same slide twice