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.
# Debian or Ubuntu
sudo apt-get install tesseract-ocr
# macOS
brew install tesseract
pip install pytesseract pymupdf pillowpytesseract calls the Tesseract program for you. PyMuPDF turns PDF pages into images, so you do not need Poppler as well.
Read a scanned PDF
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:
COMPANY EXTRACT
Company name Harbor Lane Logistics Ltd
Company number 51-482913-6
Status Active
Registered 14 March 2019That 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:
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]))'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:
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])[('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:
sudo apt-get install tesseract-ocr-hebtext = 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:
pip install ocrmypdf
ocrmypdf company-scan.pdf searchable.pdfAny 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:
{
"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.