Apache Poi Ppt 简明教程

Apache POI PPT - Quick Guide

Apache POI PPT - Overview

很多时候,软件应用程序需要生成 Microsoft Office 文件格式的报告。有时,甚至需要应用程序接收 MS-Office 文件作为输入数据。

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

任何想要生成 MS Office 文件作为输出的 Java 编程人员都必须使用一个预定义且只读的 API 来执行此操作。

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 是一个流行的 API,它允许程序员使用 Java 程序创建、修改和显示 MS-Office 文件。它是一个由 Apache Software Foundation 开发和分发的开源库。它包含用于对用户输入数据或文件解码为 MS Office 文档的类和方法。

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 library 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 包含用于操作 MS-Office 所有 OLE2 复合文档的类和方法。此 API 的组件列表如下 -

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

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

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

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

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

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

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

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

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

  9. HPBF (Horrible PuBlisher Format) − It is used to read and write MS-Publisher files.

本教程将指导你完成使用 Java 处理 Microsoft PowerPoint 演示文稿的过程。因此,讨论仅限于 XSLF component.

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

Note − POI 的较早版本支持 doc、xls、ppt 等二进制文件格式。从版本 3.5 起,POI 开始支持 MS-Office 的 OOXML 文件格式,如 docx、xlsx、pptx 等。

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

本章将带你了解 Java PowerPoint API 的一些优点及其特性。有许多供应商提供与 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 Slides for Java

针对 Java 的 Aspose 幻灯片是完全许可的 Java PPT API,由供应商 Aspose 开发和分发。此 API 的最新版本为 8.1.2,于 2014 年 7 月发布。它是一个丰富且庞大的 API(普通 Java 类和 AWT 类相结合),用于设计能够读取、写入和管理幻灯片的 PPT 组件。

Aspose slides for Java is a purely licensed 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 slides.

此 API 的常见用途如下 −

The common uses of this API are as follows −

  1. Build dynamic presentations

  2. Render and print high-fidelity presentations

  3. Generate, edit, convert, and print presentations

Apache POI

Apache POI 是 Apache 软件基金会提供的一个 100% 的开源库。大多数小型和中型应用程序开发者严重依赖 Apache POI (HSLF + XSLF)。它支持 PPT 库的所有基本功能;但是,呈现和文本提取是它的主要功能。下面给出了 Apache POI 的 PPT 架构。

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

apache poi flavors

Apache POI PPT - Installation

本教程将指导你完成在 Windows 和 Linux 系统上设置 Apache POI 的流程。Apache POI 可以在不执行任何复杂设置程序的情况下,使用几个简单的步骤轻松安装并集成到当前的 Java 环境中。在安装时需要有用户管理权限。

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

现在让我们继续进行安装 Apache POI 的步骤。

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

Step 1 − Verify your Java Installation

首先,你的系统中需要安装 Java 软件开发工具包 (SDK)。要验证这一点,请根据所使用的平台执行以下两个命令。

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.

如果 Java 安装已正确完成,则它将显示 Java 安装的当前版本和规范。以下表中给出了一个示例输出。

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.

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)

  1. We assume the readers of this tutorial have Java SDK version 11.0.11 installed on their system.

  2. In case you do not have Java SDK, download its current version from www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed.

Step 2 − Set your Java Environment

设置环境变量 JAVA_HOME 以指向计算机上安装 Java 的基本目录位置。例如,

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:\ProgramFiles\java\jdk11.0.11

2

Linux Export JAVA_HOME = /usr/local/java-current

将 Java 编译器位置的完整路径附加到系统路径。

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

Sr.No.

Platform & Description

1

Windows Append the String "C:\Program Files\Java\jdk11.0.11\bin" to the end of the system variable PATH.

2

Linux Export PATH = $PATH:$JAVA_HOME/bin/

如上所述,从命令提示符执行命令 java -version

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

Step 3 − Install Apache POI Library

https://poi.apache.org/download.html 下载最新版本的 Apache POI,并将其内容解压缩到一个文件夹中,然后可以将该文件夹中的所需库连接到你的 Java 程序。我们假设这些文件保存在 C 驱动器的文件夹中。

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 libraries can be linked to your Java program. Let us assume the files are collected in a folder on C drive.

