Merge or Split PowerPoint Presentations in Java

When working with PowerPoint Presentations, you may need to merge several presentations into one or split a large presentation into smaller ones. In this article, I will introduce how to merge or split PowerPoint Presentations in Java using Spire.Presentation for Java.

Add Dependencies

Method 1. If you are using maven, you can install the jar of Spire.Presentation for Java into your project by adding the following code to your project’s pom.xml file.

<repositories>   
    <repository>   
        <id>com.e-iceblue</id>   
        <name>e-iceblue</name>   
        <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>   
    </repository>   
</repositories>   
<dependencies>   
    <dependency>   
        <groupId> e-iceblue </groupId>   
        <artifactId>spire.presentation</artifactId>   
        <version>7.5.2</version>   
    </dependency>   
</dependencies>

Method 2. If you are not using maven, you can download Spire.Presentation for Java from this website, extract the package and then import the Spire.Presentation.jar under the lib folder into your project as a dependency.

Using The Code

Spire.Presentation for Java provides a Presentation.getSlides.append(ISlide) method which enables you to merge or split PowerPoint presentations by cloning slides from one PowerPoint presentation to another. The following examples will show you how to merge PowerPoint presentations into one and how to split a PowerPoint presentation into multiple presentations in Java.

Example 1. Merge PowerPoint Presentations into One in Java

You can extract all or specified slides of a PowerPoint presentation, and then add them to the end or specified position of a destination presentation. The following are the steps to do so:

  • Create an instance of Presentation class.
  • Load the first PowerPoint presentation using Presentation.loadFromFile() method.
  • Create an instance of Presentation class.
  • Load the second PowerPoint presentation using Presentation.loadFromFile() method.
  • Loop through the slides in the first presentation, then add each slide to the end of the second presentation using Presentation.getSlides().append() method. If you want to add each slide to a specified position, use the Presentation.getSlides().insert() method instead.
  • Save the result presentation to another file using Presentation.saveToFile() method.
import com.spire.presentation.FileFormat;
import com.spire.presentation.Presentation;

public class MergePresentations {
    public static void main(String[] args) throws Exception {
        //Create a Presentation instance
        Presentation ppt1= new Presentation();
        //Load the first presentation
        ppt1.loadFromFile("Sample1.pptx");

        //Create a Presentation instance
        Presentation ppt2 = new Presentation();
        //Load the second presentation
        ppt2.loadFromFile("Sample2.pptx");

        //Loop through the slides of the first presentation
        for(int i = 0; i < ppt1.getSlides().getCount(); i++) {
            //Append the slides of the first presentation to the end of the second presentation
            ppt2.getSlides().append(ppt1.getSlides().get(i));

            //Insert the slides of the first presentation into the specified position of second presentation
            //ppt2.getSlides().insert(0, ppt1.getSlides().get(i));
        }

        //Save the result presentation to another file
        ppt2.saveToFile("MergePresentations.pptx", FileFormat.PPTX_2013);
    }
}
Merge two or more PowerPoint presentations into one using Java

Example 2. Split a PowerPoint Presentation into Multiple Presentations in Java

You can split a PowerPoint presentation by each slide or by slide range. The following are the steps to split a PowerPoint presentation by each slide:

  • Create an instance of Presentation class.
  • Load the first PowerPoint presentation using Presentation.loadFromFile() method.
  • Loop through the slides in the presentation.
  • Within the loop, create an instance of Presentation class, remove the default slide, then add each slide of the source presentation to the new presentation using Presentation.getSlides().append() method. After that, save the result presentation to file using Presentation.saveToFile() method.
import com.spire.presentation.FileFormat;
import com.spire.presentation.Presentation;

public class SplitPresentationByEachPage {
    public static void main(String[] args) throws Exception {
        //Create a Presentation instance
        Presentation ppt = new Presentation();
        //Load the presentation
        ppt.loadFromFile("Sample1.pptx");

        //Loop through the slides in the presentation
        for (int i = 0; i < ppt.getSlides().getCount(); i++)
        {
            //Create a new Presentation
            Presentation newPPT = new Presentation();
            //Remove the default slide
            newPPT.getSlides().removeAt(0);

            //Extract each slide from the source presentation and append it to the new presentation
            newPPT.getSlides().append(ppt.getSlides().get(i));

            //Save the result presentation to file
            newPPT.saveToFile(String.format("split/split-%d.pptx",i), FileFormat.PPTX_2013);
        }
    }
}
Split a PowerPoint presentation to multiple presentations using Java

Add, Verify or Remove Digital Signature in PowerPoint in Java

A digital signature is an electronic, encrypted, stamp of authentication on digital information such as e-mail messages or electronic documents. It can help the recipient verify if the document content has been altered or not since it was signed. If any changes are made, the signature will become invalid immediately. In this article, I will demonstrate how to add, verify or remove digital signature in PowerPoint using Java.

