How to OCR a scanned PDF in Python

Updated · Tested with Python 3.13, Tesseract 5.5.0, pytesseract 0.3.13, PyMuPDF 2.2, OCRmyPDF 17.14

In short

Install Tesseract and the pytesseract package, draw each page of the PDF as a 300 DPI image with PyMuPDF, and pass the image to pytesseract.image_to_string. Check each page for existing text first and OCR only the ones without any. To get a searchable PDF instead of plain text, use OCRmyPDF.

A scanned PDF holds a picture of each page, so there is no text for a PDF library to return. Reading it takes three steps: turn each page into an image, run OCR on the image, and collect the text. The examples use company-scan.pdf, a one-page scan at 300 DPI.

What you need

Tesseract is the standard free OCR engine. It is a program, not a Python package, so install it first and then the wrapper.

Shell
# Debian or Ubuntu
sudo apt-get install tesseract-ocr
# macOS
brew install tesseract

pip install pytesseract pymupdf pillow

pytesseract calls the Tesseract program for you. PyMuPDF turns PDF pages into images, so you do not need Poppler as well.

Read a scanned PDF

Python
import io

import pymupdf
import pytesseract
from PIL import Image

with pymupdf.open("company-scan.pdf") as doc:
    for page in doc:
        pixmap = page.get_pixmap(dpi=300)
        image = Image.open(io.BytesIO(pixmap.tobytes("png")))
        print(pytesseract.image_to_string(image))

The first lines of what it prints:

Output
COMPANY EXTRACT

Company name Harbor Lane Logistics Ltd
Company number 51-482913-6

Status Active

Registered 14 March 2019

That took half a second for the page on a laptop. dpi=300 matters: it is the resolution the page is drawn at before Tesseract sees it, and too low a value is the most common cause of bad results. How to improve OCR accuracy measures the effect.

Only OCR the pages that need it

OCR is slow next to reading text that is already in the file, and less exact. Real files often mix the two, so check each page first:

Python
import io

import pymupdf
import pytesseract
from PIL import Image

def read_pdf(path):
    pages = []
    with pymupdf.open(path) as doc:
        for page in doc:
            text = page.get_text()
            if not text.strip():
                image = Image.open(io.BytesIO(page.get_pixmap(dpi=300).tobytes("png")))
                text = pytesseract.image_to_string(image)
            pages.append(text)
    return pages

for text in read_pdf("mixed-text-and-scan.pdf"):
    print(repr(text[:30]))
Output
'COMPANY EXTRACT\nCompany name\nH'
'COMPANY EXTRACT\n\nCompany name '

The first page of mixed-text-and-scan.pdf has text and is read directly. The second is a scan and goes through Tesseract.

Words with positions and confidence

image_to_data returns every word with where it is in the image, in pixels, and how sure Tesseract is, from 0 to 100:

Python
import pytesseract
from PIL import Image

data = pytesseract.image_to_data(Image.open("company-scan-300dpi.png"), output_type=pytesseract.Output.DICT)
words = [
    (data["text"][i], data["conf"][i], data["left"][i], data["top"][i])
    for i in range(len(data["text"]))
    if data["text"][i].strip()
]
print(words[:4])
Output
[('COMPANY', 96, 289, 353), ('EXTRACT', 96, 751, 353), ('Company', 96, 287, 553), ('name', 96, 505, 561)]

Low confidence is a useful warning. Flag words under about 60 for a person to check, instead of trusting every result equally.

Other languages

Tesseract reads English unless told otherwise. Install the language data and name it:

Shell
sudo apt-get install tesseract-ocr-heb
Python
text = pytesseract.image_to_string(image, lang="heb+eng")

Naming two languages lets one page mix them. Reading a Hebrew page with the English model gives nonsense, not an error; Hebrew OCR shows the difference.

Make the PDF itself searchable

If you want a PDF you can search and copy from, not just the text, use OCRmyPDF. It runs Tesseract and writes a new file with the text behind the picture:

Shell
pip install ocrmypdf
ocrmypdf company-scan.pdf searchable.pdf

Any PDF library can then read searchable.pdf. More in scanned or searchable?.

Scans and 100sands

100sands does not do OCR, so it is not a way around installing Tesseract. It reads PDFs and HTML files that contain text, and refuses a file with no text, such as company-scan.pdf, with status 422 and a body of this shape:

JSON
{
  "error": "NO_TEXT_IN_FILE",
  "message": "This PDF has no text in it. It is probably a scan or a photo; only PDFs with text can be read."
}

In a file that mixes text pages with scanned ones, it reads the text pages and returns the scanned pages blank. If those pages matter, find them with the per-page check above and OCR them.

Questions

How do I extract text from a scanned PDF in Python?

Render each page to an image with PyMuPDF's page.get_pixmap(dpi=300), open it with Pillow, and call pytesseract.image_to_string on it. Tesseract itself must be installed as a program.

Do I need Poppler or pdf2image?

No. PyMuPDF renders PDF pages to images by itself, so pdf2image and Poppler are not needed.

How do I OCR a PDF that is not in English?

Install the Tesseract data for the language and pass its code, for example lang="heb+eng" for a page that mixes Hebrew and English. Without it, Tesseract uses its English model and returns nonsense.

How long does OCR take?

About half a second for a page at 300 DPI on a laptop in our test. Reading text that is already in a PDF takes milliseconds, so OCR only the pages that have none.

Try it on your own documents

A free plan every month, no credit card. See the PDF to text API.

Start free