将必需的 jars 的完整路径添加到 CLASSPATH,如下所示。

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.0\poi-5.1.0.jar; C:\poi-bin-5.1.0\poi-ooxml-5.1.0.jar; C:\poi-bin-5.1.0\poi-ooxml-full-5.1.0.jar; C:\poi-bin-5.1.0\lib\commons-codec-1.15.jar; C:\poi-bin-5.1.0\lib\commons-collections4-4.4.jar; C:\poi-bin-5.1.0\lib\commons-io-2.11.0.jar; C:\poi-bin-5.1.0\lib\commons-math3-3.6.1.jar; C:\poi-bin-5.1.0\lib\log4j-api-2.14.1.jar; C:\poi-bin-5.1.0\lib\SparseBitSet-1.2.jar; C\poi-bin-5.1.0\ooxml-lib\commons-compress-1.21.jar C\poi-bin-5.1.0\ooxml-lib\commons-logging-1.2.jar C\poi-bin-5.1.0\ooxml-lib\curvesapi-1.06.jar C\poi-bin-5.1.0\ooxml-lib\slf4j-api-1.7.32.jar C\poi-bin-5.1.0\ooxml-lib\xmlbeans-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/lib/commons-codec-1.15.jar.tar: /usr/share/poi-bin-5.1.0/lib/commons-collections4-4.4.tar: /usr/share/poi-bin-5.1.0/lib/commons-io-2.11.0.tar: /usr/share/poi-bin-5.1.0/lib/commons-math3-3.6.1.tar: /usr/share/poi-bin-5.1.0/lib/log4j-api-2.14.1.tar: /usr/share/poi-bin-5.1.0/lib/SparseBitSet-1.2.tar: /usr/share/poi-bin-5.1.0/ooxml-lib/commons-compress-1.21.tar: /usr/share/poi-bin-5.1.0/ooxml-lib/commons-logging-1.2.tar: /usr/share/poi-bin-5.1.0/ooxml-lib/curvesapi-1.06.tar: /usr/share/poi-bin-5.1.0/ooxml-lib/slf4j-api-1.7.32.tar: /usr/share/poi-bin-5.1.0/ooxml-lib/xmlbeans-5.0.2.tar:

pom.xml

以下是运行本教程中程序的 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

在本章中,我们将了解 Apache POI API 中的一些类和方法,这些方法对于使用 Java 程序处理 PPT 文件至关重要。

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

要创建和管理演示文稿,您有一个名为 XMLSlideShow 的类,该类位于包 org.apache.poi.xslf.usermodel 中。下面给出了此类的某些重要方法和一个构造函数。

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

Class − XMLSlideShow

Class − XMLSlideShow

Package − org.apache.poi.xslf.usermodel

Package − org.apache.poi.xslf.usermodel

S.No

Constructor & Description

1

XMLSlideShow(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

XSLFSlide createSlide() Creates a blank slide in a presentation.

3

XSLFSlide createSlide(XSLFSlideLayout layout) Creates a slide with a given slide 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<XSLFSlideMaster> getSlideMasters() Returns the list of all the slides in a presentation.

7

java.util.List<XSLFSlide> getSlides() Returns all the slides in a presentation.

8

XSLFSlide removeSlide(int index) Using this method, you can remove a slide from a presentation.

9

void setPageSize(java.awt.Dimension pgSize) Using this method, you can reset the page size.

10

void setSlideOrder(XSLFSlide slide, int newIndex) Using this method, you can reorder the slides.

Slide

如需在演示文稿中创建和管理幻灯片,请使用 XSLFSlide 类的相关方法。该类中的一些重要方法如下所述。

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

Class − XSLFSlide

Class − XSLFSlide

Package − org.apache.poi.xslf.usermodel

Package − org.apache.poi.xslf.usermodel

S.No

Method & Description

1

XSLFBackground getBackground() Returns the XSLFBackground object which can be used to retrieve details like color and anchor of the background of the slide. You can also draw shapes in the slide using this object.

2

XSLFSlideLayout getSlideLayout() Provides access to the XSLFSlideLayout object of the current slide.

3

XSLFSlideMaster getSlideMaster() Provides access to the slide master of the current slide.

4

XSLFTheme getTheme() Returns the XSLFTheme object of the current slide.

5

java.lang.String getTitle() Returns the title of the current slide.

6

XSLFSlide importContent(XSLFSheet src) Copies the contents of another slide to this slide.

Slide Master

这是演示文稿的一个组件,具有不同的幻灯片布局。 XSLFSlideMaster 类可用于对其进行访问。该类的部分重要方法如下所示。

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

Class − XSLFSlideMaster

Class − XSLFSlideMaster

Package − org.apache.poi.xslf.usermodel

Package − org.apache.poi.xslf.usermodel

S.No

Method & Description

1

XSLFBackground getBackground() Returns the common background of the slide master.

2

XSLFSlideLayout getLayout(SlideLayout type) Returns the XSLFSlideLayout object.

3

java.util.List<XSLFSlideLayout> getSlideLayouts() Returns all the slide layouts in this slide master.

Slide Layout

POI 库有一个名为 XSLFSlideLayout 的类,可用于管理幻灯片的布局。

The POI library has a class called XSLFSlideLayout, using which you can manage the layouts of a slide.

Class − XSLFSlideLayout

Class − XSLFSlideLayout

Package − org.apache.poi.xslf.usermodel

Package − org.apache.poi.xslf.usermodel

S.No

Method & Description

1

void copyLayout(XSLFSlide slide) This method will copy the placeholders from this layout to the given slide.

Text Paragraph

可以使用 XSLFTextParagraph 类向幻灯片写入内容。下面提到了该类的部分重要方法。

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

Class − XSLFTextParagraph

Class − XSLFTextParagraph

Package − org.apache.poi.xslf.usermodel

Package − org.apache.poi.xslf.usermodel

S.No

Method & Description

1

XSLFTextRun addLineBreak() Inserts a line break in a paragraph.

2

XSLFTextRun addNewTextRun() Adds a new run of text in a paragraph.

3

void setBulletAutoNumber(ListAutoNumber scheme, int startAt) Applies 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 linespacing) This method is used to set line spacing in the paragraph.