Add Dependencies

In order to deal with PowerPoint documents, I will be using Spire.Presentation for Java API. The API’s jar can be either downloaded from the official website or installed from Maven by adding the following code to your maven-based project’s pom.xml file.

<repositories>   
    <repository>   
        <id>com.e-iceblue</id>   
        <name>e-iceblue</name>   
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>   
    </repository>   
</repositories>   
<dependencies>   
    <dependency>   
        <groupId> e-iceblue </groupId>   
        <artifactId>spire.presentation</artifactId>   
        <version>5.1.7</version>   
    </dependency>   
</dependencies>

Add Digital Signature to PowerPoint in Java

The following are the steps to add a digital signature to a PowerPoint document:

  • Create an instance of Presentation class.
  • Load the PowerPoint document using Presentation.loadFromFile(String filePath) method.
  • Add a digital signature to the document using Presentation.addDigitalSignature(String pfxPath, String password, String comments, Date signTime) method.
  • Save the result document using Presentation.saveToFile(String filePath, FileFormat fileFormat) method.
import com.spire.presentation.FileFormat;
import com.spire.presentation.Presentation;

import java.util.Date;

public class AddSignature {
    public static void main(String []args) throws Exception {
        //Create a Presentation instance
        Presentation presentation = new Presentation();
        //Load the PowerPoint document
        presentation.loadFromFile("Sample.pptx");

        //Add a digital signature
        String pfxPath = "Certificate.pfx";
        String password = "123456"; //The password of the .pfx file
        String comment = "Modification is not allowed";
        presentation.addDigitalSignature(pfxPath, password, comment, new Date());

        //Save the result to file
        presentation.saveToFile("AddSignature.pptx", FileFormat.PPTX_2013);
    }
}

Output:

Add digital signature to PowerPoint in Java

Verify Digital Signature in PowerPoint in Java

The following are the steps to verify digital signature in a PowerPoint document:

  • Create an instance of Presentation class.
  • Load a PowerPoint document using Presentation.loadFromFile(String filePath) method.
  • Detect if the document is digitally signed or not using Presentation.isDigitallySigned() method.
import com.spire.presentation.Presentation;

public class VerifyIfPPTisDigitallySigned {
    public static void main(String []args) throws Exception {
        //Create a Presentation instance
        Presentation presentation = new Presentation();
        //Load a PowerPoint document
        presentation.loadFromFile("AddSignature.pptx");

        //Verify if the document is digitally signed
        if (presentation.isDigitallySigned()) {
            System.out.println("This document is digitally signed");
        } else {
            System.out.println("This document is not digitally signed");
        }
    }
}

Output:

Verify digital signature in PowerPoint in Java

Remove Digital Signature from PowerPoint in Java

The following are the steps to remove all digital signatures from a PowerPoint document:

  • Create an instance of Presentation class.
  • Load a PowerPoint document using Presentation.loadFromFile(String filePath) method.
  • Detect if the document is digitally signed or not using Presentation.isDigitallySigned() method. If the result is true, remove all digital signatures using Presentation.removeAllDigitalSignatures() method.
  • Save the result document using Presentation.saveToFile(String filePath, FileFormat fileFormat) method.
import com.spire.presentation.FileFormat;
import com.spire.presentation.Presentation;

public class RemoveSignature {
    public static void main(String []args) throws Exception {
        //Create a Presentation instance
        Presentation presentation = new Presentation();

        //Load the PowerPoint document
        presentation.loadFromFile("AddSignature.pptx");

        //Determine if the document is digitally signed
        if (presentation.isDigitallySigned())
        {
            //Remove all digital signatures
            presentation.removeAllDigitalSignatures();
        }

        //Save the result document
        presentation.saveToFile("RemoveSignature.pptx", FileFormat.PPTX_2013);
    }
}

Output:

Remove digital signature in PowerPoint in Java

See More

Product Page | Tutorials  | Examples | Forum | Customized Demo | Temporary License

Hide or Unhide Slides in PowerPoint in Java

In Microsoft PowerPoint, you can hide a slide so that it won’t appear during the Slide Show. You can also unhide it if you want to show them in future presentations. In this article, I will demonstrate how to hide or unhide slides in PowerPoint programmatically in Java using Free Spire.Presentation for Java API.

Add Dependencies

You can either download the jar of Free Spire.Presentation for Java from the official website or install it from maven by adding the following configurations to your maven-based project’s pom.xml file.

<repositories>    
    <repository>    
        <id>com.e-iceblue</id>    
        <name>e-iceblue</name>    
        <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>    
    </repository>    
