In the software industry, presentations play a major role as information can be conveyed easily in a presentable way via presentations. Using Java, with the help of Apache POI, we can create elegant presentations. Let us see in this article how to do that.
Necessary dependencies for using Apache POI:
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.17</version>
</dependency>
Apache POI
It has support for both .ppt and .pptx files. i.e. viaÂ
- HSLF implementation is used for the Powerpoint 97(-2007) file formatÂ
- XSLF implementation for the PowerPoint 2007 OOXML file format.
There is no common interface available for both implementations. Hence forÂ
- .pptx formats, XMLSlideShow, XSLFSlide, and XSLFTextShape classes need to be used.
- .ppt formats, HSLFSlideShow, HSLFSlide, and HSLFTextParagraph classes need to be used.
Let us see the example of creating with .pptx format
Creation of a new presentation:
XMLSlideShow samplePPT = new XMLSlideShow(); samplePPT .createSlide();
Next is adding a slide
XSLFSlideMaster defaultSlideMaster = samplePPT .getSlideMasters().get(0);
Now, we can retrieve the XSLFSlideLayout and it has to be used while creating the new slide
XSLFSlideLayout xslFSlideLayout = defaultMaster.getLayout(SlideLayout.TITLE_AND_CONTENT); XSLFSlide slide = samplePPT.createSlide(xslFSlideLayout );
Let us cover the whole concept by going through a sample maven project.
Example Maven Project
Project Structure:
 
