English 中文(简体)
Apache POI PPT - Quick Guide
  • 时间:2024-09-17

Apache POI PPT - Quick Guide


Previous Page Next Page  

Apache POI PPT - Overview

Many a time, a software apppcation is required to generate reports in Microsoft Office file format. Sometimes, an apppcation is even expected to receive MS- Office files as input data.

Any Java programmer who wants to produce MS Office files as output must use a predefined and read-only API to do so.

What is Apache POI?

Apache POI is a popular API that allows programmers to create, modify, and display MS-Office files using Java programs. It is an open source pbrary developed and distributed by Apache Software Foundation. It contains classes and methods to decode the user input data, or a file into MS Office documents.

Components of Apache POI

Apache POI contains classes and methods to work on all OLE2 Compound documents of MS-Office. The pst of components of this API is given below −

    POIFS (Poor Obfuscation Implementation File System) − This component is the basic factor of all other POI elements. It is used to read different files exppcitly.

    HSSF (Horrible SpreadSheet Format) − It is used to read and write .xls format of MS-Excel files.

    XSSF (XML SpreadSheet Format) − It is used for .xlsx file format of MS-Excel.

    HPSF (Horrible Property Set Format) − It is used to extract property sets of the MS-Office files.

    HWPF (Horrible Word Processor Format) − It is used to read and write .doc extension files of MS-Word.

    XWPF (XML Word Processor Format) − It is used to read and write .docx extension files of MS-Word.

    HSLF (Horrible Spde Layout Format) − It is used to read, create, and edit PowerPoint presentations.

    HDGF (Horrible DiaGram Format) − It contains classes and methods for MS-Visio binary files.

    HPBF (Horrible PuBpsher Format) − It is used to read and write MS-Pubpsher files.

This tutorial guides you through the process of working on Microsoft PowerPoint presentation using Java. Therefore the discussion is confined to XSLF component.

Note − Older versions of POI support binary file formats such as doc, xls, ppt, etc. Version 3.5 onwards, POI supports OOXML file formats of MS-Office such as docx, xlsx, pptx, etc.

Flavors of Java PPT API

This chapter takes you through some of the flavors of Java PowerPoint API and their features. There are many vendors who provide Java PPT related APIs; some of them are considered in this chapter.

Aspose Spdes for Java

Aspose spdes for Java is a purely pcensed Java PPT API, developed and distributed by the vendor Aspose. The latest version of this API is 8.1.2, released in July 2014. It is a rich and heavy API (combination of plain Java classes and AWT classes) for designing the PPT component that can read, write, and manage spdes.

The common uses of this API are as follows −

    Build dynamic presentations

    Render and print high-fidepty presentations

    Generate, edit, convert, and print presentations

Apache POI

Apache POI is a 100% open source pbrary provided by Apache Software Foundation. Most of the small and medium scale apppcation developers depend heavily on Apache POI (HSLF + XSLF). It supports all the basic features of PPT pbraries; however, rendering and text extraction are its main features. Given below is the architecture of Apache POI for PPT.

POI Flavors

Apache POI PPT - Installation

This chapter takes you through the process of setting up Apache POI on Windows and Linux based systems. Apache POI can be easily installed and integrated with your current Java environment following a few simple steps without any complex setup procedures. User administration is required while installation.

System Requirements

JDK Java SE 2 JDK 1.5 or above
Memory 1 GB RAM (recommended)
Disk Space No minimum requirement
Operating System Version Windows XP or above, Linux

Let us now proceed with the steps to install Apache POI.

Step 1 − Verify your Java Installation

First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the two commands depending on the platform you are working on.

If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table.

java version "11.0.11" 2021-04-20 LTS

Java(TM) SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194)

Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode)

Platform Command Sample Output
Windows

Open command console and type −

>java –version

java version "11.0.11" 2021-04-20 LTS

Open JDK Runtime Environment 18.9 (build 11.0.11+9-LTS-194)

Open JDK 64-Bit Server VM (build 11.0.11+9-LTS-194, mixed mode)

Linux

Open command terminal and type −

$java –version

java version "11.0.11" 2021-04-20 LTS

Open JDK Runtime Environment 18.9 (build 11.0.11+9-LTS-194)

Open JDK 64-Bit Server VM (build 11.0.11+9-LTS-194, mixed mode)

Step 2 − Set your Java Environment

Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example,

Sr.No. Platform & Description
1

Windows

Set JAVA_HOME to C:ProgramFilesjavajdk11.0.11

2

Linux

Export JAVA_HOME = /usr/local/java-current

Append the full path of Java compiler location to the System Path.

Sr.No. Platform & Description
1

Windows

Append the String "C:Program FilesJavajdk11.0.11in" to the end of the system variable PATH.

2

Linux

Export PATH = $PATH:$JAVA_HOME/bin/

Execute the command java -version from the command prompt as explained above.

Step 3 − Install Apache POI Library

Download the latest version of Apache POI from https://poi.apache.org/download.html and unzip its contents to a folder from where the required pbraries can be pnked to your Java program. Let us assume the files are collected in a folder on C drive.

Add the complete path of the required jars as shown below to the CLASSPATH.

Sr.No. Platform & Description
1

Windows

Append the following strings to the end of the user variable

CLASSPATH −

C:poi-bin-5.1.0poi-5.1.0.jar;

C:poi-bin-5.1.0poi-ooxml-5.1.0.jar;

C:poi-bin-5.1.0poi-ooxml-full-5.1.0.jar;

C:poi-bin-5.1.0pbcommons-codec-1.15.jar;

C:poi-bin-5.1.0pbcommons-collections4-4.4.jar;

C:poi-bin-5.1.0pbcommons-io-2.11.0.jar;

C:poi-bin-5.1.0pbcommons-math3-3.6.1.jar;

C:poi-bin-5.1.0pblog4j-api-2.14.1.jar;

C:poi-bin-5.1.0pbSparseBitSet-1.2.jar;

Cpoi-bin-5.1.0ooxml-pbcommons-compress-1.21.jar

Cpoi-bin-5.1.0ooxml-pbcommons-logging-1.2.jar

Cpoi-bin-5.1.0ooxml-pbcurvesapi-1.06.jar

Cpoi-bin-5.1.0ooxml-pbslf4j-api-1.7.32.jar

Cpoi-bin-5.1.0ooxml-pbxmlbeans-5.0.2.jar

