DEV Community

Cover image for Make Scanned Legal PDFs Searchable in Python with OCR
AI Engine
AI Engine

Posted on Originally published at ai-engine.net

Make Scanned Legal PDFs Searchable in Python with OCR

A large part of every law firm archive is pictures of paper: old case files, signed agreements, discovery productions and court records scanned years ago. They open fine, but Ctrl+F finds nothing, and nobody can search a whole matter for one phrase. This tutorial shows how to make scanned legal PDFs searchable in Python, in two ways: a searchable copy of each PDF that works in any viewer, and a full-text index that searches every page of the case file at once.

Everything was tested on a real scanned document: the 1890 opinion of the Supreme Court of California in Colton v. Stanford, 62 pages, public domain on Wikimedia Commons. Two modern documents written for this tutorial were added, a settlement agreement and a research memo, printed and scanned. The names in them are fictional.

Want to make your own scanned files searchable? Get a free key for the OCR Wizard API.


What you need

Python 3, a RapidAPI key in the RAPIDAPI_KEY environment variable, requests for the API and pymupdf to write the text layer. SQLite ships with Python.

pip install requests pymupdf
export RAPIDAPI_KEY=your_key
Enter fullscreen mode Exit fullscreen mode

Step 1: OCR every page of the case file

The /ocr-pdf endpoint reads up to 10 pages per request, set with first_page and last_page. Save this as ocr_case_file.py. It sends the pages in windows of 10 and caches the result in a JSON file next to each PDF, so every page is read only once:

import json
import os
import sys
from pathlib import Path

import pymupdf
import requests

API_URL = "https://ocr-wizard.p.rapidapi.com/ocr-pdf"
HEADERS = {
    "x-rapidapi-key": os.environ["RAPIDAPI_KEY"],
    "x-rapidapi-host": "ocr-wizard.p.rapidapi.com",
}
CHUNK = 10  # pages per request


def ocr_pdf(path):
    """OCR every page of a scanned PDF, 10 pages per request."""
    page_count = pymupdf.open(path).page_count
    pages = []
    for first in range(1, page_count + 1, CHUNK):
        last = min(first + CHUNK - 1, page_count)
        with open(path, "rb") as f:
            r = requests.post(
                API_URL,
                headers=HEADERS,
                files={"pdf_file": f},
                data={"first_page": first, "last_page": last},
                timeout=180,
            )
        r.raise_for_status()
        pages += r.json()["body"]["pages"]
        print(f"  {path.name}: pages {first}-{last} done")
    return pages


def ocr_cached(path):
    """OCR a PDF once and keep the result next to it."""
    cache = path.with_suffix(".ocr.json")
    if cache.exists():
        return json.loads(cache.read_text())
    pages = ocr_pdf(path)
    cache.write_text(json.dumps(pages))
    return pages


if __name__ == "__main__":
    for pdf in sorted(Path(sys.argv[1]).glob("*.pdf")):
        if pdf.stem.endswith("-searchable"):
            continue
        pages = ocr_cached(pdf)
        words = sum(len(p["fullText"].split()) for p in pages)
        print(f"{pdf.name}: {len(pages)} pages, {words} words")
Enter fullscreen mode Exit fullscreen mode
$ python ocr_case_file.py casefile
colton-v-stanford.pdf: 62 pages, 18045 words
research-memo-2025-02.pdf: 1 pages, 232 words
settlement-agreement-2025.pdf: 2 pages, 396 words
Enter fullscreen mode Exit fullscreen mode

The 62 pages took 49 seconds, under a second per page. Each page comes back with fullText, the detected language, imageSize (the pixel size of the page the API read) and annotations, one entry per word with its boundingPoly. The word positions make the next step possible.


Step 2: Add a hidden text layer to each PDF

A searchable PDF is the same scan with invisible text placed exactly over each printed word. Viewers search and select that text, but draw only the image. Save this as make_searchable.py:

import sys
from pathlib import Path

import pymupdf

from ocr_case_file import ocr_cached

FONT = pymupdf.Font("helv")


def add_text_layer(pdf_path):
    """Write an invisible OCR text layer over every scanned page."""
    pages = ocr_cached(pdf_path)
    doc = pymupdf.open(pdf_path)
    for page, ocr in zip(doc, pages):
        scale = page.rect.width / ocr["imageSize"][0]  # [width, height] in pixels
        writer = pymupdf.TextWriter(page.rect)
        for word in ocr["annotations"]:
            xs = [p["x"] * scale for p in word["boundingPoly"]]
            ys = [p["y"] * scale for p in word["boundingPoly"]]
            width, height = max(xs) - min(xs), max(ys) - min(ys)
            if width <= 0 or height <= 0:
                continue
            # font size that makes the word as wide as it is on the scan
            size = min(height, width / FONT.text_length(word["text"], fontsize=1))
            writer.append((min(xs), max(ys) - height * 0.2), word["text"], font=FONT, fontsize=size)
        writer.write_text(page, render_mode=3)  # 3 = invisible, still searchable
    out = pdf_path.with_name(pdf_path.stem + "-searchable.pdf")
    doc.save(out, garbage=3, deflate=True)
    return out


if __name__ == "__main__":
    out = add_text_layer(Path(sys.argv[1]))
    term = sys.argv[2]
    pages = [p.number + 1 for p in pymupdf.open(out) if p.search_for(term)]
    print(f"{out.name}: '{term}' on pages {pages}")