7

void setTextAlign(TextAlign align) This method is used to set alignment that is to be set to the paragraph.

Text Run

这是文本主体中文本分隔的最低级别。您可以通过 XSLFTextRun 类来管理段落的文本段。下面提到了该类的部分重要方法。

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

Class − XSLFTextParagraph

Package − org.apache.poi.xslf.usermodel

Package − org.apache.poi.xslf.usermodel

S.No

Method & Description

1

XSLFHyperlink createHyperlink() Creates a hyperlink in the presentation.

2

XSLFHyperlink getHyperlink() This method is used to get the hyperlink.

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 setItalic(boolean italic) This method is used to make the paragraph italicized.

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 setUnderline(boolean underline) This method is used to underline the text in a text run.

Text shape

在 PPT 中,我们有可以容纳文本的形状。我们可以使用 XSLFTextShape 类来管理它们。下面提到了此类的一些重要方法。

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

Class − XSLFTextShape

Package − org.apache.poi.xslf.usermodel

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 slide.

POI 库有一个名为 XSLFHyperlink 的类,您可以使用它在演示文稿中创建一个超链接。下面提到了此类的一些重要方法。

The POI library has a class called XSLFHyperlink using which you can create a hyperlink in the presentation. Mentioned below are some important methods of this class.

Class − XSLFHyperlink

Class − XSLFHyperlink

Package − org.apache.poi.xslf.usermodel

Package − org.apache.poi.xslf.usermodel

S.No

Method & Description

1

java.net.URI getTargetURL() Returns the URL existing in a slide of the presentation.

2

void setAddress(java.lang.String address) This method is used to set address to a URL.

3

void setAddress(XSLFSlide slide) Sets address to the URL present in a slide of the presentation.

Apache POI PPT - Presentation

通常,我们使用 MS-PowerPoint 创建演示文稿。现在让我们看看如何使用 Java 创建演示文稿。完成本章后,你将能够创建新的 MS-PowerPoint 演示文稿,并使用你的 Java 程序打开现有的 PPT。

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

要创建一个空演示文稿,你必须实例化 org.poi.xslf.usermodel 包的 XMLSlideShow 类 −

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

XMLSlideShow ppt = new XMLSlideShow();

使用 FileOutputStream 类将更改保存到 PPT 文档 −

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);

下面给出了创建空白 MS-PowerPoint 演示文稿的完整程序。

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.XMLSlideShow;

public class CreatePresentation {
   public static void main(String args[]) throws IOException {
      //creating a new empty slide show
      XMLSlideShow ppt = new XMLSlideShow();

      //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();
   }
}

将上述 Java 代码另存为 CreatePresentation.java ,然后从命令提示符编译并执行它,如下所示 −

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

如果你的系统环境配置了 POI 库,它将编译并执行以在你的当前目录中生成一个名为 example1.pptx 的空白 PPT 文件,并在命令提示符上显示以下输出 −

If your system environment is configured with the POI library, 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

空白的 PowerPoint 文档显示如下 −

The blank PowerPoint document appears as follows −

example1

Editing an Existing Presentation

要打开现有的演示文稿,请实例化 XMLSlideShow 类,并将要编辑的文件的 FileInputStream 对象作为 XMLSlideShow 构造函数的参数传递。

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

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

你可以使用 org.poi.xslf.usermodel 包中 XMLSlideShow 类的 createSlide() 方法向演示文稿中添加幻灯片。

You can add slides to a presentation using the createSlide() method of the XMLSlideShow class which is in the org.poi.xslf.usermodel package.

XSLFSlide slide1 = ppt.createSlide();

下面给出了打开现有的 PPT 并向其中添加幻灯片的完整程序 −

Given below is the complete program to open and add slides 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.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;

public class EditPresentation {
   public static void main(String ar[]) throws IOException {
      //opening an existing slide show
      File file = new File("example1.pptx");
      FileInputStream inputstream = new FileInputStream(file);
      XMLSlideShow ppt = new XMLSlideShow(inputstream);

      //adding slides to the slideshow
      XSLFSlide slide1 = ppt.createSlide();
      XSLFSlide slide2 = ppt.createSlide();

      //saving the changes
      FileOutputStream out = new FileOutputStream(file);
      ppt.write(out);

      System.out.println("Presentation edited successfully");
      out.close();
   }
}

将上述 Java 代码另存为 EditPresentation.java ,然后从命令提示符编译并执行它,如下所示 −

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 −

slides successfully added

