OCR for scanned PDFs in golang with tesseract, poppler and qpdf
How we read scanned PDFs from a golang service by calling poppler, tesseract and qpdf: when to OCR at all, which page segmentation mode to use, timeouts, one OCR at a time, and passing PDF passwords without putting them on the command line.
A golang service of ours reads text out of PDFs that people upload. Most PDFs have a real text layer and pdftotext handles them in milliseconds. But some are scans: a picture of a page wrapped in a PDF. pdftotext gives you back a few form feeds and nothing else. And some are password protected, so nothing can read them until they're opened.
We didn't want a cloud OCR service for this. The files are private, and the tools that solve this well already exist as plain command line programs: poppler for PDF to text and PDF to image, tesseract for the OCR, and qpdf for passwords. In this blog we will look at how a Go service calls those three safely, which settings mattered, and what I saw when I ran it all in a throwaway Debian container.
The three tools
Everything comes from Debian packages:
apt-get install -y --no-install-recommends poppler-utils qpdf tesseract-ocr tesseract-ocr-eng
On Debian 13 (trixie) that gave me tesseract 5.5.0, poppler 25.03.0 and qpdf 12.2.0. On a Mac it's brew install poppler qpdf tesseract. I didn't have them on my Mac, so I cross-compiled the Go binary for linux/arm64 and ran everything inside debian:trixie-slim with the binary mounted in. Each container was removed with --rm after the run.
The order of work for one file is:
- If qpdf says it is encrypted, decrypt it with the password, if we have one.
- Run
pdftotext. If there is enough text, we're done. - Otherwise render the pages to PNG with
pdftoppmand OCR each one with tesseract.
OCR is slow and it makes mistakes, so it only runs when the text layer is missing. That was the first rule we settled on and I still think it's the most important one.
Is it really a scan
How do you know the text layer is missing? pdftotext on a scan doesn't fail. It succeeds and prints whitespace and one form feed per page. So we count letters and digits per page, and below 40 per page we call it a scan:
text, err := pdftotext(ctx, path)
if err != nil {
return Result{}, err
}
pages := strings.Count(text, "\f")
if letters(text) >= minCharsPage*max(pages, 1) {
return Result{Text: text, Pages: pages}, nil
}
if !o.OCR {
return Result{Text: text, Pages: pages}, ErrNeedsOCR
}
text, pages, err = ocrPDF(ctx, path, dir, o.Layout)
func pdftotext(ctx context.Context, path string) (string, error) {
ctx, cancel := context.WithTimeout(ctx, textTimeout)
defer cancel()
var out, stderr bytes.Buffer
cmd := exec.CommandContext(ctx, "pdftotext", "-layout", "-enc", "UTF-8", "-q", path, "-")
cmd.Stdout, cmd.Stderr = &out, &stderr
if err := cmd.Run(); err != nil {
return "", fmt.Errorf("pdftotext: %v: %s", err, strings.TrimSpace(stderr.String()))
}
return out.String(), nil
}
-layout keeps columns where they were on the page, which matters for anything with a table in it. The - at the end sends the text to stdout so we don't need a temp file for the output. Every external command runs with exec.CommandContext and a timeout, so a broken PDF that makes a tool hang can't hold a request forever.
The ErrNeedsOCR is the kill switch. OCR is on only when tesseract and pdftoppm are on PATH and OCR_ENABLED isn't set to something other than true. If OCR ever starts eating the box, we flip the env var and restart, and scans come back with a clear "needs OCR" status instead of an error.
func OCRFromEnv() bool {
if v, ok := os.LookupEnv("OCR_ENABLED"); ok && v != "true" && v != "1" {
return false
}
_, e1 := exec.LookPath("tesseract")
_, e2 := exec.LookPath("pdftoppm")
return e1 == nil && e2 == nil
}
Rendering the pages
cmd := exec.CommandContext(rctx, "pdftoppm",
"-r", dpi, "-scale-to", maxSide, "-png",
"-f", "1", "-l", strconv.Itoa(MaxOCRPages),
path, filepath.Join(dir, "page"))
if out, err := cmd.CombinedOutput(); err != nil {
return "", 0, fmt.Errorf("pdftoppm: %v: %s", err, strings.TrimSpace(string(out)))
}
pages, _ := filepath.Glob(filepath.Join(dir, "page-*.png"))
if len(pages) == 0 {
return "", 0, errors.New("pdftoppm rendered no pages")
}
sort.Slice(pages, func(i, j int) bool { return pageNo(pages[i]) < pageNo(pages[j]) })
300 DPI is what tesseract likes for normal text. But a PDF page can be any size, and a huge page at 300 DPI turns into a giant image that takes ages to OCR. -scale-to 3600 caps the longer side at 3600 pixels. An A4 page at 300 DPI is 3508 pixels tall, so normal pages are untouched and only the oversized ones shrink.
-f 1 -l 20 stops at 20 pages. Nobody needs page 400 of an upload OCR'd inside an API call.
pdftoppm names the files page-1.png or page-01.png depending on how many pages there are, padding to the width of the last page number. I sort by the parsed number anyway. Sorting strings works until it doesnt, and parsing the number cost nothing.
Running tesseract
// ocrSlot lets one OCR run at a time in this process, so a burst of scans
// can't eat all the CPU the API needs.
var ocrSlot = make(chan struct{}, 1)
func Tesseract(ctx context.Context, image string, layout Layout) (string, error) {
ctx, cancel := context.WithTimeout(ctx, perPage)
defer cancel()
if layout == "" {
layout = LayoutBlock
}
select {
case ocrSlot <- struct{}{}:
defer func() { <-ocrSlot }()
case <-ctx.Done():
return "", ctx.Err()
}
cmd := exec.CommandContext(ctx, "tesseract", image, "stdout", "-l", "eng", "--psm", string(layout))
cmd.Env = append(os.Environ(), "OMP_THREAD_LIMIT=1")
out, err := cmd.Output()
if err != nil {
var ee *exec.ExitError
if errors.As(err, &ee) {
return "", fmt.Errorf("tesseract: %v: %s", err, strings.TrimSpace(string(ee.Stderr)))
}
return "", fmt.Errorf("tesseract: %w", err)
}
return string(out), nil
}
The OCR runs inside the same process that serves the API. That was a choice, and it comes with a cost: if five people upload scans at once, five tesseracts fight the API for CPU. The buffered channel of size one is a semaphore. One OCR at a time per process, the rest wait their turn, and the wait counts against the page timeout so nobody waits forever.
OMP_THREAD_LIMIT=1 stops tesseract from starting a thread per core. On my test image with 10 cores available, the default run took 0.133s of wall time and 0.277s of CPU, and with the limit it took 0.131s of wall time and 0.126s of CPU. Same speed, half the CPU. When the API shares the box, that's an easy win.
There are two timeouts, 120 seconds for rendering all pages and 90 seconds per page for OCR. Generous, but they are there for the case where something goes very wrong, not for normal files.
Page segmentation modes
This was the part that surprised me most when I tested it. Tesseract's --psm tells it how to split the page into blocks before reading. We use three:
const (
LayoutBlock Layout = "6" // one uniform block: keeps table rows on one line
LayoutAuto Layout = "3" // finds columns, so side-by-side text doesn't interleave
LayoutSparse Layout = "11" // scattered text, e.g. a photo of a card or label
)
To see the difference I drew a test image with Pillow: two columns of six lines each, and a few labels scattered below. Here is psm 6 on it:
The left column talks Right side is another
about the first thing story that has nothing
and keeps going for to do with the left
a few more lines so one and should be read
Every line has half of the left paragraph and half of the right one glued together. For a table that's exactly right, a row stays a row. For two columns of text it is garbage. psm 3 on the same image:
The left column talks
about the first thing
and keeps going for
a few more lines so
tesseract sees a real
block of text here.
NAME
A. Example
Right side is another
story that has nothing
The columns come out as two separate blocks. And psm 11 finds every bit of text but loses the order, it alternates left, right, left, right line by line with blank lines between. It's useful only when you are hunting for scattered labels and don't care about reading order.
So the default is 6, because most of what we read is tabular. For layouts we know have panels side by side, a second pass runs with 3 and we keep whichever result our parser reads better. psm 11 runs only to fill a few gaps in the first result, never to replace it. Running OCR twice is slow, so these extra passes only happen for scans that need them.
On my fake two page scan (a table plus a short two-column bit, rotated 0.6 degrees and a little blurred, at 200 DPI) psm 6 got every row and every amount right and took 1.3 seconds for both pages. The two-column part in that file came out right with 6 and with 3, because each column was only two lines. Small test, but the table result was what I wanted to see.
Password-protected PDFs
qpdf --is-encrypted file.pdf exits 0 when the file is encrypted. Then we decrypt into a temp file and read that:
// decrypt writes an unencrypted copy. The password goes through a 0600 file,
// never the command line, where any user on the box could read it with ps.
func decrypt(ctx context.Context, in, out, password, dir string) error {
pw := filepath.Join(dir, "pw")
if err := os.WriteFile(pw, []byte(password), 0o600); err != nil {
return err
}
defer os.Remove(pw)
var stderr bytes.Buffer
cmd := exec.CommandContext(ctx, "qpdf", "--password-file="+pw, "--decrypt", in, out)
cmd.Stderr = &stderr
err := cmd.Run()
var ee *exec.ExitError
if errors.As(err, &ee) && ee.ExitCode() == 3 {
if _, statErr := os.Stat(out); statErr == nil {
return nil // 3 means "done, with warnings"
}
}
if err != nil {
if strings.Contains(strings.ToLower(stderr.String()), "password") {
return ErrPassword
}
return fmt.Errorf("qpdf: %v: %s", err, strings.TrimSpace(stderr.String()))
}
return nil
}
Two details here. First, --password=... on the command line is visible in ps and in /proc to anyone on the machine, so the password goes in a private file instead and the file is deleted right after. Second, qpdf exits with 3 when it finished but had warnings, which happens a lot with PDFs from odd generators. Exit 3 with an output file is a success. Treat it as an error and you reject files that are perfectly readable.
I tested it by encrypting the fake scan with qpdf itself, AES-256:
qpdf --encrypt s3cret-pw owner-pw 256 -- scan.pdf locked.pdf
PDF_PASSWORD_FILE=/tmp/pw readpdf locked.pdf
Without a password it stopped with pdf is password protected. With the right one it decrypted, found no text layer, and OCR'd the two pages. With a wrong password I got the same password error back, not some confusing qpdf message.
Low resolution scans
One more thing we added four days after the first OCR version went in. Some PDFs are a phone photo at low resolution placed on a page. Rendering that page at 300 DPI just scales the small photo up and blurs it, and the OCR text is poor. So when the OCR result is thin (under about 200 letters per page) we also pull the embedded images out at their native size with pdfimages -png -p, skip anything smaller than 300 pixels on a side (logos and stamps), OCR those, and keep whichever result has more text. It is a fallback for the bad cases, nothing more.
Things I'd keep
Wrap every external tool in exec.CommandContext with its own timeout. Use a temp dir per file and defer os.RemoveAll. Log the tool's stderr when it fails, but never the extracted text, it's the user's document. And keep OCR text going through the same plain parsers as normal text. We never send it to a model.
If you're building the container for this, the Dockerfile can be the same multi-stage shape as in creating a multi-stage Dockerfile for a golang web service, with the apt line above in the final stage. It makes the image noticeably bigger, so I'd keep OCR in its own image if only one service needs it.