Python-pptx: copy slide

Renat Nagaev picture Renat Nagaev · Jun 15, 2018 · Viewed 8.3k times · Source

How can I copy slide?

I created a template slide and I need to copy it and edit shapes of each copy separately.

Or how I can add my template slide to presentation.slide_layouts?

Answer

d_bergeron picture d_bergeron · Jul 3, 2018

This is what I found on GitHub, and it works for me. I did change a couple of things for my project. You will need to import six and copy. I am using pptx-6.10

def duplicate_slide(pres, index):
    template = pres.slides[index]
    try:
        blank_slide_layout = pres.slide_layouts[12]
    except:
        blank_slide_layout = pres.slide_layouts[len(pres.slide_layouts)]

    copied_slide = pres.slides.add_slide(blank_slide_layout)

    for shp in template.shapes:
        el = shp.element
        newel = copy.deepcopy(el)
        copied_slide.shapes._spTree.insert_element_before(newel, 'p:extLst')

    for _, value in six.iteritems(template.part.rels):
        # Make sure we don't copy a notesSlide relation as that won't exist
        if "notesSlide" not in value.reltype:
            copied_slide.part.rels.add_relationship(
                value.reltype,
                value._target,
                value.rId
            )

    return copied_slide

Then you can create the copy with passing in your presentation and the slide index of your template:

copied_slide = duplicate_slide(pres, 4)

I am still working on editing the shapes from the copied slide, once I am further along in my project I can update