</repositories>    
<dependencies>    
    <dependency>    
        <groupId> e-iceblue </groupId>    
        <artifactId>spire.presentation.free</artifactId>    
        <version>3.9.0</version>    
    </dependency>    
</dependencies>

Hide or Unhide Slides

You can use the setHidden method of ISlide class to hide or unhide a slide. The method takes a Boolean parameter indicates whether to hide or unhide a slide during the presentation.

The following are the steps to hide or unhide a slide:

  • Create an instance of Presentation class.
  • Load a PowerPoint document using Presentation.loadFromFile() method.
  • Access the slide that you want to hide or unhide by its index using Presentation.getSlides().get() method.
  • Hide or unhide the slide using ISlide.setHidden() method.
  • Save the result document using Presentation.saveToFile() method.
import com.spire.presentation.FileFormat;
import com.spire.presentation.ISlide;
import com.spire.presentation.Presentation;

public class HideOrUnhideSlides {
    public static void main(String []args) throws Exception {
        //Create a Presentation instance
        Presentation ppt = new Presentation();
        //Load a PowerPoint document
        ppt.loadFromFile("Sample.pptx");

        //Get the second slide 
        ISlide slide = ppt.getSlides().get(1);
        //Hide the slide
        slide.setHidden(true);
        //Unhide the slide
        //slide.setHidden(false);

        //Save the result document
        ppt.saveToFile("Result.pptx", FileFormat.PPTX_2013);
    }
}

The following is the output document after hiding the second presentation:

Hide a slide in PowerPoint Presentation in Java

Add Math Equations to PowerPoint in Java

Microsoft PowerPoint provides the “Equation” option which allows you to insert math equations to your PowerPoint document manually. In this article, I am going to demonstrate how to insert math equations to PowerPoint shape programmatically in Java using Spire.Presentation for Java library.

Add Dependencies

You can either download the jar of Spire.Presentation for Java from the official website or install it from maven by adding the following configurations to your maven-based project’s pom.xml file.

<repositories>    
    <repository>    
        <id>com.e-iceblue</id>    
        <name>e-iceblue</name>    
        <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>    
    </repository>    
</repositories>    
<dependencies>    
    <dependency>    
        <groupId> e-iceblue </groupId>    
        <artifactId>spire.presentation </artifactId>    
        <version>4.11.7</version>    
    </dependency>    
</dependencies>

Add Math Equations to PowerPoint

Spire.Presentation for Java supports creating and adding mathematical equations to PowerPoint shape using LaTeX code. You can follow the following steps to achieve this function:

  • Create a Presentation instance.
  • Get the reference of a slide by using its index.
  • Use ShapeList.appendShape() method to add a shape to the first slide.
  • Use ParagraphCollection.addParagraphFromLatexMathCode() method to create a mathematical equation from LaTeX code and add it to the shape.
  • Save the result document using Presentation.saveToFile() method.
import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;

import java.awt.geom.Rectangle2D;

public class AddMathEquations {
    public static void main(String []args) throws Exception {

        //The LaTeX codes
        String latexCode1 = "x^{2} + \\sqrt{x^{2}+1}=2";
        String latexCode2 = "F(x) &= \\int^a_b \\frac{1}{3}x^3";
        String latexCode3 = "\\alpha + \\beta  \\geq \\gamma";
        String latexCode4 = "\\overrightarrow{abc}";

        //Create a Presentation instance
        Presentation ppt = new Presentation();

        //Get the first slide by using its index
        ISlide slide = ppt.getSlides().get(0);

        //Add a shape to the slide
        IAutoShape shape = slide.getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle2D.Float(30, 100, 200, 30));
        shape.getTextFrame().getParagraphs().clear();
        //Add a math equation to the shape using the LaTeX code
        ParagraphEx para = shape.getTextFrame().getParagraphs().addParagraphFromLatexMathCode(latexCode1);

        //Add a shape to the slide
        shape = slide.getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle2D.Float(240, 100, 200, 40));
        shape.getTextFrame().getParagraphs().clear();
        //Add a math equation to the shape using the LaTeX code
        para = shape.getTextFrame().getParagraphs().addParagraphFromLatexMathCode(latexCode2);

        //Add a shape to the slide
        shape = slide.getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle2D.Float(30, 180, 200, 40));
        shape.getTextFrame().getParagraphs().clear();
        //Add a math equation to the shape using the LaTeX code
        para = shape.getTextFrame().getParagraphs().addParagraphFromLatexMathCode(latexCode3);

        //Add a shape to the slide
        shape = slide.getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle2D.Float(240, 180, 200, 40));
        shape.getTextFrame().getParagraphs().clear();
        //Add a math equation to the shape using the LaTeX code
        para = shape.getTextFrame().getParagraphs().addParagraphFromLatexMathCode(latexCode4);

        for (IShape iShape : (Iterable<IShape>)slide.getShapes())
        {
            iShape.getFill().setFillType(FillFormatType.NONE);
            iShape.getLine().setFillType(FillFormatType.NONE);
        }

        //Save the result document
        ppt.saveToFile("AddMathEquations.pptx", FileFormat.PPTX_2013);
        ppt.dispose();
    }
}
Add Math Equations to PowerPoint in Java