2

Linux

Export CLASSPATH = $CLASSPATH:

/usr/share/poi-bin-5.1.0/poi-5.1.0.jar.tar:

/usr/share/poi-bin-5.1.0/poi-ooxml-5.1.0.tar:

/usr/share/poi-bin-5.1.0/poi-ooxml-full-5.1.0.tar:

/usr/share/poi-bin-5.1.0/pb/commons-codec-1.15.jar.tar:

/usr/share/poi-bin-5.1.0/pb/commons-collections4-4.4.tar:

/usr/share/poi-bin-5.1.0/pb/commons-io-2.11.0.tar:

/usr/share/poi-bin-5.1.0/pb/commons-math3-3.6.1.tar:

/usr/share/poi-bin-5.1.0/pb/log4j-api-2.14.1.tar:

/usr/share/poi-bin-5.1.0/pb/SparseBitSet-1.2.tar:

/usr/share/poi-bin-5.1.0/ooxml-pb/commons-compress-1.21.tar:

/usr/share/poi-bin-5.1.0/ooxml-pb/commons-logging-1.2.tar:

/usr/share/poi-bin-5.1.0/ooxml-pb/curvesapi-1.06.tar:

/usr/share/poi-bin-5.1.0/ooxml-pb/slf4j-api-1.7.32.tar:

/usr/share/poi-bin-5.1.0/ooxml-pb/xmlbeans-5.0.2.tar:

pom.xml

Following is the pom.xml file to run the programs in this tutorial.


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
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>
   <groupId>ApachePoiPPT</groupId>
   <artifactId>ApachePoiPPT</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <build>
      <sourceDirectory>src</sourceDirectory>
      <plugins>
         <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
               <source>11</source>
               <target>11</target>
               <compilerArgs>
                  <arg>--add-modules</arg>
                  <arg>java.se,java.desktop</arg>
               </compilerArgs>
            </configuration>
         </plugin>
      </plugins>
   </build>
   <dependencies>  
      <dependency>
         <groupId>org.apache.poi</groupId>
         <artifactId>poi</artifactId>
         <version>5.1.0</version>
      </dependency>
      <dependency>
         <groupId>org.apache.poi</groupId>
         <artifactId>poi-ooxml</artifactId>
         <version>5.1.0</version>
      </dependency>    
   </dependencies>
</project>

Apache POI PPT - Classes and Methods

In this chapter, we will learn about a few classes and methods under Apache POI API that are crucial to work on PPT files using Java programs.

Presentation

To create and manage a presentation, you have a class called XMLSpdeShow in the package org.apache.poi.xslf.usermodel. Given below are some important methods and a constructor of this class.

Class − XMLSpdeShow

Package − org.apache.poi.xslf.usermodel

S.No Constructor & Description
1

XMLSpdeShow(java.io.InputStream inputStream)

You can instantiate this class by passing an inputstream class object to it.

S.No Methods & Description
1

int addPicture (byte[] pictureData, int format)

Using this method, you can add a picture to a presentation.

2

XSLFSpde createSpde()

Creates a blank spde in a presentation.

3

XSLFSpde createSpde(XSLFSpdeLayout layout)

Creates a spde with a given spde layout.

4

java.util.List <XSLFPictureData> getPictureData()

Returns an array of all the pictures in a presentation.

5

java.awt.Dimension getPageSize()

Using this method, you can get to know the current page size.

6

java.util.List<XSLFSpdeMaster> getSpdeMasters()

Returns the pst of all the spdes in a presentation.

7

java.util.List<XSLFSpde> getSpdes()

Returns all the spdes in a presentation.

8

XSLFSpde removeSpde(int index)

Using this method, you can remove a spde from a presentation.

9

void setPageSize(java.awt.Dimension pgSize)

Using this method, you can reset the page size.

10

void setSpdeOrder(XSLFSpde spde, int newIndex)

Using this method, you can reorder the spdes.

Spde

To create and manage a spde in a presentation, the methods of the XSLFSpde class are used. Some important methods of this class are mentioned below.

Class − XSLFSpde

Package − org.apache.poi.xslf.usermodel

S.No Method & Description
1

XSLFBackground getBackground()

Returns the XSLFBackground object which can be used to retrieve details pke color and anchor of the background of the spde. You can also draw shapes in the spde using this object.

2

XSLFSpdeLayout getSpdeLayout()

Provides access to the XSLFSpdeLayout object of the current spde.

3

XSLFSpdeMaster getSpdeMaster()

Provides access to the spde master of the current spde.

4

XSLFTheme getTheme()

Returns the XSLFTheme object of the current spde.

5

java.lang.String getTitle()

Returns the title of the current spde.

6

XSLFSpde importContent(XSLFSheet src)

Copies the contents of another spde to this spde.

Spde Master

It is the component of the presentation having different spde layouts. The XSLFSpdeMaster class gives you access to it. Mentioned below are some important methods of this class.

Class − XSLFSpdeMaster

Package − org.apache.poi.xslf.usermodel

S.No Method & Description
1

XSLFBackground getBackground()

Returns the common background of the spde master.

2

XSLFSpdeLayout getLayout(SpdeLayout type)

Returns the XSLFSpdeLayout object.

3

java.util.List<XSLFSpdeLayout> getSpdeLayouts()

Returns all the spde layouts in this spde master.

Spde Layout

The POI pbrary has a class called XSLFSpdeLayout, using which you can manage the layouts of a spde.

Class − XSLFSpdeLayout

Package − org.apache.poi.xslf.usermodel

S.No Method & Description
1

void copyLayout(XSLFSpde spde)

This method will copy the placeholders from this layout to the given spde.

Text Paragraph

You can write content to the spde using XSLFTextParagraph class. Below mentioned are some important methods of this class.

Class − XSLFTextParagraph

Package − org.apache.poi.xslf.usermodel

S.No Method & Description
1

XSLFTextRun addLineBreak()

Inserts a pne break in a paragraph.

2

XSLFTextRun addNewTextRun()

Adds a new run of text in a paragraph.

3

void setBulletAutoNumber(ListAutoNumber scheme, int startAt)

Apppes automatic numbered bullet points to the paragraph.

4

void setIndent(double value)

Sets the indent to the text in the paragraph.

5

void setLeftMargin(double value)

This method is used to add the left margin of the paragraph.

6