带有新添加幻灯片输出的 PPT 文档如下所示 −

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

editexample1

将幻灯片添加到 PPT 后,你可以在幻灯片上添加、执行、读取和写入操作。

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

Apache POI PPT - Slide Layouts

在上一章中,你已经了解了如何创建空幻灯片以及如何向其中添加幻灯片。在本章中,您将学习如何获取可用幻灯片的列表,以及如何创建具有不同布局的幻灯片。

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

Available Slide layouts

PowerPoint 演示文稿具有幻灯片布局,您可以选择所需布局来编辑幻灯片。首先,让我们找出所有可用幻灯片布局的列表。

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

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

  2. You can get the list of the slide masters using the getSlideMasters() method of the XMLSlideShow class.

  3. You can get the list of the slide layouts from each slide master using the getSlideLayouts() method of the XSLFSlideMaster class.

  4. You can get the name of the slide layout from the layout object using the getType() method of the XSLFSlideLayout class.

Note − 所有这些类都属于 org.poi.xslf.usermodel 包。

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

下面提供了获取 PPT 中可用幻灯片布局的完整程序 −

Given below is the complete program to get the list of available slide layouts in the PPT −

import java.io.IOException;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlideLayout;
import org.apache.poi.xslf.usermodel.XSLFSlideMaster;

public class SlideLayouts {
   public static void main(String args[]) throws IOException {
      //create an empty presentation
      XMLSlideShow ppt = new XMLSlideShow();
      System.out.println("Available slide layouts:");

      //getting the list of all slide masters
      for(XSLFSlideMaster master : ppt.getSlideMasters()) {
         //getting the list of the layouts in each slide master
         for(XSLFSlideLayout layout : master.getSlideLayouts()) {
            //getting the list of available slides
            System.out.println(layout.getType());
         }
      }
   }
}

将上面的 Java 代码另存为 SlideLayouts.java ,然后按如下所示从命令提示符对其进行编译和执行 −

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

$javac SlideLayouts.java
$java SlideLayouts

它将编译和执行以生成以下输出 −

It will compile and execute to generate the following output −

Available slide 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

下面展示了一些适用于 MS-Office 360、2013 版本的幻灯片布局示例。

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

sample slide layouts

Title Layout

让我们使用标题布局在 PPT 中创建一个幻灯片。请按照以下步骤操作 −

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

Step 1 − 通过实例化来创建一个空演示文稿 XMLSlideShow 如下所示。

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

XMLSlideShow ppt = new XMLSlideShow();

Step 2 − 使用 getSlideMasters() 方法获取幻灯片母版列表。此后,使用索引选择所需的幻灯片母版,如下所示。

Step 2 − Get the list of slide masters using the getSlideMasters() method. Thereafter, select the desired slide master using the index as shown below.

XSLFSlideMaster slideMaster = ppt.getSlideMasters()[0];

这里我们获取在幻灯片母版数组中位于第 0 个位置的默认幻灯片母版。

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

Step 3 − 使用 XSLFSlideMaster 类的 getLayout() 方法获取所需的布局。此方法接受一个参数,你必须在其中传递 SlideLayoutclass 的静态变量之一,它代表我们的所需布局。此类中有多个变量,每个变量都代表一个幻灯片布局。

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

下面给出的代码片段演示如何创建一个标题布局 −

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

XSLFSlideLayout titleLayout = slideMaster.getLayout(SlideLayout.TITLE);

Step 4 − 通过传递一个幻灯片布局对象作为参数来创建一个新幻灯片。

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

XSLFSlide slide = ppt.createSlide(titleLayout);

Step 5 − 使用 XSLFSlide 类的 getPlaceholder() 方法选择一个占位符。此方法接受一个整数参数。通过向其传递 0 ,你将获取 XSLFTextShape 对象,使用此对象,你可以访问幻灯片的标题文本区。使用 setText() 方法设置标题,如下所示。

Step 5 − Select a placeholder using the getPlaceholder() method of the XSLFSlide 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 slide. Set the title using the setText() method as shown below.

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

下面给出了在演示文稿中使用标题布局创建幻灯片的完整程序 −

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

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xslf.usermodel.SlideLayout;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFSlideLayout;
import org.apache.poi.xslf.usermodel.XSLFSlideMaster;
import org.apache.poi.xslf.usermodel.XSLFTextShape;

public class TitleLayout {
   public static void main(String args[]) throws IOException {
      //creating presentation
      XMLSlideShow ppt = new XMLSlideShow();

      //getting the slide master object
      XSLFSlideMaster slideMaster = ppt.getSlideMasters().get(0);

      //get the desired slide layout
      XSLFSlideLayout titleLayout = slideMaster.getLayout(SlideLayout.TITLE);

      //creating a slide with title layout
      XSLFSlide slide1 = ppt.createSlide(titleLayout);

      //selecting the place holder in it
      XSLFTextShape title1 = slide1.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("slide cretated successfully");
      out.close();
   }
}