Add Superscript and Subscript to PowerPoint in Java

When you add a trademark, copyright, or other symbol to your presentation, you might want the symbol to appear slightly above or below a certain text. In Microsoft PowerPoint, you can implement this effect simply by applying superscript or subscript formatting to the text. In this article, you will see how to achieve this task programmatically in Java using Free Spire.Presentation for Java library.

Add Dependencies

You can either download the jar of Free Spire.Presentation for Java from the official website or install it from maven by adding the following configurations to your maven-based project’s pom.xml file.

<repositories>    
    <repository>    
        <id>com.e-iceblue</id>    
        <name>e-iceblue</name>    
        <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>    
    </repository>    
</repositories>    
<dependencies>    
    <dependency>    
        <groupId> e-iceblue </groupId>    
        <artifactId>spire.presentation.free</artifactId>    
        <version>3.9.0</version>    
    </dependency>    
</dependencies>

Add Superscript and Subscript

Free Spire.Presentation for Java provides the PortionFormatEx.setScriptDistance(float value) method for applying superscript or subscript formatting to text. The value can be set as positive (superscript) or negative (subscript).

import com.spire.presentation.*;
import com.spire.presentation.drawing.*;

import java.awt.*;

public class AddSuperscriptAndSubscript {
    public static void main(String []args) throws Exception {

        //Create a Presentation instance
        Presentation presentation = new Presentation();

        //Load a PowerPoint document
        presentation.loadFromFile("template.pptx");
        //Get the first slide
        ISlide slide = presentation.getSlides().get(0);
        //Add a shape to the slide
        IAutoShape shape = presentation.getSlides().get(0).getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle(150, 100, 200, 50));
        shape.getFill().setFillType(FillFormatType.NONE);
        shape.getShapeStyle().getLineColor().setColor(Color.white);
        shape.getTextFrame().getParagraphs().clear();

        //Append text to the shape
        shape.appendTextFrame("X");
        PortionEx tr = new PortionEx("2");
        //Apply superscript format to text
        tr.getFormat().setScriptDistance(40);
        //Append text to the shape
        shape.getTextFrame().getParagraphs().get(0).getTextRanges().append(tr);

        //Set text color and font
        tr = shape.getTextFrame().getParagraphs().get(0).getTextRanges().get(0);
        tr.getFill().setFillType(FillFormatType.SOLID);
        tr.getFill().getSolidColor().setColor(new Color(128,0,128));
        tr.setFontHeight(20);
        tr.setLatinFont(new TextFont("Arial"));
        tr = shape.getTextFrame().getParagraphs().get(0).getTextRanges().get(1);
        tr.getFill().setFillType(FillFormatType.SOLID);
        tr.getFill().getSolidColor().setColor(Color.BLUE);
        tr.setLatinFont(new TextFont("Arial"));

        //Add a shape to the slide
        shape = presentation.getSlides().get(0).getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle(150, 150, 200, 50));
        shape.getFill().setFillType(FillFormatType.NONE);
        shape.getShapeStyle().getLineColor().setColor(Color.white);
        shape.getTextFrame().getParagraphs().clear();

        //Append text to the shape
        shape.appendTextFrame("H");
        tr = new PortionEx("2");
        //Apply subscript formatting to text
        tr.getFormat().setScriptDistance(-25);
        //Append text to shape
        shape.getTextFrame().getParagraphs().get(0).getTextRanges().append(tr);

        //Set text color and font
        tr = shape.getTextFrame().getParagraphs().get(0).getTextRanges().get(0);
        tr.getFill().setFillType(FillFormatType.SOLID);
        tr.getFill().getSolidColor().setColor(new Color(128,0,128));
        tr.setFontHeight(20);
        tr.setLatinFont(new TextFont("Arial"));
        tr = shape.getTextFrame().getParagraphs().get(0).getTextRanges().get(1);
        tr.getFill().setFillType(FillFormatType.SOLID);
        tr.getFill().getSolidColor().setColor(Color.BLUE);
        tr.setLatinFont(new TextFont("Arial"));

        //Save the document
        presentation.saveToFile("AddSuperscriptAndSubscript.pptx", FileFormat.PPTX_2013);
    }
}

Output:

Add Superscript and Subscript to PowerPoint in Java