Â
As this is the maven project, let us see the necessary dependencies via pom.xml
pom.xml
XML
| <?xmlversion="1.0"encoding="UTF-8"?>    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0                        http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <artifactId>powerpointpresentation-apache-poi</artifactId>    <version>0.0.1-SNAPSHOT</version>    <name>powerpointpresentation-apache-poi</name>      <parent>        <groupId>com.gfg</groupId>        <artifactId>parent-modules</artifactId>        <version>1.0.0-SNAPSHOT</version>    </parent>      <dependencies>        <dependency>            <groupId>org.apache.poi</groupId>            <artifactId>poi-ooxml</artifactId>            <version>${poi.version}</version>        </dependency>    </dependencies>      <properties>        <poi.version>5.2.0</poi.version>    </properties>  </project> | 
PowerPointHelper.java
In this file below operations are seen
- A new presentation is created
- New slides are added
- save the presentation as
FileOutputStream outputStream = new FileOutputStream(fileLocation); samplePPT.write(outputStream); outputStream.close();
We can write Text, create hyperlinks, and add images. And also the creation of a list, and table are all possible. In general, we can create a full-fledged presentation easily as well can alter the presentation by adjusting the slides, deleting the slides, etc. Below code is self-explanatory and also added comments to get an understanding of it also.
Java
| importorg.apache.poi.sl.usermodel.AutoNumberingScheme;importorg.apache.poi.sl.usermodel.PictureData;importorg.apache.poi.sl.usermodel.TableCell;importorg.apache.poi.sl.usermodel.TextParagraph;importorg.apache.poi.util.IOUtils;importorg.apache.poi.xslf.usermodel.SlideLayout;importorg.apache.poi.xslf.usermodel.XMLSlideShow;importorg.apache.poi.xslf.usermodel.XSLFAutoShape;importorg.apache.poi.xslf.usermodel.XSLFHyperlink;importorg.apache.poi.xslf.usermodel.XSLFPictureData;importorg.apache.poi.xslf.usermodel.XSLFPictureShape;importorg.apache.poi.xslf.usermodel.XSLFShape;importorg.apache.poi.xslf.usermodel.XSLFSlide;importorg.apache.poi.xslf.usermodel.XSLFSlideLayout;importorg.apache.poi.xslf.usermodel.XSLFSlideMaster;importorg.apache.poi.xslf.usermodel.XSLFTable;importorg.apache.poi.xslf.usermodel.XSLFTableCell;importorg.apache.poi.xslf.usermodel.XSLFTableRow;importorg.apache.poi.xslf.usermodel.XSLFTextParagraph;importorg.apache.poi.xslf.usermodel.XSLFTextRun;importorg.apache.poi.xslf.usermodel.XSLFTextShape;  importjava.awt.*;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.util.ArrayList;importjava.util.List;  // Helper class for the// PowerPoint presentation creationpublicclassPowerPointHelper {      /**     * Read an existing presentation     *     * @param fileLocation     *            File location of the presentation     * @return instance of {@link XMLSlideShow}     * @throws IOException     */    publicXMLSlideShow readWithExistingSlideShow(String fileLocation) throwsIOException {        returnnewXMLSlideShow(newFileInputStream(fileLocation));    }      /**     * Create a sample presentation     *     * @param fileLocation     *            File location of the presentation     * @throws IOException     */    publicvoidcreatingAPresentation(String fileLocation) throwsIOException {        // Create presentation        XMLSlideShow samplePPT = newXMLSlideShow();          XSLFSlideMaster defaultSlideMaster = samplePPT.getSlideMasters().get(0);          // Retrieving the slide layout        XSLFSlideLayout defaultLayout = defaultSlideMaster.getLayout(SlideLayout.TITLE_ONLY);          // Creating the 1st slide        XSLFSlide sampleSlide1 = samplePPT.createSlide(defaultLayout);        XSLFTextShape sampleTitle = sampleSlide1.getPlaceholder(0);        Â          // Clearing text to remove the          // predefined one in the template        sampleTitle.clearText();        XSLFTextParagraph paragraph = sampleTitle.addNewTextParagraph();          XSLFTextRun r1 = paragraph.addNewTextRun();        r1.setText("Lazyroar");        r1.setFontColor(newColor(78, 147, 89));        r1.setFontSize(48.);          // Add Image        ClassLoader classLoader = getClass().getClassLoader();        byte[] imageData = IOUtils.toByteArray(newFileInputStream(classLoader.getResource("gfglogo.png").getFile()));          XSLFPictureData pictureData = samplePPT.addPicture(imageData, PictureData.PictureType.PNG);        XSLFPictureShape picture = sampleSlide1.createPicture(pictureData);        picture.setAnchor(newRectangle(320, 230, 100, 92));          // Creating 2nd slide        defaultLayout = defaultSlideMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);        XSLFSlide sampleSlide2 = samplePPT.createSlide(defaultLayout);          // setting the tile        sampleTitle = sampleSlide2.getPlaceholder(0);        sampleTitle.clearText();        XSLFTextRun r = sampleTitle.addNewTextParagraph().addNewTextRun();        r.setText("Lazyroar");          // Adding the link        XSLFHyperlink hyperLink = r.createHyperlink();          // setting the content        XSLFTextShape content = sampleSlide2.getPlaceholder(1);        content.clearText(); // unset any existing text        content.addNewTextParagraph().addNewTextRun().setText("First paragraph");        content.addNewTextParagraph().addNewTextRun().setText("Second paragraph");        content.addNewTextParagraph().addNewTextRun().setText("Third paragraph");          // Creating 3rd slide - List        defaultLayout = defaultSlideMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);        XSLFSlide sampleSlide3 = samplePPT.createSlide(defaultLayout);        sampleTitle = sampleSlide3.getPlaceholder(0);        sampleTitle.clearText();        r = sampleTitle.addNewTextParagraph().addNewTextRun();        r.setText("List creations");          content = sampleSlide3.getPlaceholder(1);        content.clearText();        XSLFTextParagraph paragraph1 = content.addNewTextParagraph();        paragraph1.setIndentLevel(0);        paragraph1.setBullet(true);        r1 = paragraph1.addNewTextRun();        r1.setText("Bullet creations");          // the next three paragraphs form an auto-numbered list        XSLFTextParagraph paragraph2 = content.addNewTextParagraph();        paragraph2.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 1);        paragraph2.setIndentLevel(1);        XSLFTextRun r2 = paragraph2.addNewTextRun();        r2.setText("Numbered List Item - 1");          // Creating 4th slide        XSLFSlide sampleSlide4 = samplePPT.createSlide();        creationOfTable(sampleSlide4);          // Save presentation        FileOutputStream outputStream = newFileOutputStream(fileLocation);        samplePPT.write(outputStream);        outputStream.close();          // Closing presentation        samplePPT.close();    }      /**     * Delete a slide from the presentation     *     * @param pptFile     *            The presentation     * @param slideNumber     *            The number of the slide to be deleted (0-based)     */    publicvoiddeleteSlide(XMLSlideShow pptFile, intslideNumber) {        pptFile.removeSlide(slideNumber);    }      /**     * Re-order the slides inside a presentation     *     * @param pptFile     *            The presentation     * @param slideNumber     *            The number of the slide to move     * @param newSlideNumber     *            The new position of the slide (0-base)     */    publicvoidreorderSlide(XMLSlideShow pptFile, intslideNumber, intnewSlideNumber) {        List<XSLFSlide> slideList = pptFile.getSlides();          XSLFSlide secondSlide = slideList.get(slideNumber);        pptFile.setSlideOrder(secondSlide, newSlideNumber);    }      /**     * Retrieve the placeholder inside a slide     *     * @param slide     *          The slide     * @return List of placeholder inside a slide     */    publicList<XSLFShape> retrieveTemplatePlaceholders(XSLFSlide slide) {        List<XSLFShape> placeholders = newArrayList<>();          for(XSLFShape shape : slide.getShapes()) {            if(shape instanceofXSLFAutoShape) {                placeholders.add(shape);            }        }        returnplaceholders;    }      /**     * Create a table     *     * @param slide     *            Slide     */    privatevoidcreationOfTable(XSLFSlide slide) {          XSLFTable table = slide.createTable();        table.setAnchor(newRectangle(50, 50, 450, 300));          intnumColumns = 3;        intnumRows = 5;          // header        XSLFTableRow headerRow = table.addRow();        headerRow.setHeight(50);        for(inti = 0; i < numColumns; i++) {            XSLFTableCell th = headerRow.addCell();            XSLFTextParagraph p = th.addNewTextParagraph();            p.setTextAlign(TextParagraph.TextAlign.CENTER);            XSLFTextRun r = p.addNewTextRun();            r.setText("HeaderPart "+ (i + 1));            r.setBold(true);            r.setFontColor(Color.white);            th.setFillColor(newColor(79, 129, 189));            th.setBorderWidth(TableCell.BorderEdge.bottom, 2.0);            th.setBorderColor(TableCell.BorderEdge.bottom, Color.white);            // all columns are equally sized            table.setColumnWidth(i, 150);        }          // data        for(intrownum = 0; rownum < numRows; rownum++) {            XSLFTableRow tr = table.addRow();            tr.setHeight(50);            for(inti = 0; i < numColumns; i++) {                XSLFTableCell cell = tr.addCell();                XSLFTextParagraph p = cell.addNewTextParagraph();                XSLFTextRun r = p.addNewTextRun();                  r.setText("Data "+ (i * rownum + 1));                if(rownum % 2== 0) {                    cell.setFillColor(newColor(208, 216, 232));                } else{                    cell.setFillColor(newColor(233, 247, 244));                }            }        }    }} | 
We can able to get the presentation got created according to the code written and its contents are shown in the image below
 
