DEV Community

Cover image for Why Your PDF Text Extraction Returns an Empty String
Nikolas Dimitroulakis
Nikolas Dimitroulakis

Posted on

Why Your PDF Text Extraction Returns an Empty String

You wrote ten lines of Python, pointed it at a PDF, and got back "". No exception, no warning, nothing.

The reason is almost always the same: that PDF has no text layer. It is a picture of a document, not a document. Text-layer libraries return nothing and report no error, which makes this one of the quieter bugs you can ship.

Here is how to detect it and route around it.

Step 1: Check for a text layer before you extract

From the shell, poppler-utils answers this in one command:

pdffonts document.pdf
Enter fullscreen mode Exit fullscreen mode

Fonts listed means there is a text layer. Empty output means it is a scan.

In Python, with PyMuPDF:

import fitz  # PyMuPDF

def has_text_layer(path, min_chars=50, pages_to_check=3):
    doc = fitz.open(path)
    for page in doc[:pages_to_check]:
        if len(page.get_text().strip()) >= min_chars:
            return True
    return False
Enter fullscreen mode Exit fullscreen mode

Two details worth keeping:

Check several pages, not just the first. Scanned documents often carry a generated cover page with real text in front of forty pages of images. A page-one check sends the whole file down the wrong branch.

Use a character threshold, not a truthiness check. Plenty of scans carry a few stray characters from a header or a watermark. That is enough to pass if text: and nothing more.

Step 2: Text-layer PDFs

PyMuPDF is the fastest general-purpose option:

def extract_text_layer(path):
    doc = fitz.open(path)
    return "\n".join(page.get_text() for page in doc)
Enter fullscreen mode Exit fullscreen mode

If columns come out interleaved, pdftotext -layout document.pdf document.txt often does better, and pdfplumber gives you word-level coordinates when you need to reconstruct the layout yourself.

Step 3: Scanned PDFs

Scans need OCR. OCRmyPDF wraps Tesseract and writes a text layer back into the file, which means the rest of your pipeline stays unchanged:

import subprocess

def ocr_pdf(src, dst, lang="eng"):
    subprocess.run(
        ["ocrmypdf", "-l", lang, "--skip-text", src, dst],
        check=True,
    )
    return extract_text_layer(dst)
Enter fullscreen mode Exit fullscreen mode

Set -l to the right language. The default is English, and accuracy drops sharply on anything else.

For documents the local stack handles badly (poor scans, forms, handwriting), a hosted OCR document data extraction API returns layout-aware parsing without a Tesseract install, and an image OCR API covers loose JPEGs and PNGs.

Step 4: Route per file

def extract(path, ocr_output="ocr.pdf"):
    if has_text_layer(path):
        return {"method": "text-layer", "text": extract_text_layer(path)}
    return {"method": "ocr", "text": ocr_pdf(path, ocr_output)}
Enter fullscreen mode Exit fullscreen mode

Return the method alongside the text and log it. The day output looks wrong, you will know in one query whether the problem was your extraction or the source document.

Calling it as a hosted API

If you would rather not run any of this, the Extract Text from PDF API takes a remote URL or a file upload and returns the text in a single data field:

curl -X POST "https://api.eu.apyhub.com/extract/text/pdf-url" \
  -H "apy-token: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com/report.pdf"}'
Enter fullscreen mode Exit fullscreen mode

It also accepts a page range and coordinate bounds, which is useful when you only need one section of a long report.

Which method for which job

Method Good at Trade-off
pdftotext -layout One-off text-layer extraction, keeps columns roughly intact No structure, little control over output
PyMuPDF Fast bulk extraction with coordinates Tables lose row structure
pdfplumber Word positions, lined tables Noticeably slower on large files
ocrmypdf + Tesseract Clean scans, free, runs locally Accuracy falls off below 300 DPI and on skewed pages
Cloud OCR (Azure, Google, AWS) Poor scans, forms, handwriting Per-page cost, data leaves your infrastructure
Extract Text from PDF API Text-layer PDFs by URL or upload, page ranges and coordinate bounds, one call, nothing to install 50 atoms per call

A note on tables

Tables are their own problem. Lined tables (visible borders) extract reasonably well with pdfplumber or camelot. Unlined tables usually do not, and OCR makes it worse by returning text in reading order and discarding which cell each value came from.

When row and column structure matters, a table extraction API that preserves layout saves more time than tuning a parser will.

The summary

  1. Detect the text layer per file, never per batch.
  2. Text layer goes to PyMuPDF.
  3. No text layer goes to OCR.
  4. Log which branch each file took.

Most of the pain in PDF extraction comes from assuming one method handles everything. Once the routing is in place, each method only has to be good at the job it is actually given.


Every API above is also available through ApyHub MCP, so an AI agent can call them directly without a hand-written wrapper. You can try any of them from its page in the ApyHub catalog or in Voiden, the open-source API client, before writing any code.

Top comments (0)