Convert PowerPoint PPT/PPTX to PDF in Java

PowerPoint PPT or PPTX is the most popular file format for presentations, but viewing a PowerPoint document requires Microsoft PowerPoint or other equivalents to be installed on system. For users who don’t have PowerPoint, converting PowerPoint document to PDF might be a good choice. In this article, I will describe how to achieve this task programmatically using Java.

Add Dependencies

To convert PowerPoint PPT/PPTX to PDF, this article uses Spire.Presentation for Java, which is a multi-functional and easy-to-use third-party API for creating, converting and manipulating PowerPoint documents.

You can either download the API’s jar from here or install it from maven by adding the following configurations to your maven-based project’s pom.xml file.

<repositories>    
    <repository>    
        <id>com.e-iceblue</id>    
        <name>e-iceblue</name>    
        <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>    
    </repository>    
</repositories>    
<dependencies>    
    <dependency>    
        <groupId> e-iceblue </groupId>    
        <artifactId>spire.presentation </artifactId>    
        <version>4.9.2</version>    
    </dependency>    
</dependencies>

Convert PowerPoint PPT/PPTX to PDF

There are two options to save your PowerPoint PPT/PPTX document to PDF:

1. Convert the whole PowerPoint PPT/PPTX document to PDF.
2. Convert specific slide(s) of the PowerPoint PPT/PPTX to PDF.

Convert the whole PowerPoint PPT/PPTX Document to PDF

The following are the steps to convert a PowerPoint PPT or PPTX document to PDF format:

1. Create a Presentation instance.
2. Load a PowerPoint PPT/PPTX document using Presentation.loadFromFile() method.
3. Save the document to PDF using Presentation.saveToFile() method with specified file path and FileFormat.

import com.spire.presentation.FileFormat;
import com.spire.presentation.Presentation;

public class ConvertPowerPointToPDF {
    public static void main(String []args) throws Exception {
        //Create a Presentation instance
        Presentation ppt = new Presentation();
        //Load a PPT document
        //ppt.loadFromFile("Sample.ppt");
        //Load a PPTX document
        ppt.loadFromFile("Sample.pptx");
        
        //Save the document as PDF
        ppt.saveToFile("ToPDF.pdf", FileFormat.PDF);
    }
}

The input PowerPoint PPTX document:

Figure 1. Sample PPTX Document

The converted PDF:

Figure 2. Converted PDF from PPTX Document

Convert Specified Slide(s) of the PowerPoint PPT/PPTX to PDF

The following are the steps to convert a specific slide to PDF format:

1. Create a Presentation instance.
2. Load a PowerPoint PPT/PPTX document using Presentation.loadFromFile() method.
3. Get the desired slide by using its index.
4. Save the document to PDF using ISlide.saveToFile() method with specified file path and FileFormat.

import com.spire.presentation.FileFormat;
import com.spire.presentation.ISlide;
import com.spire.presentation.Presentation;

public class ConvertPowerPointToPDF {
    public static void main(String []args) throws Exception {

        //Create a Presentation instance
        Presentation ppt = new Presentation();
       //Load a PPT document
        //ppt.loadFromFile("Sample.ppt");
        //Load a PPTX document
        ppt.loadFromFile("Sample.pptx");

        //Get the second slide
        ISlide slide= ppt.getSlides().get(1);
        
        //Save the slide as PDF
        slide.SaveToFile("SpecificSlideToPDF.pdf", FileFormat.PDF);
    }
}

The second slide:

Figure 3. The Specific Slide

The converted PDF:

Figure 4. Converted PDF from Specific Slide

Java: Shrink Text to Fit in Shape or Resize Shape to Fit Text in PowerPoint

When inserting text into a PowerPoint shape, we may discover that sometimes the text is so long that it overflows the shape, or the shape is too large for the text. For such case, Microsoft PowerPoint provides the following autofit options which allows us to automatically shrink text to fit in a shape, or to resize a shape to fit text:

MS PowerPoint Autofit Options

In this article, I will describe how to achieve this task programmatically using Java.

Add Dependencies

To shrink text or resize shape in PowerPoint, this article uses Free Spire.Presentation for Java, which is a free and multi-functional third-party API for creating, converting and manipulating PowerPoint documents.

You can either download the API’s jar from here or install it from maven by adding the following configurations to your maven-based project’s pom.xml file.

<repositories>    
    <repository>    
        <id>com.e-iceblue</id>    
        <name>e-iceblue</name>    
        <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>    
    </repository>    
</repositories>    
<dependencies>    
    <dependency>    
        <groupId> e-iceblue </groupId>    
        <artifactId>spire.presentation.free</artifactId>    
        <version>3.9.0</version>    
    </dependency>    
</dependencies>

Implementation

