Part of Hosting by frameworkHosting · Documents

Make a scanned PDF searchable from code, and fix TesseractNotFoundError.

A scanned PDF is a stack of page images, so search and copy find nothing. To make the PDF searchable, OCR reads each page and adds the text as an invisible layer under the image. ocrmypdf -l eng+fra scan.pdf out.pdf does it with Tesseract. TesseractNotFoundError means the Tesseract binary isn’t installed where your code runs.

Facts checked

What a searchable PDF is

A scanner or a phone app writes one image per page. OCR finds the words in each image and where they sit. A searchable PDF keeps the page image as it is and draws the recognized words over it in invisible text, at the same positions. Viewers can then find, select and copy, and libraries such as pdf-parse can read the text.

Decide which output you need. To store a document or hand it back, you want the searchable PDF. To index it or pull fields out of it, the text alone is enough.

On a Linux server: ocrmypdf

ocrmypdf is the usual tool for converting a scanned PDF to a searchable PDF. It runs Tesseract on each page and builds the output PDF with the text layer. It needs Python 3.11 or newer, Tesseract 4.1.1 or newer, and either Ghostscript 9.54+ or the pypdfium2 package. On Debian and Ubuntu, apt install ocrmypdf brings everything except languages other than English.

It assumes English unless you pass -l. By default it writes PDF/A; --output-type pdf changes less of the file. If a page already has text, the default mode stops with exit code 6. --skip-text (--mode skip in recent versions) OCRs only the image pages, which suits files that mix scans with born-digital pages.

# Debian or Ubuntu: ocrmypdf brings Tesseract and Ghostscript; add French
sudo apt install ocrmypdf tesseract-ocr-fra

# Scanned PDF in, searchable PDF out, English and French
ocrmypdf -l eng+fra scan.pdf searchable.pdf

# Mixed files: leave pages that already have text alone
ocrmypdf -l eng+fra --skip-text mixed.pdf searchable.pdf

# Keep it a plain PDF (the default output is PDF/A), and save the text too
ocrmypdf -l eng+fra --output-type pdf --sidecar scan.txt scan.pdf searchable.pdf

From Python: ocrmypdf.ocr and pytesseract

ocrmypdf.ocr() takes the same options as the command line. It starts worker processes or threads of its own; jobs= caps them, and the ocrmypdf docs suggest calling it from a child process. Inside a web server, run it in a background job rather than in the request.

pytesseract is the lighter choice when you only want text from an image, or a one-page searchable PDF from one image. It doesn’t contain Tesseract: it runs the tesseract command and reads what it prints.

import ocrmypdf, pytesseract
from PIL import Image

# A scanned PDF to a searchable PDF (ocrmypdf 17; mode="skip" is --skip-text)
ocrmypdf.ocr("scan.pdf", "searchable.pdf", language=["eng", "fra"], mode="skip", output_type="pdf")

# Only the text of an image
text = pytesseract.image_to_string(Image.open("receipt.jpg"), lang="eng+fra")

# One image to a one-page searchable PDF (bytes)
pdf = pytesseract.image_to_pdf_or_hocr(Image.open("page.png"), lang="eng+fra", extension="pdf")

From Node.js: call the command

In Node, the simplest dependable route is to install ocrmypdf in the image and call it with execFile. Pass arguments as an array (never a shell string built from a file name), set a timeout, and write files to a temporary directory you delete afterwards. If you can’t install anything, see Tesseract.js below.

import { execFile } from "node:child_process";
import { promisify } from "node:util";

const run = promisify(execFile);

// Call the ocrmypdf command: it runs Tesseract and writes the searchable PDF.
await run("ocrmypdf", ["-l", "eng+fra", "--skip-text", "--output-type", "pdf", "scan.pdf", "searchable.pdf"], {
  timeout: 300_000,
});

TesseractNotFoundError: the binary isn’t there

pip install pytesseract installs the wrapper only, so the install succeeds and the error appears on the first OCR call. pytesseract runs the command named in pytesseract.pytesseract.tesseract_cmd, which is tesseract by default, and raises TesseractNotFoundError when it can’t start it. ocrmypdf fails the same way, with its own message.

The fix is to install the Tesseract system package in the environment your app runs in, not only where it builds. If Tesseract is installed outside the PATH, set pytesseract.pytesseract.tesseract_cmd to the full path. The third message below is the next problem you may hit: Tesseract starts but can’t find a language.

# pytesseract, at the first call (pip install succeeded)
pytesseract.pytesseract.TesseractNotFoundError: tesseract is not installed or it's not in your PATH. See README file for more information.

# ocrmypdf, exit code 3
The program 'tesseract' could not be executed or was not found on your
system PATH.

