Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failed to clone new PowerPoint slide with images

I'd like to clone one slide of a PowerPoint doc and insert into the same document with OpenXML. For this, I'm using the following function:

public static void AddNewSlide(PresentationPart parent, Slide _slideTemplate, string newId)
{
    var newSlidePart = parent.AddNewPart<SlidePart>(newId);
    newSlidePart.FeedData(_slideTemplate.SlidePart.GetStream(FileMode.Open));
    newSlidePart.AddPart(_slideTemplate.SlidePart.SlideLayoutPart, _slideTemplate.SlidePart.GetIdOfPart(_slideTemplate.SlidePart.SlideLayoutPart));
    newSlidePart.Slide.Save();
    
    DocumentFormat.OpenXml.Presentation.SlideIdList slideIdList = parent.Presentation.SlideIdList;
    uint maxSlideId = 1;

    foreach (DocumentFormat.OpenXml.Presentation.SlideId slideId in slideIdList.ChildElements)
    {
        if (slideId.Id > maxSlideId) maxSlideId = slideId.Id;
    }
    
    DocumentFormat.OpenXml.Presentation.SlideId newSlideId = new DocumentFormat.OpenXml.Presentation.SlideId { Id = ++maxSlideId, RelationshipId = parent.GetIdOfPart(newSlidePart) };
    slideIdList.Append(newSlideId);
}

If the orig slide contains just text, it works fine, but when the orig slide contans images too, the result PowerPoint doc will bw corrupted. The images on the new slide won't be displayed, just with a message: "This image cannot currently be displayed."

like image 851
koccintosful Avatar asked Dec 20 '25 03:12

koccintosful


1 Answers

This code is generating corrupted slide, because it is only copying the data and layout, but not the images that are in the slide.

newSlidePart.FeedData(_slideTemplate.SlidePart.GetStream(FileMode.Open));
newSlidePart.AddPart(_slideTemplate.SlidePart.SlideLayoutPart, _slideTemplate.SlidePart.GetIdOfPart(_slideTemplate.SlidePart.SlideLayoutPart));

for eg: the above 2 lines will say that the new slide is referring to an image, but that image itself is missing in the new slide. Hence, to solve this problem, you need to also write the code that will copy the image from the old slide to the new one.

//add all the image part from the source slide to the new one

List<ImagePart> imageParts = new List<ImagePart>();
sourceSlidePart.GetPartsOfType<ImagePart>(imageParts);

foreach (ImagePart img in imageParts)
{
    string relID = sourceSlidePart.GetIdOfPart(img); // get relationship ID

    ImagePart newImagePart = newSlidePart.AddImagePart(img.ContentType, relID);

    newImagePart.FeedData(img.GetStream(FileMode.Open));
}
like image 134
Kalpesh Popat Avatar answered Dec 22 '25 17:12

Kalpesh Popat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!