DEV Community

Cover image for How to Extract Text from PowerPoint in Java: All Slides, Specific Slides, and Tables
Dheeraj Malik
Dheeraj Malik

Posted on

How to Extract Text from PowerPoint in Java: All Slides, Specific Slides, and Tables

PowerPoint presentations often contain text that needs to be reused in reports, documentation, or other files. Instead of copying it slide by slide, you can use Java to extract the text and save it to a separate file.

This article covers three scenarios: extracting text from an entire presentation, reading text from a specific slide, and extracting text from PowerPoint tables.

1. Add the Maven Dependency

First, add a PowerPoint processing library to your Java project. If you're using Maven, include the following repository and dependency in your 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>11.9.10</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

For the examples below, we'll use a presentation named report.pptx containing slide titles, body text, project updates, and tables.

Each example is a standalone Java program that saves the extracted content to a UTF-8 text file.

2. Extract Text from All PowerPoint Slides

To extract text from an entire presentation, you can loop through its slides and examine the shapes on each one.

In PowerPoint, titles, text boxes, and many shapes containing text can be accessed through the IAutoShape interface. Each text frame contains paragraphs, and their text can be retrieved using ParagraphEx.getText().

Here's the complete code:

import com.spire.presentation.*;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ExtractAllPPTText {

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

        Presentation presentation = new Presentation();

        try {
            // Load the PowerPoint presentation
            presentation.loadFromFile("report.pptx");

            StringBuilder result = new StringBuilder();

            // Loop through all slides
            for (int i = 0;
                 i < presentation.getSlides().getCount();
                 i++) {

                ISlide slide = presentation.getSlides().get(i);

                // Add the slide number
                result.append("Slide ")
                      .append(i + 1)
                      .append(System.lineSeparator());

                // Loop through shapes on the slide
                for (Object shape : slide.getShapes()) {

                    if (shape instanceof IAutoShape) {

                        IAutoShape autoShape = (IAutoShape) shape;

                        // Read text from each paragraph
                        for (Object item :
                                autoShape.getTextFrame()
                                         .getParagraphs()) {

                            ParagraphEx paragraph =
                                    (ParagraphEx) item;

                            String text = paragraph.getText();

                            if (text != null &&
                                    !text.trim().isEmpty()) {
                                result.append(text)
                                      .append(System.lineSeparator());
                            }
                        }
                    }
                }

                result.append(System.lineSeparator());
            }

            // Save the extracted text as UTF-8
            Files.write(
                    Paths.get("ppt-all-text.txt"),
                    result.toString()
                          .getBytes(StandardCharsets.UTF_8));

            System.out.println("Text extraction completed.");

        } finally {
            presentation.dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The program creates ppt-all-text.txt, with the extracted text grouped by slide number.

The main methods are:

  • getSlides() retrieves the slides in the presentation.

  • getShapes() provides access to the shapes on each slide.

  • getTextFrame().getParagraphs() retrieves the paragraphs inside a text-containing shape.

  • ParagraphEx.getText() returns the text of each paragraph.

The code skips empty paragraphs and adds a slide number before each group of text.

One limitation is worth noting: this example extracts text from IAutoShape objects, not every type of content in a PowerPoint file. Text in tables, speaker notes, images, and some other objects requires separate handling.

Also, the extracted text follows the order of shapes in the slide's collection, which may differ from their visual reading order.

3. Extract Text from a Specific PowerPoint Slide

Sometimes you only need the text from one slide. For example, you might want to extract a project summary from slide 3 without processing the rest of the presentation.

You can access a particular slide using presentation.getSlides().get(index) and then read the text from its shapes.

The following example extracts text from the third slide:

import com.spire.presentation.*;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ExtractSingleSlideText {

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

        Presentation presentation = new Presentation();

        try {
            // Load the PowerPoint presentation
            presentation.loadFromFile("report.pptx");

            // Specify the slide number
            int slideNumber = 3;

            // Check whether the slide exists
            if (slideNumber < 1 ||
                    slideNumber > presentation.getSlides().getCount()) {
                throw new IllegalArgumentException(
                        "The specified slide does not exist.");
            }

            // Get the specified slide
            ISlide slide = presentation.getSlides()
                    .get(slideNumber - 1);

            StringBuilder result = new StringBuilder();

            // Loop through shapes on the slide
            for (Object shape : slide.getShapes()) {

                if (shape instanceof IAutoShape) {

                    IAutoShape autoShape = (IAutoShape) shape;

                    // Extract text from each paragraph
                    for (Object item :
                            autoShape.getTextFrame()
                                     .getParagraphs()) {

                        ParagraphEx paragraph =
                                (ParagraphEx) item;

                        String text = paragraph.getText();

                        if (text != null &&
                                !text.trim().isEmpty()) {
                            result.append(text)
                                  .append(System.lineSeparator());
                        }
                    }
                }
            }

            // Save the extracted text
            Files.write(
                    Paths.get("slide-3-text.txt"),
                    result.toString()
                          .getBytes(StandardCharsets.UTF_8));

            System.out.println("Slide 3 text extracted.");

        } finally {
            presentation.dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The program saves the text from the third slide to slide-3-text.txt.

Keep in mind that slide indexes start at zero:

  • get(0) accesses slide 1.

  • get(1) accesses slide 2.

  • get(2) accesses slide 3.

That's why the code uses slideNumber - 1 to convert the slide number into a collection index.

It also checks whether the requested slide exists before trying to access it.

If you need text from several selected slides, you can use an array of slide numbers and process only those slides.

4. Extract Text from Tables in PowerPoint

PowerPoint presentations may also contain tables, such as project schedules, budget summaries, or comparison data.

Unlike ordinary text boxes, tables store their text in individual cells. To read that content, you can locate ITable objects, loop through their rows and columns, and extract the text from each cell.

The following example searches all slides for tables and saves their contents as tab-separated text.

import com.spire.presentation.*;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ExtractPPTTableText {

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

        Presentation presentation = new Presentation();

        try {
            // Load the PowerPoint presentation
            presentation.loadFromFile("report.pptx");

            StringBuilder result = new StringBuilder();

            // Loop through all slides
            for (int i = 0;
                 i < presentation.getSlides().getCount();
                 i++) {

                ISlide slide = presentation.getSlides().get(i);

                // Find tables on the slide
                for (Object shape : slide.getShapes()) {

                    if (shape instanceof ITable) {

                        ITable table = (ITable) shape;

                        result.append("Table on Slide ")
                              .append(i + 1)
                              .append(System.lineSeparator());

                        // Get the number of rows and columns
                        int rowCount =
                                table.getTableRows().getCount();

                        int columnCount =
                                table.getColumnsList().getCount();

                        // Loop through table cells
                        for (int row = 0; row < rowCount; row++) {

                            for (int col = 0;
                                 col < columnCount;
                                 col++) {

                                // Read text from the cell
                                String text = table.get(col, row)
                                        .getTextFrame()
                                        .getText();

                                if (text != null) {
                                    // Replace line breaks and tabs
                                    text = text.replace("\r", " ")
                                               .replace("\n", " ")
                                               .replace("\t", " ");

                                    result.append(text);
                                }

                                // Separate columns with tabs
                                if (col < columnCount - 1) {
                                    result.append("\t");
                                }
                            }

                            result.append(System.lineSeparator());
                        }

                        result.append(System.lineSeparator());
                    }
                }
            }

            // Save the extracted table text
            Files.write(
                    Paths.get("ppt-table-text.txt"),
                    result.toString()
                          .getBytes(StandardCharsets.UTF_8));

            System.out.println("Table text extraction completed.");

        } finally {
            presentation.dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The code uses three methods to access table content:

  • getTableRows().getCount() returns the number of rows.

  • getColumnsList().getCount() returns the number of columns.

  • table.get(col, row) retrieves a cell using its column and row indexes.

Notice that table.get() takes the column index first, followed by the row index. Both indexes start at zero.

Once a cell is retrieved, getTextFrame().getText() returns its text.

For example, suppose a slide contains this table:

Task Owner Status
Module A Alex Completed
Module B Emma In Progress

The extracted text would look approximately like this:

Table on Slide 2
Task    Owner   Status
Module A    Alex    Completed
Module B    Emma    In Progress
Enter fullscreen mode Exit fullscreen mode

Columns are separated by tabs, while rows are separated by line breaks. This makes the output easier to read or import into another application.

The example also replaces line breaks and tabs inside individual cells with spaces to keep each table row on one line.

For tables with merged cells, a straightforward row-and-column loop may produce empty or repeated positions. Those cases may require additional handling based on the table structure.

5. Things to Keep in Mind

Text Inside Images Requires OCR

If a slide contains text as part of an image, such as a screenshot or scanned document, it cannot be extracted using ordinary text frame methods.

You would need optical character recognition (OCR) to identify the text in those images.

Not All PowerPoint Text Is Stored in Regular Shapes

Slide titles and text boxes can typically be accessed through IAutoShape, while table content is accessed through ITable.

Speaker notes, chart labels, text inside grouped objects, and other elements may require different handling.

If you need to extract all available text from a presentation, check which object types are present instead of assuming a single loop will capture everything.

Plain Text Does Not Preserve Formatting

Saving extracted content as TXT removes the original PowerPoint formatting, including font styles, colors, positions, and slide layouts.

If you need to preserve information such as heading levels or table structures, consider adding markers during extraction or using a structured output format instead.

Use UTF-8 for Text Files

All three examples use StandardCharsets.UTF_8 when writing the output files.

This helps preserve non-ASCII characters, including Chinese, Japanese, and other multilingual text, across different operating systems.

6. Conclusion

Extracting text from PowerPoint in Java depends on where the text is stored.

Before processing a presentation, it's worth checking whether its content consists of regular text, tables, images, or other objects. This helps you choose the appropriate extraction method and avoid missing content.

Top comments (0)