Extracting Plain Text from HTML Files Using Java

Free Spire.Doc for Java is a library that can process HTML by loading it into a document object model and extracting its textual content. This approach is useful for data processing, text cleaning, and content parsing tasks where only the core text is needed, without HTML tags, styles, or scripts.

Library Setup

Add the following dependency to you're 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>
<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.doc.free</artifactId>
    <version>14.3.1</version>
</dependency>

For Gradle, include this line:

implementation 'e-iceblue:spire.doc.free:14.3.1@jar'

Alternative, download the JAR file manually and add it to your classpath.

Implementation Example

The following Java class demonstrates loading an HTML file, extracting its text, and saving the result to a plain text file.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;

import java.io.PrintWriter;

public class HtmlTextExtractor {
    public static void main(String[] args) {
        // Instantiate a Document object
        Document htmlDoc = new Document();
        
        // Load the HTML file, specifying its format
        htmlDoc.loadFromFile("input.html", FileFormat.Html);
        
        // Retrieve the plain text content
        String extractedContent = htmlDoc.getText();
        
        // Write the extracted text to an output file
        try (PrintWriter writer = new PrintWriter("output.txt")) {
            writer.print(extractedContent);
            System.out.println("Text extraction successful. Output saved to output.txt");
        } catch (Exception e) {
            System.err.println("Error writing file: " + e.getMessage());
        }
    }
}

Code Explanation

  • A Document instance is created to hold the content.
  • The loadFromFile method parses the specified HTML file. The FileFormat.Html parameter instructs the library to interpret the input as HTML.
  • The getText() method returns a string containing all textual nodes from the document, effectively stripping away HTML markup.
  • The result is written to a .txt file using a PrintWriter within a try-with-resources statement for safe resource management.

Considerations and Limitations

  • The extracted text is a simplified representation. Complex layouts, such as tables or specific indentation, are not preserevd.
  • Content within <script> and <style> tags is generally ignored and not included in the output.
  • The free version of the library is suitable for basic tasks and smaller documents but may have limitations for large-scale or complex processing requirements.

Tags: java html Text Extraction Free Spire.Doc Data Processing

Posted on Wed, 19 Aug 2026 16:40:22 +0000 by Ton Wibier