-1

I'm able to copy the second slide of a test.pptx to a copy.pptx, and create a new copy2.pptx. But the new PPT is corrupted.

Here is my code:

import collections
import collections.abc

import copy
from pptx import Presentation


def copy_slide(prs, source, target_index):

    dest = prs.slides.add_slide(source.slide_layout)
    for shp in dest.shapes:
        shp.element.getparent().remove(shp.element)
    # Copy shapes from source, in order
    for shape in source.shapes:
        new_shape = copy.deepcopy(shape.element)
        dest.shapes._spTree.insert_element_before(new_shape, 'p:extLst')
    # Copy rels from source
    for key, val in source.part.rels.items():
        target = val._target
        dest.part.rels.add_relationship(val.reltype, target, val.rId, val.is_external)
    # Move appended slide into target_index
    prs.slides.element.insert(target_index, prs.slides.element[-1])
    return dest

prs = Presentation('test.pptx')
source = prs.slides[1]

prs2 = Presentation('copy.pptx')

copyslide = copy_slide(prs2, source, 1)

prs2.save('copy2.pptx')

print(copyslide)

I'm getting following error in the terminal:

UserWarning: Duplicate name: 'ppt/slideLayouts/_rels/slideLayout9.xml.rels'
  return self._open_to_write(zinfo, force_zip64=force_zip64) 
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
DecoderS
  • 64
  • 6

1 Answers1

1

I have done something similar using the following code:

import sys
from pptx import Presentation
import copy

def merge_powerpoint_ppts(pres_loc1, pres_loc2, output_loc):
    pres1 = Presentation(pres_loc1)
    pres2 = Presentation(pres_loc2)  
    for slide in pres2.slides:
        sl = pres1.slides.add_slide(pres1.slide_layouts[2])
        for shape in slide.shapes:
            element = shape.element
            newelement = copy.deepcopy(element)
            sl.shapes._spTree.insert_element_before(newelement, 'p:extLst')
    pres1.save(output_loc + "\Output.ppt")
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
  • I tried with your code but its adding whole second ppt to end. I want to add specific slide at specific location and also at **" pres1.slides.add_slide(pres1.slide_layouts[2]) "** after creating new layout the default slide message( Click to add text) is getting overlapped with copied content. – DecoderS Sep 06 '22 at 11:32