Skip to main content

Search and Process Text in PDF Documents

  • 3 minutes to read

The PDF Document API allows you to search for text and process matching text fragments. You can locate text, modify its formatting, remove it from the document, or use search results in other document-related operations.

Search Results

Call the PdfDocument.findText method to search a PDF document. Specify search options to control case sensitivity, whole-word matching, and the page range.

The findText method returns a collection of TextSearchInfo objects. Each object contains search results for a single page.

A TextSearchInfo object exposes the following collections:

Collection Access Method Description
Matches getMatches() Access the location of matching text on the page. Use this collection to create redaction annotations or perform other operations that require page coordinates.
Groups getGroups() Access matching text fragments. Use this collection to modify text formatting.

Find Text

Call the findText method to search for text in a PDF document.

The following code snippet searches for the word “keyword“ in a PDF document:

import java.nio.channels.*;
import java.nio.file.*;

public class Main {
    public static void main(String[] args) throws Exception {
        try (PdfDocument pdfDocument = new PdfDocument(FileChannel.open(
                Path.of("document.pdf")))) {

            TextSearchOptions options = new TextSearchOptions(
                true,   // Match case.
                true    // Match whole words.
            );

            // Search all pages in the document.
            int pageCount = pdfDocument.getPages().size();
            Iterable<TextSearchInfo> results = pdfDocument.findText(
                    "keyword",
                    options,
                    0,
                    pageCount - 1);

            // Process search results.
            for (TextSearchInfo result : results) {

            }

            // Save the document.
        }
    }
}

Format Search Results

Use the getGroups() method to access matching text fragments.

A text fragment can contain both matching and non-matching text. Call the split(TextMatchGroup group) method to separate these parts, modify matching fragments, and replace the original fragment.

The following code snippet changes the font color and underline color of all matching text fragments:

import com.devexpress.docs.pdf.*;

import java.nio.channels.*;
import java.nio.file.*;

public class Main {
    public static void main(String[] args) throws Exception {
        try (PdfDocument pdfDocument = new PdfDocument(FileChannel.open(
                Path.of("document.pdf")))) {

            TextSearchOptions options = new TextSearchOptions(
                true, // Match case.
                true // Match whole words.
            );

            // Search all pages in the document.
            int pageCount = pdfDocument.getPages().size();
            Iterable<TextSearchInfo> results = pdfDocument.findText(
                    "keyword",
                    options,
                    0,
                    pageCount - 1);

            // Process search results.
            for (TextSearchInfo result : results) {
                for (TextMatchGroup group : result.getGroups()) {

                    // Split the fragment into matching and non-matching parts.
                    TextFragment[][] matched = new TextFragment[1][];
                    TextFragment[][] notMatched = new TextFragment[1][];

                    // Split fragment into matched and non-matched parts.
                    TextFragment[] fragments =
                            group.getFragment().split(
                                    group,
                                    matched, () -> {},
                                    notMatched, () -> {});

                    SolidFill fill = new SolidFill(PdfColor.getRed());

                    // Apply formatting to matching fragments.
                    for (TextFragment[] fragment : matched) {
                        fragment[0].setUnderline(true);
                        fragment[0].setUnderlineFill(fill);
                        fragment[0].setForegroundFill(fill);
                    }

                    // Replace the original fragment.
                    pdfDocument
                            .getPages()
                            .get(result.getPageIndex())
                            .getFragments().
                            replace(group.getFragment(), fragments);
                }
            }

            // Save the document to a PDF file.
            try (WritableByteChannel writableByteChannel =
                FileChannel.open(Path.of("result.pdf"),
                    StandardOpenOption.CREATE,
                    StandardOpenOption.WRITE,
                    StandardOpenOption.TRUNCATE_EXISTING)) {

                pdfDocument.save(writableByteChannel);
            }
        }
    }
}

Remove Found Text

Call the PdfDocument.removeText() method and pass the search results returned by the findText method.

The following code snippet removes all occurrences of the word “keyword“ from a PDF document:

// Search for text.
Iterable<TextSearchInfo> results = pdfDocument.findText("keyword");

// Remove all matching text.
pdfDocument.removeText(results);

Tip

Use redaction annotations to permanently remove sensitive information from a PDF document. Refer to the following help topic for additional information: Redaction Annotations.