Tutorial

RAG on Scanned PDFs: Ask a Case File Questions and Get Page Citations in Python

Build RAG over scanned PDFs in Python: OCR every page once, clean the scan noise, search by meaning and keyword, make the model quote its sources, check every quote and highlight it on the scanned page. Tested live on a 65 page legal case file.

Three scanned PDFs of a legal case file, 65 pages, turned into an answer with a citation: the quoted sentence is highlighted on the scanned memo page and marked as found in the source

This tutorial uses the OCR Wizard API. See the docs, live demo, and pricing.

A litigation team wants to ask its case file questions in plain English: "can the client undo the settlement?", "how much did she draw?". The case file is scanned. Most RAG tutorials start from text that is already there, and a scanned page has none. This guide builds RAG over scanned PDFs in Python, with an answer that cites the file and page, quotes that are checked in code, and the quoted words highlighted on the scan.

Every output below comes from a live run on 4 December 2026, using the OCR Wizard API for the OCR. The case file is the one from our searchable legal PDF tutorial: the 1890 opinion of the Supreme Court of California in Colton v. Stanford, 62 pages scanned from a library copy, plus a one page research memo and a two page settlement agreement written for these tutorials.

Why a RAG Pipeline Sees Nothing in a Scan

The first thing a RAG loader does is read the text layer of each PDF. On our case file:

text
research-memo-2025-02.pdf       1 page,  0 words in text layer
settlement-agreement-2025.pdf   2 pages, 0 words in text layer

The memo and the agreement are pure images. The Colton PDF does carry a text layer, added when the book was digitized in 2008, but it reads "tlie" for "the", "wdiich" for "which", "ivould" for "would", and contains 105 stray ^ characters. So the pipeline ignores existing text layers and runs every page of every file through the same OCR, which also returns the word positions used for highlighting in step 6.

What You Need

  • A RapidAPI key for the OCR Wizard API in RAPIDAPI_KEY.
  • A key for the language model that writes the answers. We used an OpenAI model in OPENAI_API_KEY; any chat model that can return JSON works, the prompt is plain text.
  • pip install requests pymupdf numpy pillow fastembed openai. SQLite comes with Python.
  • The PDFs in a case folder, and the four scripts below next to it.

Step 1: OCR Every Page Once

/ocr-pdf reads up to 10 pages per call, chosen with first_page and last_page. For each page it returns the full text and every word with its box on the page image. ocr_cached saves the result next to the PDF, so building the index again, changing the chunk size or adding a highlight never calls the API twice for the same file.

python
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")
text
$ python ocr_case_file.py case
  colton-v-stanford.pdf: pages 1-10 done
  colton-v-stanford.pdf: pages 11-20 done
  colton-v-stanford.pdf: pages 21-30 done
  colton-v-stanford.pdf: pages 31-40 done
  colton-v-stanford.pdf: pages 41-50 done
  colton-v-stanford.pdf: pages 51-60 done
  colton-v-stanford.pdf: pages 61-62 done
colton-v-stanford.pdf: 62 pages, 18045 words
  research-memo-2025-02.pdf: pages 1-1 done
research-memo-2025-02.pdf: 1 pages, 232 words
  settlement-agreement-2025.pdf: pages 1-2 done
settlement-agreement-2025.pdf: 2 pages, 396 words

65 pages in 51 seconds, 9 calls. The text came out identical to the run we made for the searchable PDF tutorial on 25 November.

Step 2: Clean the Scan Before Chunking

Here is the start of page 11 as OCR returns it, line by line, exactly as printed on the scan:

text
COWAN LIBRARY, 1936
F
•
-3-
That, under such circumstances, the compromise agree-
ment should not be set aside, even though the trustee did
not impart to the cestui que trust all the knowledge of the
transactions which he might have acquired by diligent and
skillful search.

A library stamp, a stray letter, a bullet, the printed page number, and a word cut in half by a hyphen at the end of a line. Over the whole opinion, 356 words are split that way. Left as they are, "agree-" and "ment" are two words that match neither a keyword search nor the meaning of "agreement". The book also has a bookplate, blank pages and a library due date slip.