将上面的 Java 代码另存为 TitleLayout.java,然后按如下所示从命令提示符对其进行编译和执行 −

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.

slide created successfully

新加的标题版式幻灯片的 PPT 文档显示如下所示 -

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

TitleLayOut

Title and content Layout

使用标题和内容版式在 PPT 中创建幻灯片。遵循以下给出的步骤。

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

Step 1 − 通过实例化来创建一个空演示文稿 XMLSlideShow 如下所示。

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

XMLSlideShow ppt = new XMLSlideShow();

Step 2 - 使用 getSlideMasters() 方法获取幻灯片母版列表。使用索引选择所需的幻灯片母版,如下所示。

Step 2 − Get the list of slide masters using the getSlideMasters() method. Select the desired slide master using the index as shown below.

XSLFSlideMaster slideMaster = ppt.getSlideMasters()[0];

这里我们获取在幻灯片母版数组中位于第 0 个位置的默认幻灯片母版。

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

Step 3 - 使用 XSLFSlideMaster 类的 getLayout() 方法获取所需的版式。此方法接受一个参数,您必须在其中传递表示所需版式的 SlideLayout 类的 static 变量之一。此类中有几个表示幻灯片版式的变量。

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

以下代码片段显示如何创建标题和内容版式 -

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

XSLFSlideLayout contentlayout = slideMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);

Step 4 - 通过传递幻灯片版式对象作为参数来创建新幻灯片。

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

XSLFSlide slide = ppt.createSlide(SlideLayout.TITLE_AND_CONTENT);

Step 5 - 使用 XSLFSlide 类的 getPlaceholder() 方法选择占位符。此方法接受一个整数参数。通过将 1 传递给它,您将获得 XSLFTextShape 对象,使用该对象您可以访问幻灯片的内容区域。使用 setText() 方法设置标题,如下所示。

Step 5 − Select a placeholder using the getPlaceholder() method of the XSLFSlide 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 slide. Set the title using the setText() method as shown below.

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

Step 6 - 使用 XSLFTextShape 类的 clearText() 方法清除幻灯片中的现有文本。

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

body.clearText();

Step 7 - 使用 addNewTextParagraph() 方法添加新段落。现在使用 addNewTextRun() 方法向段落添加新的文本运行。现在将文本添加到文本运行,使用 setText() 方法,如下所示。

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 slide body");

下面给出了在演示文稿中使用标题布局创建幻灯片的完整程序 −

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

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xslf.usermodel.SlideLayout;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFSlideLayout;
import org.apache.poi.xslf.usermodel.XSLFSlideMaster;
import org.apache.poi.xslf.usermodel.XSLFTextShape;

public class TitleAndBodyLayout {
   public static void main(String args[]) throws IOException {
      //creating presentation
      XMLSlideShow ppt = new XMLSlideShow();

      //getting the slide master object
      XSLFSlideMaster slideMaster = ppt.getSlideMasters().get(0);

      //select a layout from specified list
      XSLFSlideLayout slidelayout = slideMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);

      //creating a slide with title and content layout
      XSLFSlide slide = ppt.createSlide(slidelayout);

      //selection of title place holder
      XSLFTextShape title = slide.getPlaceholder(0);

      //setting the title in it
      title.setText("introduction");

      //selection of body placeholder
      XSLFTextShape body = slide.getPlaceholder(1);

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

      //adding new paragraph
      body.addNewTextParagraph().addNewTextRun().setText("this is  my first slide 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("slide cretated successfully");
      out.close();
   }
}

将上述 Java 代码另存为 TitleLayout.java ,然后从命令提示符编译并执行它,如下所示 -

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 −

slide created successfully

新加的标题版式幻灯片的 PPT 文档显示如下所示 -

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

TitleAndContentLayout

以相同的方式,您也可以创建具有不同版式的幻灯片。

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

Apache POI PPT - Slide Management

完成本章后,你将能够删除、重新排序并在幻灯片上执行读写操作。

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

Changing a Slide

我们可以使用 setPageSize() 类使用 XMLSlideShow 方法更改幻灯片的页面大小。

We can change the page size of a slide using the setPageSize() method of the XMLSlideShow class.

最初创建一个演示文稿,如下所示 −

Initially create a presentation as shown below −

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

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

使用 getPageSize() 方法从 XMLSlideShow 类中获取当前幻灯片的大小。

Get the size of the current slide using the getPageSize() method of the XMLSlideShow class.

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

使用 setPageSize() 方法设置页面大小。

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 slide is given below −

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

public class ChangingSlide {
   public static void main(String args[]) throws IOException {
      //create file object
      File file = new File("TitleAndContentLayout.pptx");

      //create presentation
      XMLSlideShow ppt = new XMLSlideShow();

      //getting the current page size
      java.awt.Dimension pgsize = ppt.getPageSize();
      int pgw = pgsize.width; //slide width in points
      int pgh = pgsize.height; //slide 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("slide size changed to given dimentions ");
      out.close();
   }
}

