DEV Community

jelizaveta
jelizaveta

Posted on

How to Extract Text from PDFs in Java

Java development often involves PDF-related work including invoice analysis, contract text retrieval and document archiving. Different from readable Word/TXT files, PDFs adopt fixed layout closed architectures, so native Java APIs fail to extract text and professional third-party components are mandatory.

Spire.PDF for Java outperforms other mainstream PDF frameworks for enterprise text extraction with light weight, no extra dependencies or Adobe plugins and precise parsing. It supports all standard PDF versions and page-targeted text extraction. This article provides copy-and-run Maven-based code to implement batch full-page PDF text extraction with automatic TXT output.

Tool Introduction: Spire.PDF for Java

Spire.PDF for Java is a professional, standalone Java PDF manipulation component. It does not rely on third-party software such as Adobe Acrobat or Reader and can independently perform full-scenario operations including PDF creation, reading, editing, conversion, and text/image extraction. Its core advantages include:

  • Lightweight and efficient: Small component size, fast execution speed, and low memory usage, suitable for web, desktop, and backend API projects across various Java environments.
  • Accurate parsing: Preserves the original text layout order of PDFs, effectively avoiding issues like disordered text, missing content, and garbled characters.
  • Comprehensive functionality: Supports full-document extraction, single-page extraction, and region-specific text extraction, accommodating diverse business needs.
  • Zero environment dependencies: Developed purely in Java, cross-platform compatible with Windows, Linux, and macOS, and supports JDK 8 and above.

Maven Environment Configuration

Spire.PDF is not hosted in the Maven Central Repository, so you need to manually configure the official repository and then add the corresponding dependency. Below is the complete Maven configuration—simply paste it into your project's pom.xml file to activate it.

Configure the Repository

Add the Spire official repository under the <repositories> tag in pom.xml to pull the component dependency package:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
Enter fullscreen mode Exit fullscreen mode

Add the Core Dependency

After configuring the repository, add the core Spire.PDF dependency. This article uses the stable version 11.7.5, which offers strong compatibility:

<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>11.7.5</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Once configured, refresh your Maven project and wait for the dependency to be downloaded and imported automatically.

Complete Code Implementation: Full PDF Text Extraction

This practical implementation focuses on the core functionality: loading a local PDF file, extracting all text content page by page, concatenating the full document text, and finally saving it as a local TXT file. It also includes robust I/O exception handling and resource release to ensure code reliability.

The implementation uses four core classes from Spire.PDF:

  • PdfDocument : The main operational class for PDF documents, used for loading and closing PDF files.
  • PdfPageBase : Represents a PDF page object, providing access to individual page information.
  • PdfTextExtractor : The text extractor, serving as the core parsing tool.
  • PdfTextExtractOptions : Configuration class for text extraction, allowing customization of extraction rules.

Complete Runnable Code

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.texts.PdfTextExtractOptions;
import com.spire.pdf.texts.PdfTextExtractor;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

/**
 * PDF text extraction utility class.
 * Functionality: Extracts all text from a PDF page by page and saves it as a TXT file.
 */
public class ExtractAllTextFromPDF {
    public static void main(String[] args){
        // 1. Initialize the PDF document object and load a local PDF file (replace with your own PDF path)
        PdfDocument doc = new PdfDocument();
        try {
            doc.loadFromFile("sample.pdf");

            // 2. Define a StringBuilder to store text from all pages
            StringBuilder fullText = new StringBuilder();

            // 3. Iterate through all pages and extract text page by page
            int pageCount = doc.getPages().getCount();
            for (int i = 0; i < pageCount; i++) {
                // Get the current page
                PdfPageBase page = doc.getPages().get(i);
                // Create a text extractor for the current page
                PdfTextExtractor extractor = new PdfTextExtractor(page);
                // Extract page text using default options
                String pageText = extractor.extract(new PdfTextExtractOptions());
                // Append the text, adding blank lines between pages for better readability
                fullText.append(pageText).append("\n\n\n\n");
            }

            // 4. Write the extracted text to a TXT file
            try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
                writer.write(fullText.toString());
                System.out.println("PDF text extraction complete! Saved to output.txt");
            } catch (IOException e) {
                System.err.println("Failed to write text file: " + e.getMessage());
                e.printStackTrace();
            }
        } catch (Exception e) {
            System.err.println("Failed to load PDF or extract text: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // 5. Close the document and release file resources
            if (doc != null) {
                doc.close();
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Code Explanation

1. Document loading and initialization

Create a PdfDocument instance and call loadFromFile() to load a local PDF file. Both absolute and relative paths are supported, accommodating different project deployment scenarios.

2. Page-by-page text extraction

Retrieve the total page count and iterate through each page. Create a separate PdfTextExtractor for each page to accurately parse single-page text, avoiding confusion across multiple pages. Use StringBuilder to concatenate all page texts—this greatly improves parsing efficiency for large PDFs compared to direct string concatenation.

3. Persistent text storage

Use BufferedWriter for efficient character writing, outputting the concatenated full text to a TXT file. The try-with-resources statement automatically closes the I/O stream to prevent resource leaks.

4. Resource release and exception handling

Force-close the PDF document in the finally block to release file resources. Exceptions from file loading, text extraction, and I/O writing are all caught, with detailed error messages printed to facilitate troubleshooting.

Running the Project and Validating Results

Prerequisites for Execution

  • Place a test PDF file named sample.pdf in the project root directory, or modify the file path in the code to point to your actual PDF file.
  • Ensure that the Maven dependency has been loaded successfully with no package conflicts or missing dependencies.

Execution Results

After running the main method, the console will output PDF text extraction complete! Saved to output.txt to indicate success. An output.txt file will be automatically generated in the project root directory, containing the complete text from all PDF pages. Pages are separated by blank lines for clear, well-formatted output without garbled characters or missing text.

Common Issues and Optimization Suggestions

Fixing Text Layout Issues

The default extraction rules may cause minor layout shifts. You can enable simplified extraction mode to improve text formatting. Modify the extraction code as follows:

PdfTextExtractOptions options = new PdfTextExtractOptions();
options.setSimpleExtraction(true); // Enable simplified extraction for better layout
String pageText = extractor.extract(options);
Enter fullscreen mode Exit fullscreen mode

Handling Scanned PDFs

The solution described in this article applies to searchable native PDFs (electronically generated PDFs). For scanned image-based PDFs, text extraction alone cannot retrieve content—you would need to integrate with an OCR component like Spire.OCR for image text recognition.

Performance Optimization Tips

For very large PDFs, consider extracting pages individually and writing asynchronously to avoid loading the entire content at once and causing memory overflow. Additionally, strictly enforce document closure logic to prevent file handle accumulation.

Conclusion

This article demonstrated a simple and stable approach to full PDF text extraction using Spire.PDF for Java. By configuring the official Maven repository, adding the core dependency, parsing text page by page, and persisting it to a file, you can quickly implement PDF text parsing in your business logic.

The solution features concise code, high stability, and no environment dependencies, making it directly applicable to various Java business scenarios such as PDF document archiving, intelligent parsing, content retrieval, and data masking. Beyond text extraction, Spire.PDF also supports image extraction, table parsing, document splitting/merging, format conversion, and more, catering to the majority of PDF processing development needs.

Top comments (0)