Skip to main content

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>

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.

PageSample text
1Payment terms: invoices are due within 30 days of receipt. Any change to the payment terms must be agreed in writing.
2The supplier must deliver the equipment by the agreed date.
3Payment 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();
        }
    }
}

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

Page 1: 2
Page 3: 1
Total matches for "payment terms": 3

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();
        }
    }
}

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

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();
        }
    }
}

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.

Comments

Popular posts from this blog

3 Ways to Generate Word Documents from Templates in Java

A template is a document with pre-applied formatting like styles, tabs, line spacing and so on. You can quickly generate a batch of documents with the same structure based on the template. In this article, I am going to show you the different ways to generate Word documents from templates programmatically in Java using Free Spire.Doc for Java library. Prerequisite First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file. <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>...

Insert and Extract OLE objects in Word in Java

You can use OLE (Object Linking and Embedding) to include content from other programs, such as another Word document, an Excel or PowerPoint document to an existing Word document. This article demonstrates how to insert and extract embedded OLE objects in a Word document in Java by using Free Spire.Doc for Java API.   Add dependencies First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file.     <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>    ...

Simple Java Code to Convert Excel to PDF in Java

This article demonstrates a simple solution to convert an Excel file to PDF in Java by using free Excel API – Free Spire.XLS for Java . The following examples illustrate two possibilities to convert Excel to PDF:      Convert the whole Excel file to PDF     Convert a particular Excel Worksheet to PDF Before start with coding, you need to Download Free Spire.XLS for Java package , unzip it and import Spire.Xls.jar file from the lib folder in your project as a denpendency. 1. Convert the whole Excel file to PDF Spire.XLS for Java provides saveToFile method in Workbook class that enables us to easily save a whole Excel file to PDF. import com.spire.xls.FileFormat; import com.spire.xls.Workbook; public class ExcelToPDF {     public static void main(String[] args){         //Create a Workbook         Workbook workbook = new Workbook();   ...