
To extract text from a PDF with Python, start by checking what the file contains. A digitally generated PDF may expose selectable text. A scanned page can show readable words without containing a text layer. The same extraction call can return an empty string for a blank page, an image-only page, or a page the library cannot interpret.
This guide builds a local batch job with pypdf. It writes one UTF-8 text file per page that returns text, plus a manifest recording the source file, content hash, page number, and outcome. It does not perform OCR, reconstruct tables, or accept public uploads.
Validation status, November 13, 2026: Twenty local tests passed on Windows 11 with Python 3.12.14 and pypdf 7.0.1. The five-file demonstration produced two text files and six manifest records. Source pages were rendered and visually inspected; extracted names and record IDs were checked. Linux/macOS, a clean dependency installation, hostile files, hard resource limits, interruption recovery, concurrent workloads, OCR, and Hivenet deployment remain untested.
The useful outcome is text you can trace back to a page and inspect. Finding some characters does not establish that every word was captured, columns remained in reading order, or a table became usable rows. Keep the source document alongside the result while evaluating a new document type.
Use the pypdf text-extraction guide for the library's extraction modes and limitations. pypdf reads PDF text; it does not recognize words inside a scanned image. PDFs also do not consistently encode the paragraph and table structure a downstream application may expect.
For an image-only document, assess a separate OCR step, such as OCRmyPDF, and check its output. For tables, use a table-oriented extraction and validation process rather than splitting arbitrary extracted lines on spaces. Neither workflow is implemented in this sample.
For a bounded example, make scanned PDFs searchable with OCRmyPDF. The local Windows walkthrough uses RapidOCR, compares recognized text with rendered pages, and records a rotation failure. It does not turn an empty extraction into proof of a scan or establish cloud accuracy or capacity.
If you need to create a PDF rather than read one, the Python PDF report guide covers generating a report and inspecting the resulting pages. Its use of text extraction is one content check, not proof that the layout is correct.
Download the PDF text-extraction sample, fixtures, and tests. Extract it into a new private directory. The archive includes extract_pdf.py, test_extract_pdf.py, requirements.txt, five synthetic inputs, a README, and the observed example-output directory. It contains no customer documents or credentials.
The extraction code uses pypdf 7.0.1, the version tested here. The documentation currently describes newer releases too; do not treat the pinned version as a claim that it is the newest. The test environment already contained the dependency. The following installation procedure was not exercised in a clean environment:
python -m venv .venv
.venv/Scripts/python.exe -m pip install -r requirements.txt
From the extracted project directory, run the tests and the fixture batch. These commands use a Windows virtual-environment path; Linux and macOS paths differ.
.venv/Scripts/python.exe -m unittest -v
.venv/Scripts/python.exe extract_pdf.py fixtures run-01
Use a new output directory each time. The program refuses an existing directory, even an empty one, and will not put output inside the input directory. The shipped example-output directory is evidence to inspect, not a directory to overwrite.
The program sorts top-level files with a .pdf extension, including uppercase .PDF, and processes at most 20. Each file is read into a bounded byte buffer and hashed before parsing. That hash identifies the bytes examined in this run; it is not an authenticity check. Keep inputs stable throughout the run and record where they came from.
PDF parsing uses strict=True. The sample rejects encrypted files without trying passwords. A document that cannot be opened becomes an error record, while the remaining inputs continue. The strict-mode documentation explains the tradeoff between raising errors and attempting best-effort recovery. Strict parsing is not malware protection.
For each readable page, the program calls extract_text(). A page failure is recorded separately. Non-whitespace text is written to a numbered file; an empty result is marked needs_review with the reason no_text_found. The sample does not automatically decide whether such a page is blank or scanned.
This excerpt from the complete implementation shows the central extraction decision. The surrounding download supplies the input checks, record function, exclusive output writes, and completion handling:
for page_number in range(1, page_count + 1):
try:
text = reader.pages[page_number - 1].extract_text() or ""
except Exception:
record(path.name, digest, page_number, "error", "page_extraction_failed")
continue
if not text.strip():
record(path.name, digest, page_number, "needs_review", "no_text_found")
continue
if len(text) > MAX_CHARS:
record(path.name, digest, page_number, "rejected", "character_limit")
continue
Output names combine a sorted file number, a shortened hash, and a one-based page number. The manifest retains the full hash and source filename. Two files with the same bytes but different names still receive separate output paths; the job does not silently deduplicate them.
Reasons are short, fixed labels rather than raw exception messages. This keeps the manifest predictable, but it also limits diagnostics. A parser error needs separate local investigation. The script is a teaching example, not a complete operations or logging system.
The fixture directory contains a two-page text report, a blank page, an image-only page, an encrypted copy of the report, and deliberately malformed bytes. The encrypted fixture is used only to check rejection; it is not an example of recommended encryption.
The demonstration completed with exit code 2 and this summary:
{
"files": 5,
"records": 6,
"counts": {
"error": 1,
"extracted": 2,
"needs_review": 2,
"rejected": 1
},
"exit_code": 2
}
The two text files retained the names Málaga, Łódź, and Zoë, plus DEMO-001 on page 1 and DEMO-002 on page 2. The blank and image-only pages produced no text files. Both received no_text_found, which was the correct signal to inspect the sources rather than claim success.
The manifest uses page numbers for page-level results. It uses null when the failure or rejection applies to the whole file, such as an encrypted document or an opening error. A manifest record is therefore not always a page. Here, four readable pages and two file-level outcomes produce six records.
We rendered the four readable source pages with Poppler and inspected them alongside the text outputs. This confirms the bounded fixture result. It does not establish accurate reading order for multi-column pages, other writing systems, unusual fonts, or arbitrary business documents.
Exit code 0 means every recorded outcome returned non-whitespace text. It does not certify semantic correctness. Exit code 2 means the manifest and completion marker were written, but at least one input needs attention. Exit code 1 reports a caught setup or output failure; other uncaught failures can also end the process with a nonzero code.
The program writes manifest.json after processing the batch, then complete.json last. Require a valid completion marker and inspect its counts and the process exit code. Text files alone can be leftovers from an incomplete run. The marker is an application convention, not a crash-safe transaction or a guarantee against power loss.
Writing an output file unsuccessfully aborts the batch. Already written files can remain, but no completion marker should be present for that attempt. The tests exercised a simulated output-write error, not a full disk, forced termination, or a failed storage device.
A rerun into the same directory is refused. A fresh directory produced identical manifest and text bytes for the same stable fixtures in the recorded environment. Retain the original inputs and dependency version when comparing runs; different library versions or inputs can change results.
The example accepts at most 20 PDF files, reads at most 5 MiB plus one limit-detection byte from each file, permits at most 50 pages per document, and accepts at most 200,000 extracted characters per page. These are small exercise limits, not recommended production sizes.
The page count is checked after opening the PDF, and the character limit is checked after extraction. Those checks cannot prevent a parser from consuming substantial resources first. The process has no hard memory cap or wall-clock timeout. A compressed file's disk size does not establish its processing cost.
Keep this sample restricted to controlled local documents. A public upload service needs a separate design for authorization, file handling, process isolation, resource enforcement, retention, and failure recovery. Do not put an uploaded filename directly into an output path or assume that a .pdf extension makes a file safe. Symlink and file-mutation race attacks were not tested.
The 20 tests cover Unicode content and page provenance, blank and image-only pages, malformed and encrypted inputs, mixed outcomes, output-directory refusal, identical fresh reruns, duplicate-content filenames, empty batches, count/byte/page/character limits, simulated page and output failures, nested-output refusal, ignored non-PDF files, directory rejection, and command-line exit codes.
These tests used synthetic files and local filesystem access. No OCR engine, worker queue, HTTP endpoint, scheduler, cloud instance, or load test was run. A failed-page simulation demonstrates the application's error branch; it does not reproduce every damaged PDF.
An occasional extraction job can stay on your machine. A recurring batch may justify a CPU VM when you need a stable environment, control over dependencies, or a worker separate from an API. A managed document service may fit better if operating the parser and its failure handling is not work your team wants to own.
Before selecting capacity, measure representative document types, accepted output, runtime, and peak memory. Include rejected files and retries in that exercise. This small fixture supplies no Hivenet throughput, accuracy, capacity, or savings result.
The CPU VM buying guide connects the choice to memory, storage, access, and operating responsibilities. If jobs later arrive through multiple producers, the Celery and Redis guide can help assess a separate worker. This extractor has no Celery adapter, durable queue handoff, or retry integration.
Start with one document family and an explicit acceptance rule. Keep page provenance and rejected-input records, inspect representative outputs, and establish recovery behavior on the intended host before treating a recurring extraction job as dependable.
Pick one AI, compute, or storage workload and see the difference for yourself. Spin it up in minutes, or let our team map your fastest path to production.