Free Spire.Presentation for Java API provides a ITextFrameProperties.setAutofitType() method which can be used to shrink text to fit in a shape or resize a shape to fit text. This method accepts the following parameter:

TextAutofitType: specifies the autofit type of a shape.

To shrink text to fit in a shape or to resize a shape to fit text, you can follow the below steps:

1. Create a Presentation instance.
2. Get the first slide by using its index (zero-based).
3. Add a shape to the slide using ShapeList.appendShape() method.
4. Add text to the shape using ITextFrameProperties.setText() method.
5. Call ITextFrameProperties.setAutofitType() method to set the autofit option of the shape. For shrinking text, set the AutofitType as TextAutofitType.NORMAL. For resizing shape to fit text, set the AutofitType as TextAutofitType.SHAPE.
6. Save the result document using Presentation.saveToFile() method.

import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;

import java.awt.*;

public class ShrinkTextOrResizeShape {
    public static void main(String []args) throws Exception {
        //Create a Presentation instance
        Presentation ppt = new Presentation();
        //If you want to load an existing document, use loadFromFile method
        //ppt.loadFromFile("Input.pptx");

        //Get the first slide
        ISlide slide = ppt.getSlides().get(0);

        //Add a shape to the slide
        //If you want to get an existing shape, use slide.getShapes.get(shapeIndex) method
        IAutoShape shape = slide.getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle(100, 100, 150, 80));
        shape.getFill().setFillType(FillFormatType.NONE);
        ITextFrameProperties textFrame = shape.getTextFrame();
        //Add text to the shape
        textFrame.setText("Shrink text to fit in shape. Shrink text to fit in shape. Shrink text to fit in shape. Shrink text to fit in shape.");
        textFrame.getTextRange().getFill().setFillType(FillFormatType.SOLID);
        textFrame.getTextRange().getFill().getSolidColor().setColor(Color.BLACK);
        //Shrink text to fit in the shape by setting the AutofitType as normal
        textFrame.setAutofitType(TextAutofitType.NORMAL);

        //Add a shape to the slide
        shape = slide.getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle(350, 100, 150, 80));
        shape.getFill().setFillType(FillFormatType.NONE);
        textFrame = shape.getTextFrame();
        //Add text to the shape
        textFrame.setText("Resize shape to fit text.");
        textFrame.getTextRange().getFill().setFillType(FillFormatType.SOLID);
        textFrame.getTextRange().getFill().getSolidColor().setColor(Color.BLACK);
        //Resize shape to fit text by setting the AutofitType as shape
        textFrame.setAutofitType(TextAutofitType.SHAPE);

        //Save the document
        String result = "ShrinkTextOrResizeShape.pptx";
        ppt.saveToFile(result, FileFormat.PPTX_2013);
    }
}

Output:

Figure 1. Shrink Text to Fit in a Shape
Figure 2. Resize a shape to fit text

Insert Audio and Video Files into PowerPoint in Java

Sometimes presenters prefer to add audio or video files to PowerPoint presentation documents because they can quickly catch audiences’ attention.  In this article, I will describe how to insert audio and video files into a PowerPoint presentation document programmatically in Java using Free Spire.Presentation for Java API.

Add Dependencies

To begin, you need to add dependencies for including Free Spire.Presentation for Java into your project.

If you use maven, add the following maven dependencies to your project’s pom.xml file:

<repositories>    
    <repository>    
        <id>com.e-iceblue</id>    
        <name>e-iceblue</name>    
        <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>    
    </repository>    
</repositories>    
<dependencies>    
    <dependency>    
        <groupId> e-iceblue </groupId>    
        <artifactId>spire.presentation.free</artifactId>    
        <version>3.9.0</version>    
    </dependency>    
</dependencies>

For non-maven project, download Free Spire.Presentation for Java pack from this website, extract the zip file, then add Free Spire.Presentation.jar in the lib folder into your project as a dependency.

Insert Audio and Video

In Free Spire.Presentation for Java API, the com.spire.presentation.IAudio and com.spire.presentation.IVideo classes are used to create and deal with audio and video files. To add audio and video to a PowerPoint presentation document, you can follow these steps:

1. Create an instance of Presentation class.
2. Load a PowerPoint presentation document using Presentation.loadFromFile method.
3. Get the reference of a slide by using its index.
4. Use the IAudio.appendAudioMedia method to insert an audio file to specific location of the slide.
5. Customize the audio options such as setting play mode and volume.
6. Use the IVideo.appendVideoMedia method to insert a video file to specific location of the slide.
7. Customize the video options such as setting cover image, play mode and volume.
8. Save the result document.

The following example shows how you can insert and customize audio and video files in a PowerPoint presentation document using the Free Spire.Presentation for Java API.