# Tesseract is installed but the language data isn't (or isn't where it looks)
Error opening data file /usr/share/tesseract-ocr/5/tessdata/fra.traineddata
Please make sure the TESSDATA_PREFIX environment variable is set to your "tessdata" directory.
Failed loading language 'fra'

The fix on Render, Railway, Heroku and Streamlit

PlatformWhy Tesseract is missingFix
Render (native runtime) †Tesseract isn’t among the tools Render’s native runtimes include (ffmpeg, Ghostscript, ImageMagick and pandoc are)Deploy with a Dockerfile, such as the one below
Railway (Railpack) † † †Tesseract isn’t in the image unless you add it, and buildAptPackages installs packages for the build step onlyrailpack.json: { "deploy": { "aptPackages": ["tesseract-ocr", "tesseract-ocr-fra"] } } (or RAILPACK_DEPLOY_APT_PACKAGES), or a Dockerfile
Heroku (Cedar) † † †The language buildpack doesn’t install itAdd heroku-community/apt first (heroku buildpacks:add --index 1 heroku-community/apt) and an Aptfile listing tesseract-ocr and tesseract-ocr-fra. It unpacks packages under /app/.apt, so on heroku-24 set TESSDATA_PREFIX=/app/.apt/usr/share/tesseract-ocr/5/tessdata. Fir apps use the .deb Packages buildpack instead
Streamlit Community Cloud †System packages are installed only from packages.txtA packages.txt at the root of the repository, one Debian package per line: tesseract-ocr, tesseract-ocr-fra
Vercel, AWS Lambda † † †A function contains only its bundle: 250 MB uncompressed on both (500 MB for Python on Vercel)On Lambda, a container image (up to 10 GB) with Tesseract installed. Anywhere, Tesseract.js (below)

† Competitor details come from each vendor’s own published pages on the dates shown; prices and plans change, so check the vendor before you decide. Render (native runtime) (2026-11-25) · Railway (Railpack) (2026-11-25) · Railway (Railpack) (2026-11-25) · Railway (Railpack) (2026-11-25) · Heroku (Cedar) (2026-11-25) · Heroku (Cedar) (2026-11-25) · Heroku (Cedar) (2026-11-25) · Streamlit Community Cloud (2026-11-25) · Vercel, AWS Lambda (2026-11-25) · Vercel, AWS Lambda (2026-11-25) · Vercel, AWS Lambda (2026-11-25)

A Dockerfile that works on any container host

On any host that builds from a Dockerfile (Render’s Docker runtime, for one), the system packages are yours to choose. This one is for a Python app; the comment at the end gives the change for Node.

FROM python:3.12-slim-bookworm

# Tesseract with English (installed with it) and French, plus Ghostscript for ocrmypdf
RUN apt-get update \
 && apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-fra ghostscript \
 && rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt   # ocrmypdf, pytesseract
COPY . .

# Prints eng, fra and osd in the build log
RUN tesseract --list-langs

CMD ["gunicorn", "--bind", "0.0.0.0:8000", "app:app"]

# Node app instead: FROM node:22-bookworm-slim and add ocrmypdf to the apt-get line.

French and English: language packs

Tesseract reads only the languages whose .traineddata files it has. On Debian and Ubuntu, tesseract-ocr installs English (tesseract-ocr-eng) and orientation detection (tesseract-ocr-osd); French is a separate package, tesseract-ocr-fra. tesseract --list-langs shows what is installed.

Ask for both with eng+fra: -l eng+fra for ocrmypdf and Tesseract, lang="eng+fra" for pytesseract. Quebec documents often mix the two on one page (bilingual forms, invoices with GST and QST lines), so load both rather than guessing per file.

If Tesseract prints Failed loading language 'fra', the pack is missing or Tesseract looks in the wrong folder. Install the pack, or point TESSDATA_PREFIX at the folder that holds the .traineddata files.

No binary at all: Tesseract.js on serverless

Tesseract.js is Tesseract compiled to WebAssembly. It runs in Node.js (v16 or newer for v7) and in the browser, with no system package, so it works in Vercel functions and Lambda zip deploys. We ran the code below with eng and fra on a clean test invoice image we generated; it read the accents and the GST and QST lines correctly.

Know its limits. Its README says it “does not support PDF files”, so a scanned PDF has to be turned into page images first. And it gives you text, not a searchable PDF. Language data is downloaded from jsDelivr on first use, so the first call in a fresh instance is slower and needs network access; set langPath to a folder you ship if it can’t reach the internet.

import fs from "node:fs";
import os from "node:os";
import { createWorker } from "tesseract.js";