Â
We can test the same by means of the below test file as well
PowerPointIntegrationTest.java
Java
| importorg.apache.poi.sl.usermodel.AutoNumberingScheme;importorg.apache.poi.sl.usermodel.PictureData;importorg.apache.poi.sl.usermodel.TableCell;importorg.apache.poi.sl.usermodel.TextParagraph;importorg.apache.poi.util.IOUtils;importorg.apache.poi.xslf.usermodel.SlideLayout;importorg.apache.poi.xslf.usermodel.XMLSlideShow;importorg.apache.poi.xslf.usermodel.XSLFAutoShape;importorg.apache.poi.xslf.usermodel.XSLFHyperlink;importorg.apache.poi.xslf.usermodel.XSLFPictureData;importorg.apache.poi.xslf.usermodel.XSLFPictureShape;importorg.apache.poi.xslf.usermodel.XSLFShape;importorg.apache.poi.xslf.usermodel.XSLFSlide;importorg.apache.poi.xslf.usermodel.XSLFSlideLayout;importorg.apache.poi.xslf.usermodel.XSLFSlideMaster;importorg.apache.poi.xslf.usermodel.XSLFTable;importorg.apache.poi.xslf.usermodel.XSLFTableCell;importorg.apache.poi.xslf.usermodel.XSLFTableRow;importorg.apache.poi.xslf.usermodel.XSLFTextParagraph;importorg.apache.poi.xslf.usermodel.XSLFTextRun;importorg.apache.poi.xslf.usermodel.XSLFTextShape;  importjava.awt.*;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.util.ArrayList;importjava.util.List;  // Helper class for the// PowerPoint presentation creationpublicclassPowerPointHelper {      /**     * Read an existing presentation     *     * @param fileLocation     *            File location of the presentation     * @return instance of {@link XMLSlideShow}     * @throws IOException     */    publicXMLSlideShow readWithExistingSlideShow(String fileLocation) throwsIOException {        returnnewXMLSlideShow(newFileInputStream(fileLocation));    }      /**     * Create a sample presentation     *     * @param fileLocation     *            File location of the presentation     * @throws IOException     */    publicvoidcreatingAPresentation(String fileLocation) throwsIOException {        // Create presentation        XMLSlideShow samplePPT = newXMLSlideShow();          XSLFSlideMaster defaultSlideMaster = samplePPT.getSlideMasters().get(0);          // Retrieving the slide layout        XSLFSlideLayout defaultLayout = defaultSlideMaster.getLayout(SlideLayout.TITLE_ONLY);          // Creating the 1st slide        XSLFSlide sampleSlide1 = samplePPT.createSlide(defaultLayout);        XSLFTextShape sampleTitle = sampleSlide1.getPlaceholder(0);        Â          // Clearing text to remove the          // predefined one in the template        sampleTitle.clearText();        XSLFTextParagraph paragraph = sampleTitle.addNewTextParagraph();          XSLFTextRun r1 = paragraph.addNewTextRun();        r1.setText("Lazyroar");        r1.setFontColor(newColor(78, 147, 89));        r1.setFontSize(48.);          // Add Image        ClassLoader classLoader = getClass().getClassLoader();        byte[] imageData = IOUtils.toByteArray(newFileInputStream(classLoader.getResource("gfglogo.png").getFile()));          XSLFPictureData pictureData = samplePPT.addPicture(imageData, PictureData.PictureType.PNG);        XSLFPictureShape picture = sampleSlide1.createPicture(pictureData);        picture.setAnchor(newRectangle(320, 230, 100, 92));          // Creating 2nd slide        defaultLayout = defaultSlideMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);        XSLFSlide sampleSlide2 = samplePPT.createSlide(defaultLayout);          // setting the tile        sampleTitle = sampleSlide2.getPlaceholder(0);        sampleTitle.clearText();        XSLFTextRun r = sampleTitle.addNewTextParagraph().addNewTextRun();        r.setText("Lazyroar");          // Adding the link        XSLFHyperlink hyperLink = r.createHyperlink();          // setting the content        XSLFTextShape content = sampleSlide2.getPlaceholder(1);        content.clearText(); // unset any existing text        content.addNewTextParagraph().addNewTextRun().setText("First paragraph");        content.addNewTextParagraph().addNewTextRun().setText("Second paragraph");        content.addNewTextParagraph().addNewTextRun().setText("Third paragraph");          // Creating 3rd slide - List        defaultLayout = defaultSlideMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);        XSLFSlide sampleSlide3 = samplePPT.createSlide(defaultLayout);        sampleTitle = sampleSlide3.getPlaceholder(0);        sampleTitle.clearText();        r = sampleTitle.addNewTextParagraph().addNewTextRun();        r.setText("List creations");          content = sampleSlide3.getPlaceholder(1);        content.clearText();        XSLFTextParagraph paragraph1 = content.addNewTextParagraph();        paragraph1.setIndentLevel(0);        paragraph1.setBullet(true);        r1 = paragraph1.addNewTextRun();        r1.setText("Bullet creations");          // the next three paragraphs form an auto-numbered list        XSLFTextParagraph paragraph2 = content.addNewTextParagraph();        paragraph2.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 1);        paragraph2.setIndentLevel(1);        XSLFTextRun r2 = paragraph2.addNewTextRun();        r2.setText("Numbered List Item - 1");          // Creating 4th slide        XSLFSlide sampleSlide4 = samplePPT.createSlide();        creationOfTable(sampleSlide4);          // Save presentation        FileOutputStream outputStream = newFileOutputStream(fileLocation);        samplePPT.write(outputStream);        outputStream.close();          // Closing presentation        samplePPT.close();    }      /**     * Delete a slide from the presentation     *     * @param pptFile     *            The presentation     * @param slideNumber     *            The number of the slide to be deleted (0-based)     */    publicvoiddeleteSlide(XMLSlideShow pptFile, intslideNumber) {        pptFile.removeSlide(slideNumber);    }      /**     * Re-order the slides inside a presentation     *     * @param pptFile     *            The presentation     * @param slideNumber     *            The number of the slide to move     * @param newSlideNumber     *            The new position of the slide (0-base)     */    publicvoidreorderSlide(XMLSlideShow pptFile, intslideNumber, intnewSlideNumber) {        List<XSLFSlide> slideList = pptFile.getSlides();          XSLFSlide secondSlide = slideList.get(slideNumber);        pptFile.setSlideOrder(secondSlide, newSlideNumber);    }      /**     * Retrieve the placeholder inside a slide     *     * @param slide     *          The slide     * @return List of placeholder inside a slide     */    publicList<XSLFShape> retrieveTemplatePlaceholders(XSLFSlide slide) {        List<XSLFShape> placeholders = newArrayList<>();          for(XSLFShape shape : slide.getShapes()) {            if(shape instanceofXSLFAutoShape) {                placeholders.add(shape);            }        }        returnplaceholders;    }      /**     * Create a table     *     * @param slide     *            Slide     */    privatevoidcreationOfTable(XSLFSlide slide) {          XSLFTable table = slide.createTable();        table.setAnchor(newRectangle(50, 50, 450, 300));          intnumColumns = 3;        intnumRows = 5;          // header        XSLFTableRow headerRow = table.addRow();        headerRow.setHeight(50);        for(inti = 0; i < numColumns; i++) {            XSLFTableCell th = headerRow.addCell();            XSLFTextParagraph p = th.addNewTextParagraph();            p.setTextAlign(TextParagraph.TextAlign.CENTER);            XSLFTextRun r = p.addNewTextRun();            r.setText("HeaderPart "+ (i + 1));            r.setBold(true);            r.setFontColor(Color.white);            th.setFillColor(newColor(79, 129, 189));            th.setBorderWidth(TableCell.BorderEdge.bottom, 2.0);            th.setBorderColor(TableCell.BorderEdge.bottom, Color.white);            // all columns are equally sized            table.setColumnWidth(i, 150);        }          // data        for(intrownum = 0; rownum < numRows; rownum++) {            XSLFTableRow tr = table.addRow();            tr.setHeight(50);            for(inti = 0; i < numColumns; i++) {                XSLFTableCell cell = tr.addCell();                XSLFTextParagraph p = cell.addNewTextParagraph();                XSLFTextRun r = p.addNewTextRun();                  r.setText("Data "+ (i * rownum + 1));                if(rownum % 2== 0) {                    cell.setFillColor(newColor(208, 216, 232));                } else{                    cell.setFillColor(newColor(233, 247, 244));                }            }        }    }} | 
Output of JUnit:
 
Â
Conclusion
We have seen the ways of creating of presentation, adding text, images, lists, etc to the presentation as well as altering the presentation as well. Apache POI API is a very useful and essential API that has to be used in software industries for working with the presentation.


 
                                    







