Sub topic 3
OCR for Scanned Pages
This chapter assumes you can run Python, call an LLM API, and read the output of the PDF text check from the previous chapter. Here you handle the case where that check says the PDF has no usable text.
What OCR does
OCR (optical character recognition) turns an image of text into characters. A scanned PDF stores each page as a picture. Text extraction finds nothing to read, so you must first render each page to an image and then run OCR on it.
The pipeline for a scan has three steps: render, recognize, clean.
A working example
This example uses Tesseract, a free OCR engine. Install the Tesseract program on your system, then install the Python packages with pip install pytesseract pdf2image. The pdf2image package also needs the Poppler tools installed.
from pdf2image import convert_from_path
import pytesseract
def ocr_pdf(path, dpi=300, lang="eng"):
images = convert_from_path(path, dpi=dpi)
pages = [pytesseract.image_to_string(img, lang=lang) for img in images]
return "\n\n".join(pages)
text = ocr_pdf("scanned_invoice.pdf")
print(text[:500])The dpi value sets the render resolution. Around 300 DPI works well for normal print. Lower values blur small characters, and much higher values slow the job without helping.
Common errors
OCR output is noisy, and the LLM sees that noise. Watch for these problems:
- Look-alike characters. The letter
Oand the digit0, orland1, get swapped. This hurts invoice numbers and amounts most. - Low-quality scans. Skewed, faint, or low-resolution pages produce garbled text. Rendering at a higher DPI or converting to grayscale can help.
- Wrong language. Tesseract reads with the language model you give it. Set
langto match the document, for example"deu"for German. - Broken layout. OCR returns plain lines of text. Columns may interleave and table cells may lose their alignment. The next chapter covers this.
- Mixed PDFs. Some PDFs have text on some pages and scans on others. Check each page, not just the whole file.
from pypdf import PdfReader
from pdf2image import convert_from_path
import pytesseract
def extract_pages(path, min_chars=50):
reader = PdfReader(path)
pages = []
for i, page in enumerate(reader.pages):
text = (page.extract_text() or "").strip()
if len(text) < min_chars:
image = convert_from_path(path, dpi=300, first_page=i + 1, last_page=i + 1)[0]
text = pytesseract.image_to_string(image).strip()
pages.append(text)
return pagesThis function uses native text where it exists and falls back to OCR only for pages that need it. That saves time, since OCR is much slower than reading embedded text.
When OCR is not enough
Classic OCR is cheap and runs locally, which helps with privacy and cost. Its weak spots are complex layouts, handwriting, and stamps. For those pages, sending the page image straight to a vision-capable model can work better. A later chapter compares the two approaches.
Exercise
A 10-page PDF has native text on pages 1 to 8 and scanned images on pages 9 and 10. Your check runs on the whole file and finds plenty of text. What goes wrong, and how do you fix it?
Show answer
The whole-file check passes because pages 1 to 8 contain text, so pages 9 and 10 are never OCRed and their data is silently missing. Fix it by checking each page separately and running OCR only on pages whose extracted text falls below a threshold, as in extract_pages.