DEV Community

Jack9012
Jack9012

Posted on

Find and Highlight Text in PDF Files with Python

In document processing, data analysis, content review, and similar workflows, you may often need to search PDF files for specific text and highlight the matching content so that important information can be identified more quickly.

Automate PDF Text Highlighting

Python provides a wide range of PDF processing libraries that make this kind of automation relatively easy to implement. In this article, we will introduce two practical approaches for finding and highlighting text in PDF files: exact text matching and regular-expression-based matching.

1. Library and Environment Setup

In this tutorial, we will use Free Spire.PDF for Python to search for text and add highlight annotations to PDF documents.

The library provides convenient APIs for page traversal, exact text searching, regular expression matching, and custom highlight colors, so there is no need to manually work with low-level PDF structures.

One limitation to keep in mind is that the free version supports PDF documents with up to 10 pages . This is generally sufficient for lightweight testing, small documents, and simple document-processing tasks.

Before getting started, install the required package with pip:

pip install spire.pdf.free
Enter fullscreen mode Exit fullscreen mode

2. Scenario 1: Find and Highlight Exact Text Across a PDF

This approach is suitable when you already know the exact keyword or phrase you want to locate. The program can iterate through every page in the PDF and highlight all occurrences of the target text.

For example, the following code searches for the text "cloud service" throughout the document and highlights every match.

Complete Code

from spire.pdf import *
from spire.pdf.common import *

# Create a PdfDocument object and load the PDF file
pdf = PdfDocument()
pdf.LoadFromFile("inpue.pdf")

# Iterate through all pages in the PDF document
for i in range(pdf.Pages.Count):
    page = pdf.Pages.get_Item(i)

    # Create a text finder for the current page
    pdfTextFinder = PdfTextFinder(page)

    # Set the search parameter to find exact matches
    pdfTextFinde.Options.Parameter = TextFindParameter.IgnoreCase

    # Find all occurrences of the target text on the page
    result = pdfTextFinder.Find("cloud service")

    # Highlight all matched text in cyan
    for find in result:
        find.HighLight(Color.get_Cyan())

# Save the processed PDF document
pdf.SaveToFile("output/result.pdf")

# Release document resources
pdf.Close()
Enter fullscreen mode Exit fullscreen mode

How the Code Works

  1. Load the PDF document A PdfDocument object is created, and the LoadFromFile() method is used to open the source PDF.
  2. Iterate through each page The program loops through all pages in the document to ensure that matching text is not missed.
  3. Search for the target text A PdfTextFinder object is created for each page. The Find() method performs an exact search and returns all matching text fragments.
  4. Apply highlighting Each matching result is processed with the HighLight() method. In this example, cyan is used as the highlight color, but it can be replaced with another supported color.
  5. Save and close the document Finally, the modified PDF is saved to a new file, and Close() is called to release the document resources.

3. Scenario 2: Highlight Text Using Regular Expressions

In many cases, the text you want to find does not have a fixed value but follows a consistent pattern.

Typical examples include:

  • Numbers
  • Percentages
  • Phone numbers
  • Dates
  • Email addresses

For these situations, regular expressions provide a more flexible way to search for matching text.

In the following example, we use a regular expression to find and highlight integers, decimal numbers, and percentages.

Complete Code

from spire.pdf import *
from spire.pdf.common import *

# Create a PdfDocument object and load the PDF file
pdf = PdfDocument()
pdf.LoadFromFile("input.pdf")

# Get the first page of the PDF
# Change the page index if you want to process another page
page = pdf.Pages.get_Item(0)

# Create a text finder for the page
pdfTextFinder = PdfTextFinder(page)

# Enable regular expression matching
pdfTextFinder.Options.Parameter = TextFindParameter.Regex

# Regular expression for integers, decimals, and percentages
# Examples: 10, 99.9, 50%
pattern = r'\d+(?:\.\d+)?%?'

# Find all text fragments that match the pattern
result = pdfTextFinder.Find(pattern)

# Highlight the matched text in deep pink
for find in result:
    find.HighLight(Color.get_DeepPink())

# Save the processed PDF document
pdf.SaveToFile("output/result.pdf")

# Release document resources
pdf.Close()
Enter fullscreen mode Exit fullscreen mode

Key Points

  1. Enable regular expression mode Set Options.Parameter to TextFindParameter.Regex to switch from standard text searching to regular-expression matching.
  2. Define the matching pattern The regular expression:
   \d+(?:\.\d+)?%?
Enter fullscreen mode Exit fullscreen mode

matches several common numeric formats, including integers, decimal numbers, and percentages.

You can replace it with another pattern to search for phone numbers, dates, email addresses, or other structured text.

  1. Process a specific page This example searches only the first page of the PDF. If you need to search the entire document, you can combine this approach with the page loop used in the first example.
  2. Customize the highlight color The highlight color can be changed by using another supported color value. This makes it possible to apply different visual styles for different types of matched content.

4. Common Issues and Optimization Tips

1. The PDF Cannot Be Saved

Make sure that the output directory already exists before saving the file.

If the output folder does not exist, Python may raise a file-path-related error.

You can create the directory automatically with:

import os

os.makedirs("output", exist_ok=True)
Enter fullscreen mode Exit fullscreen mode

2. The PDF Exceeds the Page Limit

The free version supports PDF documents with up to 10 pages.

For longer documents, you can split the PDF into smaller files before performing the search and highlight operation.

3. Improving Search Accuracy

By default, the search operation may match text fragments containing the specified keyword.

If you need more precise matching, such as whole-word matching or case-sensitive searching, you can configure the corresponding options through the text finder's Options settings.

5. Conclusion

This article demonstrated two ways to find and highlight text in PDF documents with Python: exact text matching and regular-expression-based matching.

Exact matching works well when the target keyword is already known, while regular expressions are more suitable for structured or variable content such as numbers, percentages, dates, and other formatted data.

Both approaches require relatively little code and can be easily integrated into automated document-processing scripts. For small and short PDF files, they provide a straightforward way to identify important content, prepare documents for further data extraction, and reduce the amount of manual document review required.

Top comments (0)