import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;

import javax.imageio.ImageIO;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;

public class InsertAudioAndVideo {
    public static void main(String []args) throws Exception {
        //Create a Presentation instance
        Presentation ppt = new Presentation();
        presentation.loadFromFile(“Input.pptx”);
        //Get the first slide
        ISlide slide = ppt.getSlides().get(0);

        //Insert audio into the document
        Rectangle2D.Double audioRect = new Rectangle2D.Double(100, 220, 80, 80);
        IAudio audio = ppt.getSlides().get(0).getShapes().appendAudioMedia((new java.io.File("Music.wav")).getAbsolutePath(), audioRect);
        //Set audio play mode
        audio.setPlayMode(AudioPlayMode.ON_CLICK);
        //Set volume
        audio.setVolume(AudioVolumeType.LOUD);

        //Insert video into the document
        Rectangle2D.Double videoRect = new Rectangle2D.Double(250, 160, 300, 200);
        IVideo video = ppt.getSlides().get(0).getShapes().appendVideoMedia((new java.io.File("Video.mp4")).getAbsolutePath(), videoRect);
        video.getLine().setFillType(FillFormatType.NONE);
        //Set cover image for video
        BufferedImage image = ImageIO.read( new File("Video1.png"));
        video.getPictureFill().getPicture().setEmbedImage(ppt.getImages().append(image));
        //Set video play mode
        video.setPlayMode(VideoPlayMode.ON_CLICK);
        //Set volume
        video.setVolume(AudioVolumeType.LOUD);

        //Save the document
        ppt.saveToFile("Insert Audio and Video.pptx", FileFormat.PPTX_2013);
        ppt.dispose();
    }
}

The output PowerPoint document:

Insert Audio and Video to PowerPoint

Add, Lock and Remove Watermarks in PowerPoint in Java

You can add watermarks to a PowerPoint document to prevent it from illegal usage, or to specify if the document is a “draft” version. Here you will see how to work with watermarks, especially add, lock and remove watermarks in Java using Free Spire.Presentation for Java library.

Before running the following code example, you need to add dependencies for including Free Spire.Presentation for Java library in your Java project.

Add and Lock Watermarks

In general, there are two types of watermarks: text watermark and image watermark. Free Spire.Presentation library supports adding text and image watermarks to a PowerPoint document through the following steps:

  • Load the document.
  • Iterate through the slides in the document.
  • Add a shape (ex. rectangle) to each slide and then insert text/image to the shape.
  • Lock the shape to prevent them from selecting and editing   
  • Save the result document.

Add Text Watermark

import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;

import java.awt.*;
import java.awt.geom.Rectangle2D;

public class TextWatermark {
    public static void main(String []args) throws Exception {
        //Load a sample document
        Presentation ppt = new Presentation();
        ppt.loadFromFile("Input.pptx");

        //Iterate through the slides in the document
        for(int i = 0; i < ppt.getSlides().getCount(); i++)
        {
            ISlide slide = ppt.getSlides().get(i);
            //Add shape to each slide
            IAutoShape shape = slide.getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle2D.Double(340, 150, 300, 200));
            //Set shape name
            shape.setName("textWatermark");
            //Set shape fill type as no fill
            shape.getFill().setFillType(FillFormatType.NONE);
            //Set shape rotation
            shape.setRotation(-45);
            //Lock the shape to protect it from selecting and editing
            shape.getLocking().setSelectionProtection(true);
            //Set shape border type as no border
            shape.getLine().setFillType(FillFormatType.NONE);

            //Add text to shape and set font of the text
            shape.getTextFrame().setText("Confidential");
            PortionEx textRange = shape.getTextFrame().getTextRange();
            textRange.getFill().setFillType(FillFormatType.SOLID);
            textRange.getFill().getSolidColor().setColor(Color.GRAY);
            textRange.setFontHeight(40);
            textRange.setLatinFont(new TextFont("Arial"));
        }

        //Save the result document
        ppt.saveToFile("TextWatermark.pptx", FileFormat.PPTX_2013);
    }
}

Output:

Add Image Watermark

import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;

import java.awt.geom.Rectangle2D;

public class ImageWatermark {
    public static void main(String []args) throws Exception {
        //Load a document
        Presentation ppt = new Presentation();
        ppt.loadFromFile("Input.pptx");

        //Iterate through the slides in the document
        for(int i = 0; i< ppt.getSlides().getCount(); i++)
        {
            ISlide slide = ppt.getSlides().get(i);
            //Add image to the slide
            IEmbedImage image = slide.getShapes().appendEmbedImage(ShapeType.RECTANGLE, "img.jpg", new Rectangle2D.Double(340, 150, 200, 200));
            //Set image name
            image.setName("imageWatermark");
            //Set image transparency
            image.getPictureFill().getPicture().setTransparency(70);
            //Lock image
            image.getShapeLocking().setSelectionProtection(true);
            image.getLine().setFillType(FillFormatType.NONE);
        }
        
        //Save the result document
        ppt.saveToFile("ImageWatermark.pptx", FileFormat.PPTX_2013);
    }
}