// The language data is downloaded on first use (from jsDelivr) and cached in
// cachePath, the working directory by default. On Lambda or Vercel only the
// temporary directory is writable, so cache it there.
const worker = await createWorker(["eng", "fra"], 1, { cachePath: os.tmpdir() });

const { data } = await worker.recognize(fs.readFileSync("page.png")); // images, not PDFs
console.log(data.text);
await worker.terminate();

Or skip the binary: Canner’s OCR service

On a Canner project on Live or above, turn on Text recognition (OCR) in the project’s Services tab (or canner services on ocr), then redeploy. Your app gets CANNER_OCR_SOCKET, a unix socket. Send one JSON line and the file; read one JSON line and the result. There is nothing to install and no TesseractNotFoundError to chase.

It is Tesseract with English, French or both. The pdf preset returns a searchable PDF (the page images with an invisible text layer); the text preset returns UTF-8 text with pages separated by a form feed. The service runs on the same servers as your app, in Canada, with no network access, and keeps nothing: Canner counts usage and never records file names or content. This is the Node.js example from the services docs:

import net from "node:net";

export function ocr(input, preset = "text", params = {}) {
  return new Promise((resolve, reject) => {
    const socket = net.connect(process.env.CANNER_OCR_SOCKET);
    const chunks = [];
    socket.on("data", (d) => chunks.push(d));
    socket.on("error", reject);
    socket.on("close", () => {
      const reply = Buffer.concat(chunks);
      const end = reply.indexOf(10); // the header line ends at the first newline
      if (end < 0) return reject(new Error("no reply"));
      const head = JSON.parse(reply.subarray(0, end).toString());
      if (!head.ok) return reject(new Error(`${head.code}: ${head.error}`));
      resolve({ ...head, data: reply.subarray(end + 1, end + 1 + head.size) });
    });
    socket.write(JSON.stringify({ preset, size: input.length, params }) + "\n");
    socket.end(input);
  });
}

// const { data } = await ocr(fs.readFileSync("scan.pdf"), "pdf", { lang: "eng+fra" });
// fs.writeFileSync("searchable.pdf", data);

The same call from Python

The protocol is the same, so Python needs only the standard library:

import json, os, socket

def ocr(data: bytes, preset: str = "text", **params) -> bytes:
    s = socket.socket(socket.AF_UNIX)
    s.connect(os.environ["CANNER_OCR_SOCKET"])
    s.sendall(json.dumps({"preset": preset, "size": len(data), "params": params}).encode() + b"\n")
    s.sendall(data)
    f = s.makefile("rb")
    head = json.loads(f.readline())
    if not head["ok"]:
        raise RuntimeError(f'{head["code"]}: {head["error"]}')
    return f.read(head["size"])

# text = ocr(open("scan.pdf", "rb").read(), "text", lang="eng+fra", pages=10).decode()
# searchable = ocr(open("scan.pdf", "rb").read(), "pdf")

Presets, limits, and when to use something else

Canner OCR service
Presetstext (UTF-8, pages separated by a form feed) or pdf (searchable PDF)
Parameterslang eng, fra, eng+fra or fra+eng (eng); dpi 100–300 (200); pages 1–50 (20, PDF input only)
InputsPNG, JPEG, TIFF, BMP, GIF, WebP and PDF, sniffed from the bytes; images up to 100 megapixels
Per job50 MB in, 5 minutes; a PDF is read up to its first pages pages. A page with no text gives an empty result, not an error
RateOne job at a time per project, 20 a minute
Job minutes300 a month, shared with media processing and document rendering by your organization’s projects

Try it

Upload a scanned PDF or a photo of a page and get the searchable PDF back. This box runs the real service described above, is limited to 5 files an hour per visitor, and keeps nothing you upload.

PDF, PNG, JPEG or TIFF · 10 MB · first 5 pages · 5 files an hour

Build your own

The demo above is this endpoint plus a bot check and an hourly limit per visitor, kept in the project’s cache. It takes the file as the request body, scans it with CANNER_SCAN_SOCKET, sends it to CANNER_OCR_SOCKET with the pdf preset, and returns the result. The two socket functions are the docs examples, unchanged. Turn on Virus scan and Text recognition (OCR), then redeploy.

  • Scan first. Anything other than stream: OK or FOUND means the file was not scanned, and the code treats it as an error, not as clean.
  • Limit each visitor. A public endpoint like this one needs a per-visitor limit (by IP or by account) before it goes live, or anyone can spend your organization’s job minutes.
  • Expect `busy`. The service runs one job at a time per project. The code answers 429 so the client can retry; for steady volume, put uploads in a queue (background jobs).
  • Nothing on disk. The file stays in memory and goes straight back. If you keep results, Files storage scans what you upload to it.