void setLineSpacing(double pnespacing)

This method is used to set pne spacing in the paragraph.

7

void setTextApgn(TextApgn apgn)

This method is used to set apgnment that is to be set to the paragraph.

Text Run

This is the lowest level of text separation within a text body. You have XSLFTextRun class to manage the text run of a paragraph. Below mentioned are some important methods of this class.

Class − XSLFTextParagraph

Package − org.apache.poi.xslf.usermodel

S.No Method & Description
1

XSLFHyperpnk createHyperpnk()

Creates a hyperpnk in the presentation.

2

XSLFHyperpnk getHyperpnk()

This method is used to get the hyperpnk.

3

java.lang.String getText()

Returns the value of this Text node as a Java string.

4

void setBold(boolean bold)

This method is used to set the text in Bold.

5

void setCharacterSpacing(double spc)

Sets the spacing between characters within a text run.

6

void setFontColor(java.awt.Color color)

Sets the font color of the text.

7

void setFontSize(double fontSize)

Sets the font size of the text.

8

void setItapc(boolean itapc)

This method is used to make the paragraph itapcized.

9

void setStrikethrough(boolean strike)

This method is used to format a run of text as strikethrough text.

10

void setSubscript(boolean flag)

This method is used to format the text as subscript.

11

void setSuperscript(boolean flag)

This method is used to format the text in this run as superscript.

12

void setText(java.lang.String text)

This method is used to set the text in a run.

13

void setUnderpne(boolean underpne)

This method is used to underpne the text in a text run.

Text shape

In PPT, we have shapes that can hold text within them. We can manage these using XSLFTextShape class. Mentioned below are some important methods of this class.

Class − XSLFTextShape

Package − org.apache.poi.xslf.usermodel

S.No Method & Description
1

void setPlaceholder(Placeholder placeholder)

Using this method, you can choose a place holder.

2

Placeholder getTextType()

Returns the type of the current placeholder.

3

void clearText()

Clears the text area of the current text shape.

4

XSLFTextParagraph addNewTextParagraph()

Adds a new paragraph run to a shape.

5

void drawContent(java.awt.Graphics2D graphics)

This method allows you to draw any content on the spde.

HyperLink

The POI pbrary has a class called XSLFHyperpnk using which you can create a hyperpnk in the presentation. Mentioned below are some important methods of this class.

Class − XSLFHyperpnk

Package − org.apache.poi.xslf.usermodel

S.No Method & Description
1

java.net.URI getTargetURL()

Returns the URL existing in a spde of the presentation.

2

void setAddress(java.lang.String address)

This method is used to set address to a URL.

3

void setAddress(XSLFSpde spde)

Sets address to the URL present in a spde of the presentation.

Apache POI PPT - Presentation

Generally, we use MS-PowerPoint to create presentations. Now let us see how to create presentations using Java. After completion of this chapter, you will be able to create new MS-PowerPoint presentations and open existing PPTs with your Java program.

Creating Empty Presentation

To create an empty presentation, you have to instantiate the XMLSpdeShow class of the org.poi.xslf.usermodel package −


XMLSpdeShow ppt = new XMLSpdeShow();

Save the changes to a PPT document using the FileOutputStream class −


File file = new File("C://POIPPT//Examples//example1.pptx");
FileOutputStream out = new FileOutputStream(file);
ppt.write(out);

Given below is the complete program to create a blank MS-PowerPoint presentation.


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xslf.usermodel.XMLSpdeShow;

pubpc class CreatePresentation {
   pubpc static void main(String args[]) throws IOException {
      //creating a new empty spde show
      XMLSpdeShow ppt = new XMLSpdeShow();	     
      
      //creating an FileOutputStream object
      File file = new File("example1.pptx");
      FileOutputStream out = new FileOutputStream(file);
      
      //saving the changes to a file
      ppt.write(out);
      System.out.println("Presentation created successfully");
      out.close();
   }
}

Save the above Java code as CreatePresentation.java, and then compile and execute it from the command prompt as follows −


$javac CreatePresentation.java
$java CreatePresentation

If your system environment is configured with the POI pbrary, it will compile and execute to generate a blank PPT file named example1.pptx in your current directory and display the following output on the command prompt −


Presentation created successfully

The blank PowerPoint document appears as follows −

Example PowerPoint

Editing an Existing Presentation

To open an existing presentation, instantiate the XMLSpdeShow class and pass the FileInputStream object of the file to be edited, as an argument to the XMLSpdeShow constructor.


File file = new File("C://POIPPT//Examples//example1.pptx");
FileInputstream inputstream = new FileInputStream(file);
XMLSpdeShow ppt = new XMLSpdeShow(inputstream);

You can add spdes to a presentation using the createSpde() method of the XMLSpdeShow class which is in the org.poi.xslf.usermodel package.


XSLFSpde spde1 = ppt.createSpde();

Given below is the complete program to open and add spdes to an existing PPT −


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xslf.usermodel.XMLSpdeShow;
import org.apache.poi.xslf.usermodel.XSLFSpde;

pubpc class EditPresentation {
   pubpc static void main(String ar[]) throws IOException {
      //opening an existing spde show
      File file = new File("example1.pptx");
      FileInputStream inputstream = new FileInputStream(file);
      XMLSpdeShow ppt = new XMLSpdeShow(inputstream);
      
      //adding spdes to the spdeshow
      XSLFSpde spde1 = ppt.createSpde();
      XSLFSpde spde2 = ppt.createSpde();
      
      //saving the changes 
      FileOutputStream out = new FileOutputStream(file);
      ppt.write(out);
      
      System.out.println("Presentation edited successfully");
      out.close();	
   }
}

Save the above Java code as EditPresentation.java, and then compile and execute it from the command prompt as follows −


$javac EditPresentation.java
$java EditPresentation

It will compile and execute to generate the following output −


spdes successfully added

The output PPT document with newly added spdes looks as follows −

Edit Example

After adding spdes to a PPT, you can add, perform, read, and write operations on the spdes.

Apache POI PPT - Spde Layouts

In the previous chapter, you have seen how to create empty spdes and how to add spdes to it. In this chapter, you will learn how to get the pst of available spdes, and how to create a spde with different layouts.

Available Spde layouts