clean_page drops page numbers and stray marks, joins the split words, and skips pages that are not running text. The test is simple: on a bookplate, a title page or a date slip, most letters are capitals. The first two sentences of page 11 after cleaning:

text
COWAN LIBRARY, 1936 That, under such circumstances, the compromise agreement should not be
set aside, even though the trustee did not impart to the cestui que trust all the
knowledge of the transactions which he might have acquired by diligent and skillful
search.

One line stays: COWAN LIBRARY, 1936, a stamp printed on a single page. A rule that removes it would also remove headings such as SETTLEMENT AGREEMENT, and one stamp does not hurt a search.

Step 3: Chunk and Index the Case File

Each page is cut into passages of 120 words that overlap by 30, so a sentence cut at a boundary is still whole in one of them. Passages never cross a page: a citation must point to one page. Each passage goes into two indexes: SQLite FTS5 for keywords, and a vector from a small embedding model that runs on your own machine, so the text of the case file does not leave it at this stage.

python
import re
import sqlite3
import sys
from pathlib import Path

import numpy as np
from fastembed import TextEmbedding

from ocr_case_file import ocr_cached

EMBED = TextEmbedding("BAAI/bge-small-en-v1.5")  # runs locally, about 70 MB
CHUNK_WORDS, OVERLAP = 120, 30


def is_prose(text):
    """Bookplates, library slips and title pages are mostly capitals."""
    letters = re.findall(r"[A-Za-z]", text)
    return len(text.split()) >= 40 and sum(c.islower() for c in letters) > len(letters) / 2


def clean_page(text):
    """Remove scan noise from one OCR page and rebuild running text."""
    keep = [
        line for line in (l.strip() for l in text.split("\n"))
        if not re.fullmatch(r"[-_.\s]*\d[\d.+]*[-_.\s]*", line)  # page numbers: -3-, _7_, 22-
        and len(re.sub(r"\W", "", line)) > 2  # stray marks: F, *, •
    ]
    text = "\n".join(keep)
    text = re.sub(r"(\w)-\n(\w)", r"\1\2", text)  # agree-\nment -> agreement
    text = re.sub(r"\s+", " ", text).strip()
    return text if is_prose(text) else ""


def chunk(text):
    words = text.split()
    step = CHUNK_WORDS - OVERLAP
    return [" ".join(words[i:i + CHUNK_WORDS]) for i in range(0, max(len(words) - OVERLAP, 1), step)]


def build(folder, db_path="rag.db"):
    db = sqlite3.connect(db_path)
    db.execute("DROP TABLE IF EXISTS chunks")
    db.execute("CREATE VIRTUAL TABLE chunks USING fts5(file, page UNINDEXED, text, tokenize='porter unicode61')")
    for pdf in sorted(Path(folder).glob("*.pdf")):
        for number, page in enumerate(ocr_cached(pdf), start=1):
            text = clean_page(page["fullText"])
            for piece in chunk(text) if text else []:
                db.execute("INSERT INTO chunks VALUES (?, ?, ?)", (pdf.name, number, piece))
    db.commit()
    texts = [t for (t,) in db.execute("SELECT text FROM chunks ORDER BY rowid")]
    vectors = np.array(list(EMBED.embed(texts)), dtype=np.float32)
    np.save(Path(db_path).with_suffix(".npy"), vectors)
    return len(texts)


if __name__ == "__main__":
    print(f"{build(sys.argv[1])} chunks indexed")
text
$ python build_rag_index.py case
214 chunks indexed

19 seconds on an 8 core laptop CPU, model loading included.

Step 4: Pick the Passages for the Model

We wrote 16 questions with the page that answers each one: dates, amounts, what a witness said, the outcome of the appeal, case names cited by the court, a section of the memo, a clause of the settlement. Most are phrased differently from the text, the way a lawyer would ask. For each method we counted how often the right page was among the 8 passages sent to the model:

