DEV Community

jelizaveta
jelizaveta

Posted on

How to Extract Text and Images from Word Documents Using Java

Parsing Word documents is a common yet challenging task in Java enterprise development. Use cases range from document content archiving and structured data extraction to batch asset exporting. While Apache POI has long been the go-to solution, it often falls short with its verbose APIs, poor image extraction support, and compatibility issues with newer docx formats—problems that can turn a simple task into a debugging nightmare.

Spire.Doc for Java offers a compelling alternative. This lightweight, high-performance library requires no Office installation and excels at extracting text, images, tables, and more with remarkable precision. Its intuitive API and robust parsing engine make it an ideal choice for most enterprise-grade development scenarios.

In this tutorial, we'll walk through:

  • Setting up Spire.Doc via Maven
  • Extracting full-text content from Word documents and exporting it as TXT
  • Batch exporting embedded images as PNG files

Each example comes with complete, runnable code and detailed explanations—perfect for developers of all experience levels. Let's dive in!

1. Technical Overview and Environment Setup

1.1 Component Advantages

Spire.Doc for Java is a professional-grade Word processing library that supports full parsing of both .doc and .docx formats. Its core advantages include:

  • No Office dependency — Works without installing Microsoft Office
  • Clean, intuitive API — Minimal boilerplate, maximum productivity
  • High parsing accuracy — Preserves formatting and structure faithfully
  • Batch processing support — Handle multiple documents efficiently

These features effectively resolve common pain points like garbled text, image loss, and formatting corruption frequently encountered with native POI-based solutions.

1.2 Maven Dependency Configuration

First, add the Spire.Doc for Java repository and dependency to your 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.doc</artifactId>
        <version>14.7.4</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Once configured, refresh your Maven project to automatically download the dependency package, and you're ready to begin document parsing development.

2. Example 1: Extracting All Text from Word and Exporting to TXT

Spire.Doc provides the minimalist getText() method to retrieve all plain text content from a document in one go, automatically filtering out images, formatting symbols, controls, and other non-text elements. It also supports persisting the extracted text as a TXT file for convenient content archiving.

Complete Code Implementation

import com.spire.doc.Document;
import java.io.FileWriter;
import java.io.IOException;

public class ExtractText {
    public static void main(String[] args) throws IOException {
        // 1. Create document object and load local Word document
        Document document = new Document();
        document.loadFromFile("sample1.docx");

        // 2. Extract all text content from the document
        String text = document.getText();

        // 3. Write the text to a local TXT file
        writeStringToTxt(text, "ExtractedText.txt");
        System.out.println("Word text extraction complete, saved to ExtractedText.txt");
    }

    /**
     * Utility method to write text content to a TXT file
     * @param content The extracted text content
     * @param txtFileName The output file name
     * @throws IOException IO exception
     */
    public static void writeStringToTxt(String content, String txtFileName) throws IOException {
        // Write to file in append mode
        FileWriter fWriter = new FileWriter(txtFileName, true);
        try {
            fWriter.write(content);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            // Force flush the stream and close resources to avoid memory leaks
            try {
                fWriter.flush();
                fWriter.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Walkthrough

  1. Initialize the Document object — Create a new Document instance and load the target Word file using loadFromFile(), which supports both relative and absolute paths.
  2. Extract text content — Call getText() to quickly parse the full document text. This method automatically preserves the original text layout logic while stripping away non-text elements.
  3. Persist to file — A custom utility method writes the extracted content to a TXT file in append mode. The finally block ensures the stream is properly flushed and closed, preventing IO resource leaks.

3. Example 2: Batch Extracting Embedded Images from Word and Exporting as PNG

Images in Word documents are nested within document nodes and cannot be retrieved via a simple one-line API call. Spire.Doc supports traversing the document's tree structure to precisely identify all image nodes, batch extract them, and export in PNG format—compatible with all embedded images in body text, paragraphs, headers, footers, and text boxes.

Complete Code Implementation

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
import com.spire.doc.interfaces.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;

public class ExtractImage {
    public static void main(String[] args) throws IOException {
        // 1. Load the Word document
        Document document = new Document();
        document.loadFromFile("sample2.docx");

        // 2. Initialize a queue to traverse the document tree nodes
        Queue<ICompositeObject> nodes = new LinkedList<>();
        nodes.add(document);
        List<BufferedImage> images = new ArrayList<>();

        // 3. Deep traverse the document to filter image nodes
        while (nodes.size() > 0) {
            ICompositeObject node = nodes.poll();
            for (int i = 0; i < node.getChildObjects().getCount(); i++) {
                IDocumentObject child = node.getChildObjects().get(i);
                // Recursively add composite nodes for continued deep traversal
                if (child instanceof ICompositeObject) {
                    nodes.add((ICompositeObject) child);
                }
                // Identify image nodes and collect images
                else if (child.getDocumentObjectType() == DocumentObjectType.Picture) {
                    DocPicture picture = (DocPicture) child;
                    images.add(picture.getImage());
                }
            }
        }

        // 4. Create output directory and batch save images
        File outputDir = new File("output");
        if (!outputDir.exists()) {
            outputDir.mkdirs();
        }
        for (int i = 0; i < images.size(); i++) {
            File file = new File(String.format("output/extractImage-%d.png", i));
            ImageIO.write(images.get(i), "PNG", file);
        }
        System.out.println("Image extraction complete, extracted " + images.size() + " images");
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Walkthrough

  1. Load the document — As in the previous example, create a Document instance and load the target Word file.
  2. Set up traversal structures — A Queue manages the document nodes for deep traversal, while a List collects all extracted images.
  3. Traverse and filter — The algorithm performs a breadth-first traversal of the document tree:
    • When encountering a composite node (containing child elements), it's added to the queue for further traversal.
    • When a picture node is identified via DocumentObjectType.Picture, the image data is extracted and stored.
  4. Export images — The output directory is created if it doesn't already exist. Each image is then written as a PNG file with an ordered, predictable filename for easy management.

4. Runtime Considerations and Common Issues

To ensure smooth execution, keep the following points in mind:

Issue Recommendation
Document path errors Place test documents in the project root directory during development. For production, use absolute paths to avoid FileNotFoundException.
Dependency download failures If Maven cannot pull the dependency, manually download the JAR from the official repository and import it into your project as a local library.
Missing or blank images The traversal logic covers all document nodes, ensuring compatibility with complex layouts, nested structures, and mixed text-image content. No image loss or blank output should occur.
High memory usage during batch processing When processing multiple large documents, manually release resources after each document using document.dispose() to prevent memory leaks.

5. Summary

This article demonstrated two core functionalities—full-text extraction and batch image export from Word documents—using the Spire.Doc for Java component. Compared to traditional POI-based approaches, this solution offers:

  • Cleaner, more maintainable code — Minimal boilerplate and intuitive method calls
  • Superior compatibility — Handles both legacy .doc and modern .docx formats flawlessly
  • Higher parsing stability — Preserves content integrity without garbled text or image loss
  • Production-ready performance — Suitable for enterprise-scale batch processing

This solution can be quickly adopted in a wide range of business scenarios, including document archiving systems, content search engines, asset extraction pipelines, and office automation workflows. Developers can easily extend the functionality presented here—for example, extracting text from specific sections, customizing output image formats, or building batch traversal pipelines for large document collections.

With Spire.Doc for Java, Word document processing no longer needs to be a headache. Start building your document parsing solution today with the code and techniques covered in this guide.

Top comments (0)