Sub topic 3
OCR for Scanned Pages
This chapter assumes you can run Python scripts, install packages with pip, and read a PDF with a library such as pypdf. It also assumes you know the difference between a native-text PDF and a scanned one, which the earlier chapters on document types and text extraction covered.
What OCR does and why you need it
A scanned PDF stores each page as a picture. There are no characters inside the file, only pixels. When you call extract_text() on such a file, pypdf finds nothing to return, so you get an empty or near-empty string.
Optical character recognition (OCR) is the process of turning an image of text into actual text. An OCR engine finds regions that look like text, splits them into lines and characters, and predicts which character each shape represents. The output is a string, sometimes with extra data such as word positions and a confidence score.
In an extraction pipeline, OCR sits between ingestion and the LLM. Its output replaces the text layer that a native PDF would have given you.
Detecting that you need OCR
The earlier check used a character count threshold. That works for a first pass, but it has two failure modes you should know about.
- A scanned document can carry a hidden text layer from an earlier OCR run. That text may be poor, but the check will treat the file as native.
- A mixed document can have some native pages and some scanned pages. A whole-file check hides this.
Checking page by page handles the second problem. Decide per page, and send only the weak pages to OCR.
from pypdf import PdfReader
def pages_needing_ocr(path, min_chars=50):
reader = PdfReader(path)
flagged = []
for index, page in enumerate(reader.pages):
text = (page.extract_text() or "").strip()
if len(text) < min_chars:
flagged.append(index)
return flagged
print(pages_needing_ocr("invoice.pdf"))A page with only a short legitimate text, such as a cover page, may be flagged too. That is acceptable because OCR on such a page costs little.
Running OCR with Tesseract
Tesseract is a widely used open-source OCR engine. You use it from Python through the pytesseract wrapper, which calls the Tesseract program installed on your machine. You also need a way to turn PDF pages into images. The pdf2image package does this and relies on the Poppler tools.
Install the system programs first. On Debian or Ubuntu:
sudo apt-get install tesseract-ocr poppler-utils
pip install pytesseract pdf2imageOn macOS, brew install tesseract poppler does the same job. Language data is a separate install, for example tesseract-ocr-deu for German.
The following function renders chosen pages and runs OCR on each:
from pdf2image import convert_from_path
import pytesseract
def ocr_pages(path, page_indexes, dpi=300, lang="eng"):
results = {}
for index in page_indexes:
images = convert_from_path(
path, dpi=dpi, first_page=index + 1, last_page=index + 1
)
results[index] = pytesseract.image_to_string(images[0], lang=lang)
return results
flagged = [0, 1]
texts = ocr_pages("scanned_invoice.pdf", flagged)
for index, page_text in texts.items():
print(f"--- page {index + 1} ---")
print(page_text[:300])Note that convert_from_path counts pages from 1, while the lists from pypdf count from 0. The + 1 converts between the two. Mixing these up is a common off-by-one error.
Resolution and preprocessing
OCR accuracy depends heavily on image quality. Three settings matter most.
| Factor | Typical guidance | What goes wrong otherwise |
|---|---|---|
| Resolution | Render at 300 DPI for normal print | Below about 200 DPI, small characters blur together |
| Contrast | Convert to grayscale, optionally threshold to black and white | Gray backgrounds and stamps become noise |
| Skew | Straighten pages rotated by a few degrees | Lines of text are misread or split |
Rendering at a higher DPI is not always better. Past about 400 DPI the images grow large, OCR slows down, and accuracy rarely improves for normal print.
A small preprocessing step with Pillow often helps:
from PIL import ImageOps
def preprocess(image):
gray = ImageOps.grayscale(image)
gray = ImageOps.autocontrast(gray)
return gray.point(lambda p: 255 if p > 160 else 0)The fixed threshold of 160 is a starting value. Faint scans may need a lower or higher number, and a hard threshold can erase light handwriting or colored text. Test on your own documents rather than trusting a default.
Page segmentation modes
Tesseract guesses how a page is laid out. You can override the guess with the --psm option. The right mode depends on the content.
| Mode | Meaning | Use for |
|---|---|---|
| 3 | Fully automatic page segmentation (default) | Ordinary pages |
| 4 | Single column of variable-sized text | Receipts, narrow columns |
| 6 | Single uniform block of text | Cleanly cropped regions |
| 11 | Sparse text, find as much as possible | Forms with scattered labels |
You pass it like this:
text = pytesseract.image_to_string(image, config="--psm 4")If a receipt comes out with lines in the wrong order, trying mode 4 is a cheap first experiment.
Using confidence scores
OCR engines know when they are unsure. Tesseract can return per-word confidence values from 0 to 100 through image_to_data. Averaging them gives a rough page quality signal.
import pytesseract
from pytesseract import Output
def ocr_with_confidence(image, lang="eng"):
data = pytesseract.image_to_data(image, lang=lang, output_type=Output.DICT)
words, scores = [], []
for word, conf in zip(data["text"], data["conf"]):
if word.strip() and float(conf) >= 0:
words.append(word)
scores.append(float(conf))
mean_conf = sum(scores) / len(scores) if scores else 0.0
return " ".join(words), mean_confWords with a confidence of -1 are layout markers, not real words, so the code skips them. A low mean confidence is a useful input for the human review step later in the tutorial. You can also use it now: if a page scores below a threshold you choose, such as 60, you might send the page image directly to a vision model instead.
Common OCR errors and how they affect extraction
OCR errors are not random. They follow patterns, and those patterns hit exactly the fields you care about.
- Digit and letter confusion:
0andO,1andlandI,5andS,8andB. An invoice number such asINV-0081can becomeINV-O08l. - Dropped or merged punctuation: a decimal point lost from
1,250.00turns it into125000, off by a factor of 100. - Merged columns: text from two table columns joins into one line, so a label gets attached to the wrong value.
- Missing small text: footnotes, stamps and fine print are often skipped.
The LLM can sometimes repair these errors from context, but it can also build a confident answer on top of a wrong digit. Two defenses apply. First, do not tell the model to "fix" the text, because that invites guessing. Second, use the grounding checks from a later chapter, and be aware that grounding compares the extracted value against the OCR text. If OCR read the digit wrongly, the value will pass grounding and still be wrong. Only evaluation against the original image or labeled data catches that.
Alternatives to local OCR
Tesseract is free and runs offline, which helps with privacy. It is weaker on photos taken at an angle, handwriting, and complex layouts. Other options exist.
| Option | Strength | Trade-off |
|---|---|---|
| Tesseract | Free, local, many languages | Sensitive to image quality and layout |
| Cloud OCR services | Better on tables, forms and handwriting | Cost per page, and documents leave your systems |
| Vision-capable LLM | Reads layout and text in one step | Higher cost and latency, and output can drift from the page |
The last row connects to the multimodal chapter. A vision model can skip the OCR step, but it is not free of errors either. Many pipelines use Tesseract first, check the confidence, and escalate only the poor pages.
Putting the OCR step together
This function combines detection, OCR and a page-level quality signal. It returns the text for the whole document and a list of weak pages.
from pypdf import PdfReader
from pdf2image import convert_from_path
import pytesseract
from pytesseract import Output
def document_text(path, min_chars=50, dpi=300, low_conf=60):
reader = PdfReader(path)
pages, weak = [], []
for index, page in enumerate(reader.pages):
text = (page.extract_text() or "").strip()
if len(text) >= min_chars:
pages.append(text)
continue
image = convert_from_path(
path, dpi=dpi, first_page=index + 1, last_page=index + 1
)[0]
data = pytesseract.image_to_data(image, output_type=Output.DICT)
scores = [float(c) for w, c in zip(data["text"], data["conf"])
if w.strip() and float(c) >= 0]
mean_conf = sum(scores) / len(scores) if scores else 0.0
pages.append(pytesseract.image_to_string(image).strip())
if mean_conf < low_conf:
weak.append(index)
return "\n\n".join(pages), weakThe result goes straight into the prompt template you wrote earlier. The weak list is kept so that later steps can route those pages to a stronger method or to a person.
Summary of decisions
- Check each page for a text layer. Run OCR only where it is missing.
- Render at about 300 DPI, and preprocess when scans are noisy.
- Choose a page segmentation mode that matches the layout.
- Record confidence per page and keep it.
- Remember that downstream checks cannot detect OCR misreads on their own.
Exercise
A scanned receipt is OCR'd and the LLM extracts a total of 125000.00. The printed total is 1,250.00, and the string "125000" appears in the OCR text. Why did the grounding check not catch the error, and what would you add to catch it?
Show answer
The grounding check only compares the extracted value with the OCR text, and the OCR text itself had lost the decimal point, so the wrong value is present in the source it checks. It cannot see the image. To catch it, use the OCR confidence for that page to route low-confidence pages to review, add a plausibility rule (for example, total must equal the sum of line items), and compare against labeled ground truth in evaluation. A second read of the page image with a vision model, with disagreements sent to a person, would also help.
Exercise
Your pipeline calls convert_from_path(path, first_page=index, last_page=index) with a zero-based page index from pypdf. What goes wrong, and how do you fix it?
Show answer
convertfrompath numbers pages from 1, so page index 0 is invalid and every other page is shifted back by one, so OCR runs on the wrong page. Pass first_page=index + 1 and last_page=index + 1.