Method (8 passages)Right page foundNoise passages sent
Keyword search only, cleaned text10 / 160
Search by meaning only, cleaned text14 / 160
Meaning, topped up with 2 keyword matches, raw OCR text16 / 163
Meaning, topped up with 2 keyword matches, cleaned text15 / 160

Keyword search misses questions asked in other words: "the final outcome of the appeal" never meets the court's "The judgment and the order denying a new trial are affirmed". Search by meaning missed "Does the release cover fraud claims?": the word "fraud" sits at the end of a long list in the release clause, and keyword search finds it at once. Six passages by meaning plus the two best keyword matches covers both.

Cleaning did not change how often the right page was found: the one question that moved did so because the passage boundaries moved. What it changed is the noise. On the raw text, the bookplate, the title page and the library card took 3 of the slots sent to the model. After cleaning, none. We kept the cleaned version: every slot taken by a bookplate is a slot the evidence does not get.

Step 5: Answer With Quotes, and Check Every Quote

The model gets the 8 passages, numbered, each with its file and page. It must answer from them only, cite the passage number and copy the exact words it relies on. Then the code checks each quote against the passage it claims to come from. A quote that is not there is dropped, not shown. Each checked quote is also saved as a highlighted image of its page, with the function from step 6.

python
import json
import re
import sqlite3
import sys
from pathlib import Path

import numpy as np
from openai import OpenAI

from build_rag_index import EMBED
from highlight_citation import highlight

CASE = "case"  # folder with the PDFs and their .ocr.json
db = sqlite3.connect("rag.db")
ROWS = db.execute("SELECT rowid, file, page, text FROM chunks ORDER BY rowid").fetchall()
VECTORS = np.load("rag.npy")
llm = OpenAI()  # reads OPENAI_API_KEY


STOP = set("what when where which who how does did the and for was were with that this from into about before after have has had can could should would".split())


def keyword_hits(question, n=20):
    words = [w for w in re.findall(r"\w{3,}", question) if w.lower() not in STOP]
    terms = " OR ".join(f'"{w}"' for w in words)
    rows = db.execute("SELECT rowid FROM chunks WHERE chunks MATCH ? ORDER BY rank LIMIT ?", (terms, n))
    return [rowid - 1 for (rowid,) in rows]


def meaning_hits(question, n=20):
    q = np.array(next(EMBED.query_embed(question)), dtype=np.float32)
    return list(np.argsort(-(VECTORS @ q))[:n])


def search(question, by_meaning=6, by_keyword=2):
    """Best passages by meaning, topped up with exact keyword matches."""
    picked = meaning_hits(question)[:by_meaning]
    for i in keyword_hits(question):
        if len(picked) == by_meaning + by_keyword:
            break
        if i not in picked:
            picked.append(i)
    return [ROWS[i] for i in picked]


PROMPT = """Answer the question using only the numbered excerpts from a case file.
Return JSON: {{"answer": "...", "citations": [{{"excerpt": 1, "quote": "exact words copied from that excerpt"}}]}}
Every claim needs a citation. Write plain ASCII text. If the excerpts do not contain the answer, set "answer" to "Not found in the case file" and leave citations empty.

{excerpts}

Question: {question}"""


def norm(text):
    return re.sub(r"[^a-z0-9]+", " ", text.lower()).strip()


def ask(question):
    hits = search(question)
    excerpts = "\n\n".join(f"[{n}] {file}, page {page}:\n{text}" for n, (_, file, page, text) in enumerate(hits, 1))
    reply = llm.chat.completions.create(
        model="gpt-5.4-mini",
        response_format={"type": "json_object"},
        messages=[{"role": "user", "content": PROMPT.format(excerpts=excerpts, question=question)}],
    )
    result = json.loads(reply.choices[0].message.content)
    for c in result["citations"]:
        _, file, page, text = hits[c["excerpt"] - 1]
        c.update(file=file, page=page, verified=norm(c["quote"]) in norm(text))
    return result