保存上述 Java 代码为 ChangingSlide.java ,然后按照以下步骤从命令提示符处进行编译和执行 -

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

$javac ChangingSlide.java
$java ChangingSlide

它会编译并执行以生成以下输出。

It will compile and execute to generate the following output.

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

以下是更改幻灯片大小之前的演示文稿的快照 -

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

TitleAndContentLayout

更改大小后,幻灯片如下所示 -

The slide appears as follows after changing its size −

slideAfterChange

Reordering Slides

您可以使用 setSlideOrder() 方法设置幻灯片顺序。下面是设置幻灯片顺序的步骤。

You can set the slide order using the setSlideOrder() method. Given below is the procedure to set the order of the slides.

如以下所示打开现有的 PPT 文档 -

Open an existing PPT document as shown below −

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

使用 getSlides() 方法获取幻灯片,如下所示 -

Get the slides using the getSlides() method as shown below −

List<XSLFSlide> slides = ppt.getSlides();

从幻灯片数组中选择一个幻灯片,并使用 setSlideOrder() 方法更改顺序,如下所示 -

Select a slide from the array of the slides, and change the order using the setSlideOrder() method as shown below −

//selecting the fourth slide
XSLFSlide selectesdslide = slides.get(4);

//bringing it to the top
ppt.setSlideOrder(selectesdslide, 1);

下面是重新排列演示文稿中幻灯片的完整程序 -

Given below is the complete program to reorder the slides 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.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;

public class ReorderSlide {
   public static void main(String args[]) throws IOException {
      //opening an existing presentation
      File file = new File("example1.pptx");
      XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(file));

      //get the slides
      List<XSLFSlide> slides = ppt.getSlides();

      //selecting the fourth slide
      XSLFSlide selectesdslide = slides.get(13);

      //bringing it to the top
      ppt.setSlideOrder(selectesdslide, 0);

      //creating an file object
      FileOutputStream out = new FileOutputStream(file);

      //saving the changes to a file
      ppt.write(out);
      out.close();
   }
}

将以上 Java 代码保存为 ReorderSlide.java ,然后从命令提示符编译并执行它,如下所示:

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

$javac ReorderSlide.java
$java ReorderSlide

它会编译并执行以生成以下输出。

It will compile and execute to generate the following output.

Reordering of the slides is done

下面是重新排序幻灯片前的演示文稿的快照:

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

Before Reorder

重新排序幻灯片后,演示文稿会以如下方式出现。在这里,我们选中包括图像的幻灯片并将其移到顶部。

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

After Reorder

Deleting Slides

您可以使用 removeSlide() 方法来删除幻灯片。按照下列步骤删除幻灯片。

You can delete the slides using the removeSlide() method. Follow the steps given below to delete slides.

使用 XMLSlideShow 类打开现有的演示文稿,如下所示:

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

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

使用 removeSlide() 方法删除所需的幻灯片。此方法接受一个整数参数。将要删除的幻灯片的索引传递给此方法。

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

ppt.removeSlide(1);

以下是从演示文稿中删除幻灯片的程序:

Given below is the program to delete slides 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.XMLSlideShow;

public class Deleteslide {
   public static void main(String args[]) throws IOException {
      //Opening an existing slide
      File file = new File("image.pptx");
      XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(file));

      //deleting a slide
      ppt.removeSlide(1);

      //creating a file object
      FileOutputStream out = new FileOutputStream(file);

      //Saving the changes to the presentation
      ppt.write(out);
      out.close();
   }
}

将以上 Java 代码保存为 Deleteslide.java ,然后从命令提示符编译并执行它,如下所示:

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

$javac Deleteslide.java
$java Deleteslide

它将编译和执行以生成以下输出 −

It will compile and execute to generate the following output −

reordering of the slides is done

以下快照显示的是删除幻灯片前的演示文稿:

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

After Reorder

删除幻灯片后,演示文稿如下所示 −

After deleting the slide, the presentation appears as follows −

deleteslides

Apache POI PPT - Images

在本章中,您将学习如何向 PPT 添加图像以及如何从中读取图像。

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

Adding Image

您可以使用 createPicture()XSLFSlide 方法向演示文稿添加图像。此方法以字节数组格式接受图像。因此,您需要创建要添加到演示文稿的图像的字节数组。

You can add images to a presentation using the createPicture() method of XSLFSlide. 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.

按照给定的步骤向演示文稿添加图像。使用 XMLSlideShow 创建一个空幻灯片,如下所示 −

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

XMLSlideShow ppt = new XMLSlideShow();

在其中使用 createSlide() 创建一个空演示文稿。

Create an empty presentation in it using createSlide().

XSLFSlide slide = ppt.createSlide();

读取要添加的图像文件,并使用 IOUtils 类的 IOUtils.toByteArray() 将其转换为字节数组,如下所示 −

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));

使用 addPicture() 将图像添加到演示文稿。此方法接受两个变量:要添加的图像的字节数组格式和表示图像文件格式的静态变量。 addPicture() 方法的用法如下所示 −

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);

