0
votes

I'm trying to split a pptx presentation into a set of one-slide presentations with use of docx4j. Therefore I try to insert an existing slide, taken from an existing presentation and insert it in a newly created presentation.

So far I have the following code which does run through and create splitted pptx files. However the output files are corrupted and are missing images.

// load existing presentation from where slide will be extracted 
PresentationMLPackage presentationMLPackage = PresentationMLPackage.load(new FileInputStream("data/input/" + inFileName + ".pptx"));        
MainPresentationPart mpp = presentationMLPackage.getMainPresentationPart();

for(int i=0; i<mpp.getSlideCount(); i++) {

    // extract slide
    SlidePart sp = mpp.getSlide(i);
    Sld spContent = sp.getContents();

    // extract layout
    String sourceLayoutXml = sp.getSlideLayoutPart().getXML();
    String sourceMasterXml = sp.getSlideLayoutPart().getSlideMasterPart().getXML();

    // create new ppt
    PresentationMLPackage newPpt = PresentationMLPackage.createPackage(); // TODO: other than landscape, 16x9?

    MainPresentationPart mppNewPpt = (MainPresentationPart)newPpt.getParts().getParts().get(
                new PartName("/ppt/presentation.xml"));
    SlideLayoutPart layoutPart = (SlideLayoutPart)newPpt.getParts().getParts().get(
                new PartName("/ppt/slideLayouts/slideLayout1.xml"));

    layoutPart.setContents(
                (SldLayout)XmlUtils.unmarshalString(sourceLayoutXml, Context.jcPML));

    SlideMasterPart masterPart = layoutPart.getSlideMasterPart();
    masterPart.setContents(
                    (SldMaster)XmlUtils.unmarshalString(sourceMasterXml, Context.jcPML));

    // create new blank slide
    SlidePart slidePart = new SlidePart();

    // set content from extracted slide
    slidePart.setContents(spContent);

    // add slide to presentation
    mppNewPpt.addSlide(0, slidePart);

    // set slide layout part for new slide
    slidePart.addTargetPart(layoutPart);

    // save new ppt
    newPpt.save(new FileOutputStream(outDir + "/" + inFileName + "_slide_" + i + ".pptx"));
}

I think this has something to do with the incorrect import of existing SlideLayout. Does anyone have any experience with importing/copying existing slides(with custom layouts) into a new presentation?

I would really appreciate any sharing of thoughts/examples/hints.

Thank you!

Paul

1

1 Answers

0
votes

The issue is that images are stored separately and need to be added as relationships and referenced using the corresponding relId.

A "poor man's" approach would be to clone the existing pptx (OpcPackage clone()), then delete the slides you don't want. Doing it this way, the output pptx file may still contain objects you don't need (you'll need to try it and see).

Otherwise, you could use our commercial MergePptx component (part of Docx4j Enterprise).