DEV Community

Cover image for How to Find and Highlight Text in a PDF with Java
Dheeraj Malik
Dheeraj Malik

Posted on

How to Find and Highlight Text in a PDF with Java

When you review a purchase agreement, the phrase “payment terms” might appear in the main contract and again in an addendum. A Java program can tell you which pages to check, pinpoint each match on the page, and save a highlighted copy to share with a reviewer.

The examples below use the same three-page PDF. You can run each one on its own, depending on whether you need page numbers, coordinates, or a marked-up document.

Set Up the Maven Project

Add this repository and dependency to your project's pom.xml.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>

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

Prepare a Sample PDF

Save a searchable PDF as purchase-agreement.pdf in the program's working directory. To reproduce the examples, put the following text on three separate pages and export the document as a PDF.

Page Sample text
1 Payment terms: invoices are due within 30 days of receipt. Any change to the payment terms must be agreed in writing.
2 The supplier must deliver the equipment by the agreed date.
3 Payment terms in the signed addendum take precedence.

All three examples use TextFindParameter.IgnoreCase, so both “Payment terms” and “payment terms” match.

Find the Pages That Contain a Keyword

To see which pages mention the phrase, create a PdfTextFinder for each page and call find(). The size of the result tells you how many matches that page contains. The program skips pages with zero matches and adds 1 to the zero-based page index before printing it.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.texts.PdfTextFinder;
import com.spire.pdf.texts.TextFindParameter;

import java.util.EnumSet;

public class FindPdfKeywordPages {

    public static void main(String[] args) {
        String keyword = "payment terms";

        PdfDocument document = new PdfDocument();
        try {
            document.loadFromFile("purchase-agreement.pdf");
            int totalMatches = 0;

            for (int i = 0; i < document.getPages().getCount(); i++) {
                PdfTextFinder finder = new PdfTextFinder(document.getPages().get(i));
                finder.getOptions().setTextFindParameter(EnumSet.of(TextFindParameter.IgnoreCase));
                int matches = finder.find(keyword).size();

                if (matches > 0) {
                    System.out.printf("Page %d: %d%n", i + 1, matches);
                    totalMatches += matches;
                }
            }

            System.out.printf("Total matches for \"%s\": %d%n", keyword, totalMatches);
        } finally {
            document.dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

For the sample agreement, the console output looks like this.

Page 1: 2
Page 3: 1
Total matches for "payment terms": 3
Enter fullscreen mode Exit fullscreen mode

Get the Page Coordinates of Each Match

Each match comes back as a PdfTextFragment. Its getPositions() method returns an array of points. A match that spans multiple lines can return more than one point, so the code prints every point for that match.

Coordinates are measured in points (pt) from the top-left corner of the page. The x-coordinate increases to the right, and the y-coordinate increases down the page.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.texts.PdfTextFinder;
import com.spire.pdf.texts.PdfTextFragment;
import com.spire.pdf.texts.TextFindParameter;

import java.awt.geom.Point2D;
import java.util.EnumSet;
import java.util.Locale;

public class GetPdfKeywordPositions {

    public static void main(String[] args) {
        String keyword = "payment terms";

        PdfDocument document = new PdfDocument();
        try {
            document.loadFromFile("purchase-agreement.pdf");

            for (int i = 0; i < document.getPages().getCount(); i++) {
                PdfTextFinder finder = new PdfTextFinder(document.getPages().get(i));
                finder.getOptions().setTextFindParameter(EnumSet.of(TextFindParameter.IgnoreCase));
                int matchNumber = 0;

                for (PdfTextFragment match : finder.find(keyword)) {
                    matchNumber++;
                    for (Point2D position : match.getPositions()) {
                        System.out.printf(Locale.ROOT,
                                "Page %d, match %d: x=%.2f pt, y=%.2f pt%n",
                                i + 1, matchNumber, position.getX(), position.getY());
                    }
                }
            }
        } finally {
            document.dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Here are the coordinates from the sample PDF. The values will vary with the layout of your file.

Page 1, match 1: x=72.00 pt, y=72.29 pt
Page 1, match 2: x=172.07 pt, y=96.29 pt
Page 3, match 1: x=72.00 pt, y=72.29 pt
Enter fullscreen mode Exit fullscreen mode

Highlight All Matches in the PDF

Search each page as before, then call highLight(Color.YELLOW) on every match. Once all pages have been processed, save the document to a new file so you have a separate copy for review.

import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.texts.PdfTextFinder;
import com.spire.pdf.texts.PdfTextFragment;
import com.spire.pdf.texts.TextFindParameter;

import java.awt.Color;
import java.util.EnumSet;

public class HighlightPdfKeywords {

    public static void main(String[] args) {
        String keyword = "payment terms";

        PdfDocument document = new PdfDocument();
        try {
            document.loadFromFile("purchase-agreement.pdf");

            for (int i = 0; i < document.getPages().getCount(); i++) {
                PdfTextFinder finder = new PdfTextFinder(document.getPages().get(i));
                finder.getOptions().setTextFindParameter(EnumSet.of(TextFindParameter.IgnoreCase));

                for (PdfTextFragment match : finder.find(keyword)) {
                    match.highLight(Color.YELLOW);
                }
            }

            document.saveToFile("purchase-agreement-highlighted.pdf", FileFormat.PDF);
        } finally {
            document.dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Open purchase-agreement-highlighted.pdf to see two yellow highlights on page 1 and one on page 3.

Common Issues

Why does the search miss text I can see on the page?

Try copying the phrase from your PDF viewer into a plain-text editor. If the page is an image-only scan, run OCR first to create a searchable text layer. If you can copy the text, check for extra spaces or line breaks in the copied phrase.

Why do the page numbers differ from the ones printed in the PDF?

The program counts from the first page in the file. If a cover page comes before the main text, the page labeled “1” in the footer may be page 2 in the search results.

Can I remove the highlights from the PDF viewer's comments panel?

highLight() writes the highlight into the page content. To give reviewers control over individual highlights in the comments panel, create PDF highlight annotations.

Top comments (0)