使用 createPicture() 将图像嵌入到幻灯片中,如下所示 −

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

XSLFPictureShape pic = slide.createPicture(idx);

下面给出了在演示文稿的幻灯片中添加图像的完整程序 −

Given below is the complete program to add an image to the slide 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.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFPictureData;
import org.apache.poi.xslf.usermodel.XSLFPictureShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;

public class AddingImage {
   public static void main(String args[]) throws IOException {
      //creating a presentation
      XMLSlideShow ppt = new XMLSlideShow();

      //creating a slide in it
      XSLFSlide slide = ppt.createSlide();

      //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 slide with given picture on it
      XSLFPictureShape pic = slide.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();
   }
}

将上述 Java 代码另存为 AddingImage.java ,然后从命令提示符编译并执行,如下所示 −

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 slides is done

带有新添加幻灯片的演示文稿(其中包含图像)如下所示 −

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

AddingImage

Reading Image

您可以使用 XMLSlideShow 类中的 getPictureData() 方法获取所有图片的数据。以下程序从演示文稿读取图像 −

You can get the data of all the pictures using the getPictureData() method of the XMLSlideShow 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.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFPictureData;

public class Readingimage {
   public static void main(String args[]) throws IOException {
      //open an existing presentation
      File file = new File("addingimage.pptx");
      XMLSlideShow ppt = new XMLSlideShow(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();
   }
}

将上述 Java 代码另存为 Readingimage.java ,然后从命令提示符编译并执行,如下所示 −

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

在本章中,你将学习如何在演示文稿中创建超链接。

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

你可以使用 XSLFTextRun 类的 createHyperlink() 方法来读取演示文稿中的超链接。按照下面给出的步骤,在演示文稿中创建一个超链接。

You can read the hyperlinks in a presentation using the createHyperlink() method of the XSLFTextRun class. Follow the procedure given below to create a hyperlink in a presentation.

使用 XMLSlideShow 类创建一个空演示文稿,如下所示:

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

XMLSlideShow ppt = new XMLSlideShow();

创建一个空幻灯片,并使用主体和内容布局创建一个文本框和幻灯片的正文。

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

//create an empty presentation
XSLFSlideMaster slideMaster = ppt.getSlideMasters()[0];

//creating a slide with title and content layout
XSLFSlideLayout slidelayout = slideMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);
XSLFSlide slide = ppt.createSlide(slidelayout);

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

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

创建文本运行对象,并设置其文本,如下所示:

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

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

使用 XSLFTextRun 类的 createHyperlink() 方法创建一个超链接,如下所示:

Create a hyperlink using the createHyperlink() method of the XSLFTextRun class as shown below −

XSLFHyperlink link = textRun.createHyperlink();

使用 XSLFHyperlink 类的 setAddress() 方法设置超链接的链接地址,如下所示:

Set the link address to the hyperlink using the setAddress() method of XSLFHyperlink class as shown below −

link.setAddress("https://www.tutorialspoint.com/");

下面给出了在演示文稿中创建超链接的完整程序:

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

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

import org.apache.poi.xslf.usermodel.SlideLayout;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFHyperlink;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFSlideLayout;
import org.apache.poi.xslf.usermodel.XSLFSlideMaster;
import org.apache.poi.xslf.usermodel.XSLFTextRun;
import org.apache.poi.xslf.usermodel.XSLFTextShape;

public class CreatingHyperlinks {
   public static void main(String args[]) throws IOException {
      //create an empty presentation
      XMLSlideShow ppt = new XMLSlideShow();

      //getting the slide master object
      XSLFSlideMaster slideMaster = ppt.getSlideMasters().get(0);

      //select a layout from specified list
      XSLFSlideLayout slidelayout = slideMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);

      //creating a slide with title and content layout
      XSLFSlide slide = ppt.createSlide(slidelayout);

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

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

      //adding new paragraph
      XSLFTextRun textRun = body.addNewTextParagraph().addNewTextRun();

      //setting the text
      textRun.setText("Tutorials point");

      //creating the hyperlink
      XSLFHyperlink link = textRun.createHyperlink();

      //setting the link address
      link.setAddress("https://www.tutorialspoint.com/");

      //create the file object
      File file = new File("hyperlink.pptx");
      FileOutputStream out = new FileOutputStream(file);

      //save the changes in a file
      ppt.write(out);
      System.out.println("slide created successfully");
      out.close();
   }
}

将上述 Java 代码保存为 CreatingHyperlinks.java ,然后从命令提示符编译并执行,如下所示:

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

$javac CreatingHyperlinks.java
$java CreatingHyperlinks

它将编译和执行以生成以下输出 −

It will compile and execute to generate the following output −

slide created successfully

新添加的幻灯片及其正文中的超链接如下所示:

The newly added slide with the hyperlink in its body looks as follows −

CreateHyperlink

Apache POI PPT - Reading Shapes