Enter fullscreen mode Exit fullscreen mode
$ python make_searchable.py casefile/colton-v-stanford.pdf "cestui que trust"
colton-v-stanford-searchable.pdf: 'cestui que trust' on pages [9, 10, 11, 16, 19, 20, 21, 24, 26, 32, 33, 38, 39]
Enter fullscreen mode Exit fullscreen mode

The scale converts API pixels to PDF points with the imageSize of each page. The font size makes each invisible word as wide as the printed one, so selection lands on the right word. render_mode=3 writes text that is never drawn. The 62 pages took 2.9 seconds, and the file went from 2.9 MB to 3.2 MB.

Page 11 of the scanned opinion before and after: no result on the original, compromise agreement highlighted on the searchable copy even across a line break

On this page the phrase is printed as compromise agree- and ment on two lines, and the viewer still finds it.


Step 3: Index the whole case file in SQLite

A searchable PDF answers "where is this phrase in this file?". A case file needs "which documents and pages mention it?". SQLite has full-text search built in (FTS5). Save this as index_case_file.py:

import re
import sqlite3
import sys
from pathlib import Path

from ocr_case_file import ocr_cached


def clean(text):
    # join words split across lines: "pro-\ntect" -> "protect"
    text = re.sub(r"(\w)-\n(\w)", r"\1\2", text)
    return text.replace("\n", " ")


def build_index(folder, db_path="case_index.db"):
    db = sqlite3.connect(db_path)
    db.execute("DROP TABLE IF EXISTS pages")
    db.execute(
        "CREATE VIRTUAL TABLE pages USING fts5("
        "file, page UNINDEXED, text, tokenize='porter unicode61')"
    )
    for pdf in sorted(Path(folder).glob("*.pdf")):
        if pdf.stem.endswith("-searchable"):
            continue
        for number, page in enumerate(ocr_cached(pdf), start=1):
            db.execute(
                "INSERT INTO pages VALUES (?, ?, ?)",
                (pdf.name, number, clean(page["fullText"])),
            )
    db.commit()
    return db


if __name__ == "__main__":
    db = build_index(sys.argv[1])
    files, pages = db.execute("SELECT count(DISTINCT file), count(*) FROM pages").fetchone()
    print(f"indexed {pages} pages from {files} files")
Enter fullscreen mode Exit fullscreen mode
$ python index_case_file.py casefile
indexed 65 pages from 3 files
Enter fullscreen mode Exit fullscreen mode

Indexing takes 0.3 seconds because it reads the cached JSON. The porter tokenizer matches word forms, so release also finds released.

The clean function matters. Printed opinions split long words across lines with a hyphen, and this one has 356 of them. Indexed as raw text, pro- and tect never match protect. What the join changes on the opinion:

Search Pages, raw text Pages, after the join
investigation 15 17
transaction 13 16
"compromise agreement" 10 11
protect 1 2

Step 4: Search across every document

Save this as search_case_file.py. It returns the best pages first, with the matched words in brackets:

import sqlite3
import sys


def search(query, db_path="case_index.db", limit=5):
    db = sqlite3.connect(db_path)
    return db.execute(
        "SELECT file, page, snippet(pages, 2, '[', ']', '...', 12) "
        "FROM pages WHERE pages MATCH ? ORDER BY rank LIMIT ?",
        (query, limit),
    ).fetchall()


if __name__ == "__main__":
    query = sys.argv[1]
    print(f"> {query}")
    for file, page, snippet in search(query):
        print(f"  {file} p.{page}: {snippet}")
Enter fullscreen mode Exit fullscreen mode
$ python search_case_file.py '"compromise agreement"'
> "compromise agreement"
  research-memo-2025-02.pdf p.1: ...Marlow, setting aside a prior [compromise agreement] Question Dunmore asked whether it...
  colton-v-stanford.pdf p.15: _7_ About two years after the execution of the [compromise agreement] plaintiff...
  colton-v-stanford.pdf p.10: ...by the defendants before the [compromise agreement] was executed, that there were...
  colton-v-stanford.pdf p.27: ...her, and entered into the [compromise agreement] after a careful and thorough...
Enter fullscreen mode Exit fullscreen mode

One query covers the 1890 opinion and the 2025 memo together; the phrase is on 12 pages in total.

Terminal output of three searches across the scanned case file, with matched words highlighted

FTS5 understands the operators lawyers already use in research databases:

Query Finds Result on the case file
"settlement payment" exact phrase both pages of the settlement agreement
releas* prefix the agreement, the memo and 4 pages of the opinion
NEAR(fraud compromise, 5) both words within 5 words opinion page 35: "operated as a compromise of the alleged fraud"
confidential* AND "governing law" both terms on the page settlement agreement, page 2
fiduciary NOT trustee first term without the second opinion pages drop from 10 to 2

Production tips

  • Index new documents at upload: OCR the scan when it enters the matter, write the searchable copy and insert its pages. Let a nightly job catch up on the archive.
  • Keep the original scan: file the searchable copy alongside it, not instead of it.
  • Never pay twice for a page: the cached JSON holds text and word positions, so a new index or text layer needs no new API call.
  • Filter by matter: add the client and matter number to each row so a search never shows another client's pages.
  • Extract fields from contracts: see OCR scanned contracts in Python.

Full tutorial with images: Make Scanned Legal PDFs Searchable on ai-engine.net.


Next step

Get a free key on the OCR Wizard API page, copy a scanned case file into a folder and run the four scripts.

Top comments (0)