// server.js: POST a file as the request body, get the searchable PDF back.
// Needs Text recognition (OCR) and Virus scan turned on in the Services tab.
import http from "node:http";
import net from "node:net";

const MAX = 50 * 1024 * 1024; // the OCR service takes up to 50 MB

// scan() is the Node.js example from /docs/services#scan
function scan(buffer) {
  return new Promise((resolve, reject) => {
    const socket = net.connect(process.env.CANNER_SCAN_SOCKET);
    const out = [];
    socket.on("data", (d) => out.push(d));
    socket.on("error", reject);
    socket.on("close", () => {
      const verdict = Buffer.concat(out).toString().replace(/\0$/, "").trim();
      if (verdict === "stream: OK") return resolve({ clean: true });
      const found = verdict.match(/^stream: (.+) FOUND$/);
      if (found) return resolve({ clean: false, signature: found[1] });
      reject(new Error(verdict || "scan failed")); // not scanned: do not treat as clean
    });
    socket.write("zINSTREAM\0");
    for (let i = 0; i < buffer.length; i += 65536) {
      const part = buffer.subarray(i, i + 65536);
      const size = Buffer.alloc(4);
      size.writeUInt32BE(part.length);
      socket.write(size);
      socket.write(part);
    }
    socket.end(Buffer.alloc(4)); // a zero-length chunk ends the stream
  });
}

// ocr() is the Node.js example from /docs/services#ocr
function ocr(input, preset = "text", params = {}) {
  return new Promise((resolve, reject) => {
    const socket = net.connect(process.env.CANNER_OCR_SOCKET);
    const chunks = [];
    socket.on("data", (d) => chunks.push(d));
    socket.on("error", reject);
    socket.on("close", () => {
      const reply = Buffer.concat(chunks);
      const end = reply.indexOf(10); // the header line ends at the first newline
      if (end < 0) return reject(new Error("no reply"));
      const head = JSON.parse(reply.subarray(0, end).toString());
      if (!head.ok) return reject(new Error(`${head.code}: ${head.error}`));
      resolve({ ...head, data: reply.subarray(end + 1, end + 1 + head.size) });
    });
    socket.write(JSON.stringify({ preset, size: input.length, params }) + "\n");
    socket.end(input);
  });
}

function readBody(req) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    let size = 0;
    req.on("data", (d) => {
      size += d.length;
      if (size <= MAX) chunks.push(d);
    });
    req.on("end", () => (size > MAX ? reject(new Error("too_large: 50 MB at most")) : resolve(Buffer.concat(chunks))));
    req.on("error", reject);
  });
}

http.createServer(async (req, res) => {
  if (req.method !== "POST" || req.url !== "/ocr") return res.writeHead(404).end();
  // A public endpoint needs a per-visitor limit here, such as a few files an hour per IP.
  try {
    const file = await readBody(req);
    const verdict = await scan(file);
    if (!verdict.clean) return res.writeHead(422).end(`Rejected: ${verdict.signature}`);
    const { data } = await ocr(file, "pdf", { lang: "eng+fra" });
    res.writeHead(200, { "content-type": "application/pdf" });
    res.end(data); // nothing is written to disk
  } catch (err) {
    const code = err.message.split(":")[0];
    const status = { too_large: 413, unsupported_input: 415, busy: 429, rate: 429 }[code] ?? 500;
    res.writeHead(status).end(err.message);
  }
}).listen(process.env.PORT || 3000);

// curl --data-binary @scan.pdf -o searchable.pdf https://your-app.example/ocr

Questions

How do I convert a scanned PDF to a searchable PDF?

Run OCR on it and add the text as an invisible layer: ocrmypdf -l eng+fra scan.pdf searchable.pdf. ocrmypdf uses Tesseract and needs it installed on the server. On Canner, the OCR service’s pdf preset does the same without installing anything.

Why do I get TesseractNotFoundError after pip install pytesseract?

pytesseract is only a wrapper around the tesseract command. pip doesn’t install Tesseract itself. Install the tesseract-ocr system package where the app runs (Dockerfile, Aptfile, packages.txt or railpack.json), or set tesseract_cmd to its path.

How do I OCR French text with Tesseract?

Install the French data (tesseract-ocr-fra on Debian and Ubuntu) and pass fra, or eng+fra for documents that mix both languages: -l eng+fra on the command line, lang="eng+fra" in pytesseract.

Can Tesseract.js read a PDF?

No. Its README says it does not support PDF files. Turn each page into an image first, then recognize the images. It returns text, not a searchable PDF.

OCR in English and French, in Canada, with nothing to install.

Text recognition comes with Live: create an account, move your project to Live, turn the service on and redeploy. Files are processed on the same servers as your app and nothing is kept.