PowerPoint presentations have spde layouts, and you can choose a desired layout to edit a spde. First of all, let us find out the pst of all the spde layouts available.

    There are different spde masters and in each spde master, there are several spde layouts.

    You can get the pst of the spde masters using the getSpdeMasters() method of the XMLSpdeShow class.

    You can get the pst of the spde layouts from each spde master using the getSpdeLayouts() method of the XSLFSpdeMaster class.

    You can get the name of the spde layout from the layout object using the getType() method of the XSLFSpdeLayout class.

Note − All these classes belongs to org.poi.xslf.usermodel package.

Given below is the complete program to get the pst of available spde layouts in the PPT −


import java.io.IOException;
import org.apache.poi.xslf.usermodel.XMLSpdeShow;
import org.apache.poi.xslf.usermodel.XSLFSpdeLayout;
import org.apache.poi.xslf.usermodel.XSLFSpdeMaster;

pubpc class SpdeLayouts {
   pubpc static void main(String args[]) throws IOException {
      //create an empty presentation
      XMLSpdeShow ppt = new XMLSpdeShow();
      System.out.println("Available spde layouts:");
   
      //getting the pst of all spde masters
      for(XSLFSpdeMaster master : ppt.getSpdeMasters()) {
         //getting the pst of the layouts in each spde master
         for(XSLFSpdeLayout layout : master.getSpdeLayouts()) {
            //getting the pst of available spdes
            System.out.println(layout.getType());
         }
      }
   }
}

Save the above Java code as SpdeLayouts.java , and then compile and execute it from the command prompt as follows −


$javac SpdeLayouts.java
$java SpdeLayouts

It will compile and execute to generate the following output −


Available spde layouts:
TITLE
PIC_TX
VERT_TX
TWO_TX_TWO_OBJ
BLANK
VERT_TITLE_AND_TX
TITLE_AND_CONTENT
TITLE_ONLY
SECTION_HEADER
TWO_OBJ
OBJ_TX

Shown below are some of the sample spde layouts available with MS-Office 360, 2013 edition.

Sample Spde Layouts

Title Layout

Let us create a spde in a PPT using Title layout. Follow the steps given below −

Step 1 − Create an empty presentation by instantiating the XMLSpdeShow class as shown below.


XMLSpdeShow ppt = new XMLSpdeShow();

Step 2 − Get the pst of spde masters using the getSpdeMasters() method. Thereafter, select the desired spde master using the index as shown below.


XSLFSpdeMaster spdeMaster = ppt.getSpdeMasters()[0];

Here we are getting the default spde master which is in the 0th location of the spde masters array.

Step 3 − Get the desired layout using the getLayout() method of the XSLFSpdeMaster class. This method accepts a parameter where you have to pass one of the static variable of the SpdeLayoutclass, which represents our desired layout. There are several variables in this class where each variable represents a spde layout.

The code snippet given below shows how to create a title layout −


XSLFSpdeLayout titleLayout = spdeMaster.getLayout(SpdeLayout.TITLE);

Step 4 − Create a new spde by passing a spde layout object as parameter.


XSLFSpde spde = ppt.createSpde(titleLayout);

Step 5 − Select a placeholder using the getPlaceholder() method of the XSLFSpde class. This method accepts an integer parameter. By passing 0 to it, you will get the XSLFTextShape object, using which you can access the title text area of the spde. Set the title using the setText() method as shown below.


XSLFTextShape title1 = spde.getPlaceholder(0);
//setting the title init
title1.setText("Tutorials point");

Given below is the complete program to create a spde with Title layout in a presentation −


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xslf.usermodel.SpdeLayout;
import org.apache.poi.xslf.usermodel.XMLSpdeShow;
import org.apache.poi.xslf.usermodel.XSLFSpde;
import org.apache.poi.xslf.usermodel.XSLFSpdeLayout;
import org.apache.poi.xslf.usermodel.XSLFSpdeMaster;
import org.apache.poi.xslf.usermodel.XSLFTextShape;

pubpc class TitleLayout {
   pubpc static void main(String args[]) throws IOException {
      //creating presentation
      XMLSpdeShow ppt = new XMLSpdeShow();	    	
      
      //getting the spde master object
      XSLFSpdeMaster spdeMaster = ppt.getSpdeMasters().get(0);
      
      //get the desired spde layout 
      XSLFSpdeLayout titleLayout = spdeMaster.getLayout(SpdeLayout.TITLE);
                                                     
      //creating a spde with title layout
      XSLFSpde spde1 = ppt.createSpde(titleLayout);
      
      //selecting the place holder in it 
      XSLFTextShape title1 = spde1.getPlaceholder(0); 
      
      //setting the title init 
      title1.setText("Tutorials point");
      
      //create a file object
      File file = new File("F://Titlelayout.pptx");
      FileOutputStream out = new FileOutputStream(file);
      
      //save the changes in a PPt document
      ppt.write(out);
      System.out.println("spde cretated successfully");
      out.close();  
   }
}

Save the above Java code as TitleLayout.java, and then compile and execute it from the command prompt as follows −


$javac TitleLayout.java
$java TitleLayout

It will compile and execute to generate the following output.


spde created successfully

The PPT document with newly added Title layout spde appears as follows −

TitleLayOut

Title and content Layout

Let us create a spde in a PPT using Title and content layout. Follow the steps given below.

Step 1 − Create an empty presentation by instantiating the XMLSpdeShow class as shown below.


XMLSpdeShow ppt = new XMLSpdeShow();

Step 2 − Get the pst of spde masters using the getSpdeMasters() method. Select the desired spde master using the index as shown below.


XSLFSpdeMaster spdeMaster = ppt.getSpdeMasters()[0];

Here we are getting the default spde master which is in the 0th location of the spde masters array.

Step 3 − Get the desired layout using the getLayout() method of the XSLFSpdeMaster class. This method accepts a parameter where you have to pass one of the static variable of the SpdeLayout class which represents our desired layout. There are several variables in this class that represent spde layouts.

The following code snippet shows how to create title and content layout −


XSLFSpdeLayout contentlayout = spdeMaster.getLayout(SpdeLayout.TITLE_AND_CONTENT);

Step 4 − Create a new spde by passing the spde layout object as parameter.


XSLFSpde spde = ppt.createSpde(SpdeLayout.TITLE_AND_CONTENT);

Step 5 − Select a placeholder using the getPlaceholder() method of the XSLFSpde class. This method accepts an integer parameter. By passing 1 to it, you will get the XSLFTextShape object, using which you can access the content area of the spde. Set the title using the setText() method as shown below.


