Tools,

OCRmyPDF in Python: one script, tested

1,876 of 1,955

words from one ocr() call, in 19 s

Get the script

OCRmyPDF from pip, on 10 scanned book pages: the script, the traps and the file size.

Same text from Python and the command line

Words found, of 1,955, and time for 10 pages
Run Words Time
ocrfolder.py, below 1,876 20 s
The ocrmypdf command 1,876 23 s
ocr(OcrOptions(...)) 1,876 21 s
ocr_engine="rapidocr" 1,884 61 s
Tesseract alone, no OCRmyPDF 1,878 39 s
Our Actor's code, on our Mac 1,879 45 s

The first three gave the same text, byte for byte. Their times are the whole run, and ocrfolder.py also handled two more files. The other rows time the OCR only.

RapidOCR is a second engine: pip install "ocrmypdf[rapidocr]". It found 8 more words and took about 3 times as long.

Install with Python 3.11 or later

brew install tesseract [email protected]
python3.13 -m venv ocr
ocr/bin/pip install ocrmypdf

No Ghostscript: our Mac had none, and OCRmyPDF still made a PDF/A of our scan. For other PDFs, it can fall back to Ghostscript.

Do not use the python3 that comes with macOS. On our Mac it is 3.9.6, so pip installed OCRmyPDF 15.4.4 with no error, and the import failed:

ImportError: reportlab requires 3.10+; other versions are unsupported.

The script: a folder of PDFs in

Save this as ocrfolder.py:

"""OCR every PDF in a folder: a searchable PDF and a .txt file next to each one."""

import sys
from pathlib import Path

import ocrmypdf


def main(folder):
    ocrmypdf.configure_logging(ocrmypdf.Verbosity.quiet)
    for pdf in sorted(Path(folder).glob("*.pdf")):
        if pdf.name.endswith(".ocr.pdf"):
            continue
        out = pdf.with_suffix(".ocr.pdf")
        try:
            ocrmypdf.ocr(pdf, out, sidecar=out.with_suffix(".txt"),
                         mode="skip", jobs=4, progress_bar=False)
            print("ok  ", pdf.name)
        except ocrmypdf.EncryptedPdfError:
            print("skip", pdf.name, "(password)")
        except ocrmypdf.ExitCodeException as e:
            print("fail", pdf.name, type(e).__name__, e)


if __name__ == "__main__":
    main(sys.argv[1] if len(sys.argv) > 1 else ".")

What it printed on our folder

ocr/bin/python ocrfolder.py scans

Our folder held the scan, a copy of the script's own output and a locked copy:

ok   already.pdf
skip locked.pdf (password)
ok   scan.pdf

scan.ocr.pdf is a PDF/A with the scanned JPEGs untouched. For already.pdf, mode="skip" copied the pages, and the .txt says "[OCR skipped on page(s) 1-10]".

jobs=4 cut 53 s to 19 s

One ocr() call on the 10 pages
Setting Time
jobs=1 53 s
jobs=2 28 s
jobs=4 19 s
jobs=4, use_threads=False 20 s

All four gave the same text. Leave jobs out and OCRmyPDF uses one worker per CPU, 18 on our Mac, but never more than one per page.

When you need the __main__ guard

In OCRmyPDF 17.14.1, ocr() runs its workers as threads by default. Our script ran fine with the if __name__ == "__main__": line removed.

With use_threads=False, it starts processes instead. On our Mac, without the guard, the worker processes crashed with a Python error that points to "Safe importing of main module", and the script hung. We stopped it at 300 s.

With the guard, the same run took 25 s. Keep the guard.

The errors worth catching

All three error classes are subclasses of ocrmypdf.ExitCodeException, so the script's last except catches the rest.

optimize=3 cut the PDF to 2.8 MB

PDF size and page JPEG quality
optimize PDF JPEG
0 6.53 MB kept
1, the default 6.49 MB kept
2 5.10 MB quality 75
3 2.79 MB quality 40

The text was the same at every level. Levels 2 and 3 re-encode the page JPEGs and need pngquant: brew install pngquant.

The same line of the scan twice: the original JPEG on top, the optimize=3 copy below, both easy to read
Top: the scan as it came in (quality 87). Below: optimize=3.

Same 10 pages, one scorer

The 10 pages are proofread Wikisource scans, 1,955 words in all. The score is true words found in order, with exact case and punctuation.

How we ran it
  • OCRmyPDF 17.14.1 and pikepdf 10.18.1 on Python 3.13.
  • Tesseract 5.5.4 from Homebrew, on macOS 26.6.
  • One Apple Silicon Mac, one run at a time, at low priority, so times are rough.
  • Every OCRmyPDF run with Tesseract that we scored gave the same text.
  • We count words in the .txt file. pdftotext found 1,845 in the PDF's text layer.
  • We made the locked copy with pikepdf.
  • Licenses: OCRmyPDF is MPL-2.0, Tesseract and RapidOCR Apache-2.0, pngquant GPL-3.0 or later. We ran them and ship none of them.

Scanned pages to text, no install

Run it yourself. Our Apify Actor reads PDF, PNG, JPEG, WEBP and TIFF for $0.006 a page, with nothing to install. Its code found 1,879 of these 1,955 words.

Try the Actor

Or send us the scan. Tack, our AI, does the job for $29, up to 50 pages. First page free.

Get one page free

Questions people ask

How do I run OCRmyPDF from Python?

Install Tesseract, then pip install ocrmypdf on Python 3.11 or later. Call ocrmypdf.ocr("in.pdf", "out.pdf", sidecar="out.txt", jobs=4).

Do I need if __name__ == "__main__" for ocrmypdf.ocr()?

Not with the default threads in OCRmyPDF 17.14.1. With use_threads=False on our Mac, yes: without it our script hung. Keep it anyway.

Why does ocrmypdf.ocr() raise PriorOcrFoundError?

The PDF already has text. Pass mode="skip" to copy those pages as they are. Our script does that.

How do I make the OCRmyPDF output smaller?

optimize=3 cut our scan from 6.5 MB to 2.8 MB with the same text. It needs pngquant, and the page JPEGs lose quality.

Does OCRmyPDF need Ghostscript?

Not in our test. OCRmyPDF 17.14.1 made a PDF/A of our scan on a Mac with no Ghostscript. The default engine needs Tesseract.