您可以使用 XSLFShape 类中的 getShapeName() 方法获取演示文稿中使用的形状的数量。下面是用于从演示文稿读取形状的程序 −

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.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;

public class ReadingShapes {
   public static void main(String args[]) throws IOException {
      //creating a slideshow
      File file = new File("shapes.pptx");
      XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(file));

      //get slides
      List<XSLFSlide> slide = ppt.getSlides();

      //getting the shapes in the presentation
      System.out.println("Shapes in the presentation:");
      for (int i = 0; i < slide.size(); i++){
         List<XSLFShape> sh = slide.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();
   }
}

将上述 Java 代码另存为 ReadingShapes.java ,然后从命令提示符编译并执行,如下所示 −

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 slide with the various shapes appears as follows −

ReadingShapes

Apache POI PPT - Formatting Text

可以使用 XSLFTextRun 类的方法设置演示文稿中的文本格式。为此,您需要通过选择幻灯片布局之一来创建一个 XSLFTextRun 类对象,如下所示 −

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 slide layouts as shown below −

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

//getting the slide master object
XSLFSlideMaster slideMaster = ppt.getSlideMasters().get(0);

//select a layout from specified list
XSLFSlideLayout slidelayout = slideMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);

//creating a slide with title and content layout
XSLFSlide slide = ppt.createSlide(slidelayout);

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

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

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

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

您可以使用 setFontSize() 设置演示文稿中文本的字体大小。

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, italic, underline, strikeout) to the text in a presentation.

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

//change the text it to italic format
run.setItalic(true)

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

//underline the text
run.setUnderlined(true);

要在段落之间换行,请使用 XSLFTextParagraph 类的 addLineBreak() ,如下所示 −

To have line 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.SlideLayout;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFSlideLayout;
import org.apache.poi.xslf.usermodel.XSLFSlideMaster;
import org.apache.poi.xslf.usermodel.XSLFTextParagraph;
import org.apache.poi.xslf.usermodel.XSLFTextRun;
import org.apache.poi.xslf.usermodel.XSLFTextShape;

public class TextFormating {
   public static void main(String args[]) throws IOException {
      //creating an empty presentation
      XMLSlideShow ppt = new XMLSlideShow();

      //getting the slide master object
      XSLFSlideMaster slideMaster = ppt.getSlideMasters().get(0);

      //select a layout from specified list
      XSLFSlideLayout slidelayout = slideMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);

      //creating a slide with title and content layout
      XSLFSlide slide = ppt.createSlide(slidelayout);

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

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

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

      //formatting line 1

      XSLFTextRun run1 = paragraph.addNewTextRun();
      run1.setText("This is a colored line");

      //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 line
      paragraph.addLineBreak();

      //formatting line 2

      XSLFTextRun run2 = paragraph.addNewTextRun();
      run2.setText("This is a bold line");
      run2.setFontColor(java.awt.Color.CYAN);

      //making the text bold
      run2.setBold(true);
      paragraph.addLineBreak();

      //formatting line 3

      XSLFTextRun run3 = paragraph.addNewTextRun();
      run3.setText(" This is a striked line");
      run3.setFontSize(12.0);

      //making the text italic
      run3.setItalic(true);

      //strike through the text
      run3.setStrikethrough(true);
      paragraph.addLineBreak();

      //formatting line 4

      XSLFTextRun run4 = paragraph.addNewTextRun();
      run4.setText(" This an underlined line");
      run4.setUnderlined(true);

      //underlining 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();
   }
}

将以上代码保存为 TextFormating.java ,然后从命令提示符编译并执行,如下所示 −

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 slide with formatted text appears as follows −

FormattingText

Apache POI PPT - Merging

你可以使用 XMLSlideShow 类的 importContent() 方法合并多个演示文稿。以下是合并两个演示文稿的完整程序 −

You can merge multiple presentations using the importContent() method of the XMLSlideShow 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.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;

public class MergingMultiplePresentations {

      public static void main(String args[]) throws IOException {

      //creating empty presentation
      XMLSlideShow ppt = new XMLSlideShow();

      //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);
         XMLSlideShow src = new XMLSlideShow(inputstream);

         for(XSLFSlide srcSlide : src.getSlides()) {

            //merging the contents
            ppt.createSlide().importContent(srcSlide);
         }
      }

      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();
   }
}

将以上代码保存为 MergingMultiplePresentations.java ,然后从命令提示符编译并执行,如下所示 −

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 slides. Here you can see the content of the earlier slides merged together.

combinedPresentation

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.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;

public class PptToImage {
   public static void main(String args[]) throws IOException {
      //creating an empty presentation
      File file=new File("pptToImage.pptx");
      XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(file));

      //getting the dimensions and size of the slide
      Dimension pgsize = ppt.getPageSize();
      List<XSLFSlide> slide = ppt.getSlides();
      BufferedImage img = null;
      for (int i = 0; i < slide.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
         slide.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();
   }
}

将以上 Java 代码保存为 PpttoPNG.java ,然后从命令提示符编译并执行,如下所示 −

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