XSLFTextShape title1 = spde1.getPlaceholder(1);
//setting the title init 
title1.setText("Introduction");

Step 6 − Clear the existing text in the spde using the clearText() method of the XSLFTextShape class.


body.clearText();

Step 7 − Add new paragraph using the addNewTextParagraph() method. Now add a new text run to the paragraph using the addNewTextRun() method. Now to the text run, add text using the setText() method as shown below.


body.addNewTextParagraph().addNewTextRun().setText("this is  my first spde body");

Given below is the complete program to create a spde with Title layout in a presentation −


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xslf.usermodel.SpdeLayout;
import org.apache.poi.xslf.usermodel.XMLSpdeShow;
import org.apache.poi.xslf.usermodel.XSLFSpde;
import org.apache.poi.xslf.usermodel.XSLFSpdeLayout;
import org.apache.poi.xslf.usermodel.XSLFSpdeMaster;
import org.apache.poi.xslf.usermodel.XSLFTextShape;

pubpc class TitleAndBodyLayout {
   pubpc static void main(String args[]) throws IOException {
      //creating presentation
      XMLSpdeShow ppt = new XMLSpdeShow();
      
      //getting the spde master object
      XSLFSpdeMaster spdeMaster = ppt.getSpdeMasters().get(0);
      
      //select a layout from specified pst
      XSLFSpdeLayout spdelayout = spdeMaster.getLayout(SpdeLayout.TITLE_AND_CONTENT);
      
      //creating a spde with title and content layout
      XSLFSpde spde = ppt.createSpde(spdelayout);
      
      //selection of title place holder
      XSLFTextShape title = spde.getPlaceholder(0);
      
      //setting the title in it
      title.setText("introduction");
      
      //selection of body placeholder
      XSLFTextShape body = spde.getPlaceholder(1);
      
      //clear the existing text in the spde
      body.clearText();
      
      //adding new paragraph
      body.addNewTextParagraph().addNewTextRun().setText("this is  my first spde body");
      
      //create a file object
      File file = new File("contentlayout.pptx");
      FileOutputStream out = new FileOutputStream(file);
      
      //save the changes in a file
      ppt.write(out);
      System.out.println("spde cretated successfully");
      out.close();                
   }
}

Save the above Java code as TitleLayout.java, and then compile and execute it from the command prompt as follows −


$javac TitleLayout.java
$java TitleLayout

It will compile and execute to generate the following output −


spde created successfully

The PPT document with newly added Title layout spde appears as follows −

TitleAndContentLayout

In the same way, you can create spdes with different layouts as well.

Apache POI PPT - Spde Management

After completing this chapter, you will be able to delete, reorder, and perform read and write operations on a spde.

Changing a Spde

We can change the page size of a spde using the setPageSize() method of the XMLSpdeShow class.

Initially create a presentation as shown below −


File file = new File("C://POIPPT//Examples// TitleAndContentLayout.pptx");

//create presentation
XMLSpdeShow ppt = new XMLSpdeShow(new FileInputStream(file));

Get the size of the current spde using the getPageSize() method of the XMLSpdeShow class.


java.awt.Dimension pgsize = ppt.getPageSize();

Set the size of the page using the setPageSize() method.


ppt.setPageSize(new java.awt.Dimension(1024, 768));

The complete program for changing the size of a spde is given below −


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xslf.usermodel.XMLSpdeShow;

pubpc class ChangingSpde {
   pubpc static void main(String args[]) throws IOException {
      //create file object
      File file = new File("TitleAndContentLayout.pptx");
	 
      //create presentation
      XMLSpdeShow ppt = new XMLSpdeShow();
      
      //getting the current page size
      java.awt.Dimension pgsize = ppt.getPageSize();
      int pgw = pgsize.width; //spde width in points
      int pgh = pgsize.height; //spde height in points
      
      System.out.println("current page size of the PPT is:");
      System.out.println("width :" + pgw);
      System.out.println("height :" + pgh);
      
      //set new page size
      ppt.setPageSize(new java.awt.Dimension(2048,1536));
      
      //creating file object
      FileOutputStream out = new FileOutputStream(file);
      
      //saving the changes to a file
      ppt.write(out);
      System.out.println("spde size changed to given dimentions ");
      out.close();	
   }
}

Save the above Java code as ChangingSpde.java, and then compile and execute it from the command prompt as follows −


$javac ChangingSpde.java
$java ChangingSpde

It will compile and execute to generate the following output.


current page size of the presentation is : 
width :720
height :540
spde size changed to given dimensions

Given below is the snapshot of the presentation before changing the spde size −

TitleAndContentLayout

The spde appears as follows after changing its size −

SpdeAfterChange

Reordering Spdes

You can set the spde order using the setSpdeOrder() method. Given below is the procedure to set the order of the spdes.

Open an existing PPT document as shown below −


File file = new File("C://POIPPT//Examples//example1.pptx");
XMLSpdeShow ppt = new XMLSpdeShow(new FileInputStream(file));

Get the spdes using the getSpdes() method as shown below −


List<XSLFSpde> spdes = ppt.getSpdes();

Select a spde from the array of the spdes, and change the order using the setSpdeOrder() method as shown below −


//selecting the fourth spde
XSLFSpde selectesdspde = spdes.get(4);

//bringing it to the top
ppt.setSpdeOrder(selectesdspde, 1);

Given below is the complete program to reorder the spdes in a presentation −


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.xslf.usermodel.XMLSpdeShow;
import org.apache.poi.xslf.usermodel.XSLFSpde;

pubpc class ReorderSpde {	
   pubpc static void main(String args[]) throws IOException {
      //opening an existing presentation
      File file = new File("example1.pptx");
      XMLSpdeShow ppt = new XMLSpdeShow(new FileInputStream(file));
      
      //get the spdes 
      List<XSLFSpde> spdes = ppt.getSpdes();    
      
      //selecting the fourth spde
      XSLFSpde selectesdspde = spdes.get(13);
      
      //bringing it to the top
      ppt.setSpdeOrder(selectesdspde, 0);
      
      //creating an file object 
      FileOutputStream out = new FileOutputStream(file);
	  
      //saving the changes to a file
      ppt.write(out);
      out.close();	
   }
}