if __name__ == "__main__":
    question = sys.argv[1]
    result = ask(question)
    print(f"> {question}\n{result['answer']}")
    for n, c in enumerate(result["citations"], 1):
        if not c["verified"]:
            print(f'  [{c["file"]} p.{c["page"]}] "{c["quote"]}" (NOT IN SOURCE, dropped)')
            continue
        png = f'cite-{n}-{Path(c["file"]).stem}-p{c["page"]}.png'
        boxes = highlight(f'{CASE}/{c["file"]}', c["page"], c["quote"], png)
        print(f'  [{c["file"]} p.{c["page"]}] "{c["quote"]}" -> {png} ({boxes} words)')

A question about the client's own case, answered from the research memo:

text
> Can Dunmore undo the settlement if it later learns that Marlow hid information about the missed deliveries?
Probably not, unless Dunmore can show actual fraud. A compromise agreement is not set aside merely
because one side did not disclose everything it knew when the other side made its own independent
investigation. The memorandum also says the Services Agreement is an ordinary commercial contract
and creates no fiduciary duty, and that if Dunmore signs the release after reviewing its own
delivery logs, a later claim of nondisclosure will be hard to sustain.
  [research-memo-2025-02.pdf p.1] "Probably not, unless Dunmore can show actual fraud." -> cite-1-research-memo-2025-02-p1.png (8 words)
  [research-memo-2025-02.pdf p.1] "Courts have long held that a compromise agreement between parties dealing at arm's length is not set aside merely because one side did not disclose everything it knew, when the other side made its own independent investigation." -> cite-2-research-memo-2025-02-p1.png (37 words)
  [research-memo-2025-02.pdf p.1] "Here, the Services Agreement is an ordinary commercial contract and creates no fiduciary duty." -> cite-3-research-memo-2025-02-p1.png (14 words)
  [research-memo-2025-02.pdf p.1] "Dunmore had its own delivery logs." -> cite-4-research-memo-2025-02-p1.png (6 words)
  [research-memo-2025-02.pdf p.1] "If it signs the release after reviewing them, a later claim of nondisclosure will be hard to sustain." -> cite-5-research-memo-2025-02-p1.png (18 words)

A question about the scanned opinion, where the answer sits on two pages:

text
> How much had Mrs. Colton been allowed to draw for her own use, and why did she want to sell?
Mrs. Colton had been allowed to draw about $175,000 for her own use, and she wanted to sell because
she was determined to get out of the enterprises without waiting and taking her chances on creating
a market.
  [colton-v-stanford.pdf p.51] "had been allowed to draw about $175,000 for her own use" -> cite-1-colton-v-stanford-p51.png (11 words)
  [colton-v-stanford.pdf p.50] "Mrs. Colton was determined to get out of the enterprises without waiting and taking her chances on creating a market." -> cite-2-colton-v-stanford-p50.png (21 words)

And a question the case file cannot answer:

text
> Who was the judge assigned to the Dunmore case in the Court of Common Pleas?
Not found in the case file

The page numbers are PDF pages, not the numbers printed on the paper: page 51 of the PDF carries the printed number 43. Cite the PDF page in the tool, and add the printed number if your court filings need it.

Step 6: Highlight the Quote on the Scan

OCR Wizard returns each word with its four corners on the page image. find_quote looks for the quoted words in that list, joining words split by a line-break hyphen the same way as the cleaning step, and highlight draws a yellow box over each one on a render of the page.

python
import re
from pathlib import Path

import pymupdf
from PIL import Image, ImageDraw

from ocr_case_file import ocr_cached


def words_with_boxes(page):
    """OCR words of one page, with words split by a line-break hyphen joined back."""
    out = []
    for a in page["annotations"]:
        word = re.sub(r"[^a-z0-9]", "", a["text"].lower())
        if out and out[-1][2]:  # previous word ended with "-": glue this one to it
            prev, boxes, _ = out.pop()
            out.append((prev + word, boxes + [a["boundingPoly"]], False))
        elif word:
            out.append((word, [a["boundingPoly"]], a["text"].endswith("-")))
    return [(w, b) for w, b, _ in out]


