Search code examples
javadocx4j

how to read and edit existing pptx using Docx4j?


I am using the following code to iterate over existing pptx, but how can I edit (replace text or image) in specific slide.

Example in documentation

    String inputfilepath = "C:/tmp/template.pptx";

            PresentationMLPackage presentationMLPackage = 
                (PresentationMLPackage)OpcPackage.load(new java.io.File(inputfilepath));

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

            SlidePart slidePart = presentationMLPackage.getMainPresentationPart().getSlide(i);

            SlideLayoutPart slideLayoutPart = slidePart.getSlideLayoutPart();

            //System.out.println(slp.getSourceRelationships().get(0).getTarget());
            System.out.println(slidePart.getPartName().getName());

            String layoutName = slideLayoutPart.getJaxbElement().getCSld().getName(); 

            System.out.println("layout: " + slideLayoutPart.getPartName().getName() + " with cSld/@name='" + layoutName + "'");

            System.out.println("Master: " + slideLayoutPart.getSlideMasterPart().getPartName().getName());

}

Solution

  • I have done many researches on office files like docx,xlsx,ppt I would like to suggest you one thing Once you open your file with zip/rar you will find its internal file structure

    Files 
    
    _rels
    docProps
    ppt
    

    [Content_types].xml these folders contain files are usually xml PPt and move to slides inside slide there will be xml files names slide1..2..3.etc these files have every text you type in your ppt. Replace Xml file with your content using the java coding and place it back into zip file.

    Thats it. Its working 100% i have implemented it many times.

    **summary:**
    
    In java code just try this
    1.Rename your file extension from pptx to zip
    2.extract path ppt\slides\[yourslide].xml
    3.do your content replacement for the extracted xml file.
    4.Place it back into zip 
    5.rename the file extension to pptx 
    

    That is it enjoy!!!

    regards, Kishan.c.s