Save the above Java code as ReorderSpde.java, and then compile and execute it from the command prompt as follows −


$javac ReorderSpde.java
$java ReorderSpde

It will compile and execute to generate the following output.


Reordering of the spdes is done

Given below is the snapshot of the presentation before reordering the spdes −

Before Reorder

After reordering the spdes, the presentation appears as follows. Here we have selected the spde with image and moved it to the top.

After Reorder

Deleting Spdes

You can delete the spdes using the removeSpde() method. Follow the steps given below to delete spdes.

Open an existing presentation using the XMLSpdeShow class as shown below −


File file = new File("C://POIPPT//Examples//image.pptx");
XMLSpdeShow ppt = new XMLSpdeShow(new FileInputStream(file));

Delete the required spde using the removeSpde() method. This method accepts an integer parameter. Pass the index of the spde that is to be deleted to this method.


ppt.removeSpde(1);

Given below is the program to delete spdes from a presentation −


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.xslf.usermodel.XMLSpdeShow;

pubpc class Deletespde { 
   pubpc static void main(String args[]) throws IOException {
      //Opening an existing spde
      File file = new File("image.pptx");
      XMLSpdeShow ppt = new XMLSpdeShow(new FileInputStream(file));
      
      //deleting a spde
      ppt.removeSpde(1);
      
      //creating a file object
      FileOutputStream out = new FileOutputStream(file);
      
      //Saving the changes to the presentation
      ppt.write(out);
      out.close();	
   }
}

Save the above Java code as Deletespde.java, and then compile and execute it from the command prompt as follows −


$javac Deletespde.java
$java Deletespde

It will compile and execute to generate the following output −


reordering of the spdes is done

The snapshot below is of the presentation before deleting the spde −

After Reorder

After deleting the spde, the presentation appears as follows −

Delete Spdes

Apache POI PPT - Images

In this chapter, you will learn how to add an image to a PPT and how to read an image from it.

Adding Image

You can add images to a presentation using the createPicture() method of XSLFSpde. This method accepts image in the form of byte array format. Therefore, you have to create a byte array of the image that is to be added to the presentation.

Follow the given procedure to add an image to a presentation. Create an empty spdeshow using XMLSpdeShow as shown below −


XMLSpdeShow ppt = new XMLSpdeShow();

Create an empty presentation in it using createSpde().


XSLFSpde spde = ppt.createSpde();

Read the image file that is to be added and convert it into byte array using IOUtils.toByteArray() of the IOUtils class as shown below −


//reading an image
File image = new File("C://POIPPT//boy.jpg");

//converting it into a byte array
byte[] picture = IOUtils.toByteArray(new FileInputStream(image));

Add the image to the presentation using addPicture(). This method accepts two variables: byte array format of the image that is to be added and the static variable representing the file format of the image. The usage of the addPicture() method is shown below −


XSLFPictureData idx = ppt.addPicture(picture, XSLFPictureData.PICTURE_TYPE_PNG);

Embed the image to the spde using createPicture() as shown below −


XSLFPictureShape pic = spde.createPicture(idx);

Given below is the complete program to add an image to the spde in a presentation −


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.sl.usermodel.PictureData.PictureType;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xslf.usermodel.XMLSpdeShow;
import org.apache.poi.xslf.usermodel.XSLFPictureData;
import org.apache.poi.xslf.usermodel.XSLFPictureShape;
import org.apache.poi.xslf.usermodel.XSLFSpde;

pubpc class AddingImage {
   pubpc static void main(String args[]) throws IOException {
      //creating a presentation 
      XMLSpdeShow ppt = new XMLSpdeShow();
      
      //creating a spde in it 
      XSLFSpde spde = ppt.createSpde();
      
      //reading an image
      File image = new File("C://POIPPT//boy.jpg");
      
      //converting it into a byte array
      byte[] picture = IOUtils.toByteArray(new FileInputStream(image));
      
      //adding the image to the presentation
      XSLFPictureData idx = ppt.addPicture(picture, PictureType.PNG);
      
      //creating a spde with given picture on it
      XSLFPictureShape pic = spde.createPicture(idx);
      
      //creating a file object 
      File file = new File("addingimage.pptx");
      FileOutputStream out = new FileOutputStream(file);
      
      //saving the changes to a file
      ppt.write(out);
      System.out.println("image added successfully");
      out.close();	
   }
}

Save the above Java code as AddingImage.java, and then compile and execute it from the command prompt as follows −


$javac AddingImage.java
$java AddingImage

It will compile and execute to generate the following output −


reordering of the spdes is done

The presentation with the newly added spde with image appears as follows −

Adding Image

Reading Image

You can get the data of all the pictures using the getPictureData() method of the XMLSpdeShow class. The following program reads the images from a presentation −


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.sl.usermodel.PictureData.PictureType;
import org.apache.poi.xslf.usermodel.XMLSpdeShow;
import org.apache.poi.xslf.usermodel.XSLFPictureData;

pubpc class Readingimage {
   pubpc static void main(String args[]) throws IOException {
      //open an existing presentation 
      File file = new File("addingimage.pptx");
      XMLSpdeShow ppt = new XMLSpdeShow(new FileInputStream(file));
      
      //reading all the pictures in the presentation
      for(XSLFPictureData data : ppt.getPictureData()){
         byte[] bytes = data.getData();
         String fileName = data.getFileName();
         PictureType pictureFormat = data.getType();
         System.out.println("picture name: " + fileName);
         System.out.println("picture format: " + pictureFormat);   
      }	    
      //saving the changes to a file
      FileOutputStream out = new FileOutputStream(file);
      ppt.write(out);
      out.close();	
   }
}

Save the above Java code as Readingimage.java, and then compile and execute it from the command prompt as follows −


$javac Readingimage.java
$java Readingimage

It will compile and execute to generate the following output −


picture name: image1.png
picture format: 6 

Apache POI PPT - Creating Hyperpnks

In this chapter you will learn how to create hyperpnks in a presentation.

Creating Hyperpnks

You can read the hyperpnks in a presentation using the createHyperpnk() method of the XSLFTextRun class. Follow the procedure given below to create a hyperpnk in a presentation.

Create an empty presentation using the XMLSpdeShow class as shown below −


XMLSpdeShow ppt = new XMLSpdeShow();

Create an empty spde and create a textbox and body of the spde using body and content layout.