Output:

Remove Watermarks

Use the following code, you’re able to remove either the text watermark shape or the image watermark shape by detecting shape name.

import com.spire.presentation.*;

public class RemoveWatermark {
    public static void main(String []args) throws Exception {
        //Load a document
        Presentation ppt = new Presentation();
        ppt.loadFromFile("imageWatermark.pptx");

        //Iterate through the slides in the document
        for(int i = 0; i < ppt.getSlides().getCount(); i++)
        {
            ISlide slide = ppt.getSlides().get(i);
            //Iterate through the shapes on each slide
            for (int j = slide.getShapes().getCount()-1; j >= 0; j--)
            {
                IShape shape = slide.getShapes().get(j);
                //Remove the shape named "imageWatermark"
                if (shape.getName().equals("imageWatermark"))
                {
                    slide.getShapes().removeAt(j);
                }
            }
        }

        //Save the result document
        ppt.saveToFile("RemoveWatermark.pptx", FileFormat.PPTX_2013);
    }
}

Output:

Replace Text and Image in PowerPoint in Java

Replacing text or image one-by-one manually is time consuming and inefficient, especially when dealing with a large document with a huge amount of data. In this article, I will demonstrate how to replace text and image in PowerPoint programmatically in Java using Free Spire.Presentation for Java library.

Contents

  • Add dependencies
  • Replace text with new text
  • Replace image with new image

Add Dependencies

There are two ways to include Free Spire.Presentation for Java in your Java project.

For maven projects, add the following dependencies to your project’s pom.xml file:

<repositories>    
    <repository>    
        <id>com.e-iceblue</id>    
        <name>e-iceblue</name>    
        <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>    
    </repository>    
</repositories>    
<dependencies>    
    <dependency>    
        <groupId> e-iceblue </groupId>    
        <artifactId>spire.presentation.free</artifactId>    
        <version>3.9.0</version>    
    </dependency>    
</dependencies>

For non-maven projects, download Free Spire.Presentation for Java pack, extract the zip file, then add Free Spire.Presentation.jar in the lib folder into your project as a dependency.

Replace text with new text

You can use the replaceFirstText(String matchedString, String newValue, boolean caseSensitive) or  the replaceAllText(String matchedString, String newValue, boolean caseSensitive) methods provided by ISlide class to replace the first occurrence of a text or all the occurrences of a text in a PowerPoint slide.

The input PowerPoint document:

import com.spire.presentation.FileFormat;
import com.spire.presentation.ISlide;
import com.spire.presentation.Presentation;

public class ReplaceText {
    public static void main(String []args) throws Exception {
        //Create a Presentation instance
        Presentation ppt = new Presentation();
        //Load a PowerPoint document
        ppt.loadFromFile("Sample.pptx");

        //Get the first slide
        ISlide slide = ppt.getSlides().get(0);

        //Replace the first occurrence of a text
        //slide.replaceFirstText("Old String", "New String", false);
        //Replace all the occurrences of a text
        slide.replaceAllText("Old String", "New String", false);

        //Save the document
        ppt.saveToFile("ReplaceText.pptx", FileFormat.PPTX_2013);
    }
}

Output:

Replace image with new image

import com.spire.presentation.*;
import com.spire.presentation.drawing.IImageData;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;

public class ReplaceImage {
    public static void main(String []args) throws Exception {
        //Create a Presentation instance
        Presentation presentation= new Presentation();

        //Load the sample PowerPoint document
        presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pptx");

        //Add an image to the image collection
        String imagePath = "C:\\Users\\Administrator\\Desktop\\Rabbit.png";
        BufferedImage bufferedImage = ImageIO.read(new FileInputStream(imagePath));
        IImageData image = presentation.getImages().append(bufferedImage);

        //Get the shape collection from the first slide
        ShapeCollection shapes = presentation.getSlides().get(0).getShapes();

        //Loop through the shape collection
        for (int i = 0; i < shapes.getCount(); i++) {

            //Determine if a shape is a picture
            if (shapes.get(i) instanceof SlidePicture) {

                //Fill the shape with a new image
                ((SlidePicture) shapes.get(i)).getPictureFill().getPicture().setEmbedImage(image);
            }
        }

        //Save the document
        presentation.saveToFile("ReplaceImage.pptx", FileFormat.PPTX_2013);
    }
}

Output:

Design a site like this with WordPress.com
Get started