def find_quote(page, quote):
    target = [w for w in (re.sub(r"[^a-z0-9]", "", t.lower()) for t in quote.split()) if w]
    words = words_with_boxes(page)
    for start in range(len(words) - len(target) + 1):
        if [w for w, _ in words[start:start + len(target)]] == target:
            return [box for _, boxes in words[start:start + len(target)] for box in boxes]
    return []


def highlight(pdf_path, page_number, quote, out_path):
    page = ocr_cached(Path(pdf_path))[page_number - 1]
    boxes = find_quote(page, quote)
    width, height = page["imageSize"]
    pix = pymupdf.open(pdf_path)[page_number - 1].get_pixmap(dpi=150)
    image = Image.frombytes("RGB", (pix.width, pix.height), pix.samples)
    sx, sy = pix.width / width, pix.height / height
    layer = Image.new("RGBA", image.size)
    draw = ImageDraw.Draw(layer)
    for poly in boxes:
        xs, ys = [p["x"] * sx for p in poly], [p["y"] * sy for p in poly]
        draw.rectangle([min(xs) - 2, min(ys) - 2, max(xs) + 2, max(ys) + 2], fill=(255, 214, 0, 110))
    Image.alpha_composite(image.convert("RGBA"), layer).convert("RGB").save(out_path)
    return len(boxes)
Answer about Mrs. Colton with two citations marked as found in the source, next to page 51 of the scanned 1890 opinion with the quoted words highlighted in yellow

The reader checks the answer against the original page in one look, which is what a lawyer does before relying on anything a model wrote. The highlight is drawn from the OCR coordinates; the PDF itself is not modified.

Production Tips

  • Show only checked quotes. The verified flag is the line between a citation and a claim. Never display a quote that failed the check.
  • Write your own test questions. Ten to twenty questions with the page that answers them, rerun after every change to the cleaning, the chunk size or the search. Our table took under a minute to compute.
  • Keep the OCR result with the file. The .ocr.json holds the text and the word boxes. Indexes, highlights and new features all run from it without another OCR call.
  • Choose where the text goes. OCR and retrieval run before any model sees the case file, and the embeddings run locally. Only the 8 passages picked for a question go to the language model, so pick a provider and settings that fit your confidentiality rules.
  • Look at a few pages before writing cleaning rules. Each archive has its own stamps and headers. Ten minutes reading raw OCR output tells you which rules you need.
  • It is not legal advice. The tool finds and quotes; a lawyer reads the page and decides.

Next Step

Get a key on the OCR Wizard API page and run the four scripts on a case file of your own. To add a searchable text layer to the same PDFs, see our searchable legal PDF tutorial, and to pull parties, dates and clauses out of contracts, the scanned contracts tutorial.

Sources

Frequently Asked Questions

Can you use RAG on scanned PDFs?
Yes, once every page has been through OCR. A scanned page is an image, so a RAG pipeline that reads the PDF text layer gets nothing: our scanned memo and settlement agreement returned 0 words. Run OCR on each page first, keep the page number with the text, then chunk, index and retrieve as usual.
How do I make a RAG answer cite the page of a scanned document?
Keep the file name and page number on every chunk, ask the model to return the exact words it relies on with the excerpt number, then check in code that each quote really appears in that excerpt. With the word positions returned by OCR, the same quote can be highlighted on the scanned page so a reader sees the source in one click.
Should I clean OCR text before chunking?
Yes. Scans carry page numbers, library stamps, stray marks and words split across lines with a hyphen. In our 62 page opinion, 356 words were split across lines, and without cleaning 3 of the passages sent to the model for 16 test questions were bookplates or title pages. After cleaning, none were.
Keyword search or embeddings for RAG on legal documents?
Both. On 16 questions about our case file, keyword search alone put the right page in the 8 passages sent to the model 10 times, search by meaning 14 times, and search by meaning topped up with the 2 best keyword matches 15 times. Keyword search catches exact words that search by meaning can miss, such as fraud inside a long release clause.

Ready to Try OCR Wizard?

Check out the full API documentation, live demos, and code samples on the OCR Wizard spotlight page.

Related Articles

Continue learning with these related guides and tutorials.