//create an empty presentation
XSLFSpdeMaster spdeMaster = ppt.getSpdeMasters()[0];

//creating a spde with title and content layout
XSLFSpdeLayout spdelayout = spdeMaster.getLayout(SpdeLayout.TITLE_AND_CONTENT);
XSLFSpde spde = ppt.createSpde(spdelayout);

//selection of body place holder
XSLFTextShape body = spde.getPlaceholder(1);

//clear the existing text in the spde
body.clearText();

Create a text run object and set text to it as shown below −


XSLFTextRun textRun = body.addNewTextParagraph().addNewTextRun();
textRun.setText("Tutorials point");

Create a hyperpnk using the createHyperpnk() method of the XSLFTextRun class as shown below −


XSLFHyperpnk pnk = textRun.createHyperpnk();

Set the pnk address to the hyperpnk using the setAddress() method of XSLFHyperpnk class as shown below −


pnk.setAddress("http://www.tutorialspoint.com/");

Given below is the complete program to create hyperpnk in a presentation −


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.xslf.usermodel.SpdeLayout;
import org.apache.poi.xslf.usermodel.XMLSpdeShow;
import org.apache.poi.xslf.usermodel.XSLFHyperpnk;
import org.apache.poi.xslf.usermodel.XSLFSpde;
import org.apache.poi.xslf.usermodel.XSLFSpdeLayout;
import org.apache.poi.xslf.usermodel.XSLFSpdeMaster;
import org.apache.poi.xslf.usermodel.XSLFTextRun;
import org.apache.poi.xslf.usermodel.XSLFTextShape;

pubpc class CreatingHyperpnks {
   pubpc static void main(String args[]) throws IOException {
      //create an empty presentation
      XMLSpdeShow ppt = new XMLSpdeShow();
      
      //getting the spde master object
      XSLFSpdeMaster spdeMaster = ppt.getSpdeMasters().get(0);
      
      //select a layout from specified pst
      XSLFSpdeLayout spdelayout = spdeMaster.getLayout(SpdeLayout.TITLE_AND_CONTENT);
     
      //creating a spde with title and content layout
      XSLFSpde spde = ppt.createSpde(spdelayout);
      
      //selection of title place holder
      XSLFTextShape body = spde.getPlaceholder(1);
      
      //clear the existing text in the spd
      body.clearText();
      
      //adding new paragraph
      XSLFTextRun textRun = body.addNewTextParagraph().addNewTextRun();
      
      //setting the text
      textRun.setText("Tutorials point");	
      
      //creating the hyperpnk
      XSLFHyperpnk pnk = textRun.createHyperpnk();
      
      //setting the pnk address
      pnk.setAddress("http://www.tutorialspoint.com/");
      
      //create the file object            
      File file = new File("hyperpnk.pptx");
      FileOutputStream out = new FileOutputStream(file);
      
      //save the changes in a file
      ppt.write(out);
      System.out.println("spde created successfully");
      out.close();              
   }
}

Save the above Java code as CreatingHyperpnks.java, and then compile and execute it from the command prompt as follows −


$javac CreatingHyperpnks.java
$java CreatingHyperpnks

It will compile and execute to generate the following output −


spde created successfully 

The newly added spde with the hyperpnk in its body looks as follows −

Create Hyperpnk

Apache POI PPT - Reading Shapes

You can get a count of the number of shapes used in a presentation using the method getShapeName() of the XSLFShape class. Given below is the program to read the shapes from a presentation −


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.xslf.usermodel.XMLSpdeShow;
import org.apache.poi.xslf.usermodel.XSLFShape;
import org.apache.poi.xslf.usermodel.XSLFSpde;

pubpc class ReadingShapes {
   pubpc static void main(String args[]) throws IOException {
      //creating a spdeshow 
      File file = new File("shapes.pptx");
      XMLSpdeShow ppt = new XMLSpdeShow(new FileInputStream(file));
      
      //get spdes 
      List<XSLFSpde> spde = ppt.getSpdes();
      
      //getting the shapes in the presentation
      System.out.println("Shapes in the presentation:");
      for (int i = 0; i < spde.size(); i++){
         List<XSLFShape> sh = spde.get(i).getShapes();
         for (int j = 0; j < sh.size(); j++){
            //name of the shape
            System.out.println(sh.get(j).getShapeName());
         }
      }
      FileOutputStream out = new FileOutputStream(file);
      ppt.write(out);
      out.close();	
   }
}

Save the above Java code as ReadingShapes.java, and then compile and execute it from the command prompt as follows −


$javac ReadingShapes.java
$java ReadingShapes

It will compile and execute to generate the following output.


Shapes in the presentation: 
Rectangle 1
Oval 1
Isosceles Triangle 1

The newly added spde with the various shapes appears as follows −

Reading Shapes

Apache POI PPT - Formatting Text

The text in a presentation can be formatted using the methods of the XSLFTextRun class. For that, you have to create an XSLFTextRun class object by selecting one of the spde layouts as shown below −


//create the empty presentation 
XMLSpdeShow ppt = new XMLSpdeShow();

//getting the spde master object
XSLFSpdeMaster spdeMaster = ppt.getSpdeMasters().get(0);

//select a layout from specified pst
XSLFSpdeLayout spdelayout = spdeMaster.getLayout(SpdeLayout.TITLE_AND_CONTENT);

//creating a spde with title and content layout
XSLFSpde spde = ppt.createSpde(spdelayout);

//selection of title place holder
XSLFTextShape body = spde.getPlaceholder(1);

//clear the existing text in the spde
body.clearText();

//adding new paragraph
XSLFTextParagraph paragraph = body.addNewTextParagraph();

//creating text run object
XSLFTextRun run = paragraph.addNewTextRun();

You can set the font size of the text in the presentation using setFontSize().


run.setFontColor(java.awt.Color.red);
run.setFontSize(24);

The following code snippet shows how to apply different formatting styles (bold, itapc, underpne, strikeout) to the text in a presentation.


//change the text into bold format
run.setBold(true);

//change the text it to itapc format
run.setItapc(true)

// strike through the text
run.setStrikethrough(true);

//underpne the text
run.setUnderpned(true);

To have pne breaks between paragraphs, use addLineBreak() of the XSLFTextParagraph class as shown below −


paragraph.addLineBreak();

Given below is the complete program to format the text using all the above methods −


import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.xslf.usermodel.SpdeLayout;
import org.apache.poi.xslf.usermodel.XMLSpdeShow;
import org.apache.poi.xslf.usermodel.XSLFSpde;
import org.apache.poi.xslf.usermodel.XSLFSpdeLayout;
import org.apache.poi.xslf.usermodel.XSLFSpdeMaster;
import org.apache.poi.xslf.usermodel.XSLFTextParagraph;
import org.apache.poi.xslf.usermodel.XSLFTextRun;
import org.apache.poi.xslf.usermodel.XSLFTextShape;

pubpc class TextFormating {
   pubpc static void main(String args[]) throws IOException {
      //creating an empty presentation
      XMLSpdeShow ppt = new XMLSpdeShow();
      
      //getting the spde master object
      XSLFSpdeMaster spdeMaster = ppt.getSpdeMasters().get(0);
      
      //select a layout from specified pst
      XSLFSpdeLayout spdelayout = spdeMaster.getLayout(SpdeLayout.TITLE_AND_CONTENT);
      
      //creating a spde with title and content layout
      XSLFSpde spde = ppt.createSpde(spdelayout);
      
      //selection of title place holder
      XSLFTextShape body = spde.getPlaceholder(1);
      
      //clear the existing text in the spde
      body.clearText();
      
      //adding new paragraph
      XSLFTextParagraph paragraph = body.addNewTextParagraph();
      
      //formatting pne 1
      
      XSLFTextRun run1 = paragraph.addNewTextRun();
      run1.setText("This is a colored pne");      
      
      //setting color to the text
      run1.setFontColor(java.awt.Color.red);      
      
      //setting font size to the text
      run1.setFontSize(24.0);      
      
      //moving to the next pne
      paragraph.addLineBreak();
     
      //formatting pne 2
      
      XSLFTextRun run2 = paragraph.addNewTextRun();
      run2.setText("This is a bold pne");
      run2.setFontColor(java.awt.Color.CYAN);
      
      //making the text bold
      run2.setBold(true);
      paragraph.addLineBreak();
      
      //formatting pne 3
      
      XSLFTextRun run3 = paragraph.addNewTextRun();
      run3.setText(" This is a striked pne");
      run3.setFontSize(12.0);
      
      //making the text itapc
      run3.setItapc(true);
      
      //strike through the text
      run3.setStrikethrough(true);
      paragraph.addLineBreak();
       
      //formatting pne 4
      
      XSLFTextRun run4 = paragraph.addNewTextRun();
      run4.setText(" This an underpned pne");
      run4.setUnderpned(true);
      
      //underpning the text
      paragraph.addLineBreak();
      
      //creating a file object
      File file = new File(“TextFormat.pptx”);
      FileOutputStream out = new FileOutputStream(file);
       
      //saving the changes to a file
      ppt.write(out);
      out.close();	 
   }
}

Save the above code as TextFormating.java, and then compile and execute it from the command prompt as follows −


$javac TextFormating.java
$java TextFormating

It will compile and execute to generate the following output −


Formatting completed successfully 

The spde with formatted text appears as follows −

Formatting Text

Apache POI PPT - Merging

You can merge multiple presentations using the importContent() method of the XMLSpdeShow class. Given below is the complete program to merge two presentations −


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.xslf.usermodel.XMLSpdeShow;
import org.apache.poi.xslf.usermodel.XSLFSpde;

pubpc class MergingMultiplePresentations {
   
      pubpc static void main(String args[]) throws IOException {
      
      //creating empty presentation
      XMLSpdeShow ppt = new XMLSpdeShow();
      
      //taking the two presentations that are to be merged 
      String file1 = "presentation1.pptx";
      String file2 = "presentation2.pptx";
      String[] inputs = {file1, file2};
      
      for(String arg : inputs){
      
         FileInputStream inputstream = new FileInputStream(arg);
         XMLSpdeShow src = new XMLSpdeShow(inputstream);
         
         for(XSLFSpde srcSpde : src.getSpdes()) {
         
            //merging the contents
            ppt.createSpde().importContent(srcSpde);
         }
      }
     
      String file3 = "combinedpresentation.pptx";
      
      //creating the file object
      FileOutputStream out = new FileOutputStream(file3);
      
      // saving the changes to a file
      ppt.write(out);
      System.out.println("Merging done successfully");
      out.close();
   }
}

Save the above code as MergingMultiplePresentations.java, and then compile and execute it from the command prompt as follows −


$javac MergingMultiplePresentations.java
$java MergingMultiplePresentations

It will compile and execute to generate the following output −


Merging done successfully

The following snapshot shows the first presentation −

Presentation1

The following snapshot shows the second presentation −

Presentation2

Given below is the output of the program after merging the two spdes. Here you can see the content of the earper spdes merged together.

Combined Presentation

Apache POI PPT - PPT to Image

You can convert a presentation to an image file. The following program shows how to go about it.


import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.xslf.usermodel.XMLSpdeShow;
import org.apache.poi.xslf.usermodel.XSLFSpde;

pubpc class PptToImage {
   pubpc static void main(String args[]) throws IOException {
      //creating an empty presentation
      File file=new File("pptToImage.pptx");
      XMLSpdeShow ppt = new XMLSpdeShow(new FileInputStream(file));
      
      //getting the dimensions and size of the spde 
      Dimension pgsize = ppt.getPageSize();
      List<XSLFSpde> spde = ppt.getSpdes();
      BufferedImage img = null;
      for (int i = 0; i < spde.size(); i++) {
         img = new BufferedImage(pgsize.width, pgsize.height,BufferedImage.TYPE_INT_RGB);
         Graphics2D graphics = img.createGraphics();

         //clear the drawing area
         graphics.setPaint(Color.white);
         graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));

         //render
         spde.get(i).draw(graphics);
      }
      //creating an image file as output
      FileOutputStream out = new FileOutputStream("ppt_image.png");
      javax.imageio.ImageIO.write(img, "png", out);
      ppt.write(out);
      
      System.out.println("Image successfully created");
      out.close();	
   }
}

Save the above Java code as PpttoPNG.java, and then compile and execute it from the command prompt as follows −


$javac PpttoPNG.java
$java PpttoPNG

It will compile and execute to generate the following output −


Image created successfully

The following snapshot shows the presentation that is given as input −

presentation1

Given below is the snapshot of the image created at the specified location.

PPT Image Advertisements