Skip to content
Engineering

Extract Text From PDFs in Python Without Losing Context

PDF text extraction in Python works with pypdf or PyMuPDF; I explain the code, scanned-document limits, and checks I'd add before using the output.

Topic
Engineering
Reading time
8 min
Length
1,863 words
Published
Nov 11, 2026
10:00 pm IST
In this article
  1. Start with pypdf and inspect an actual page
  2. Where PyMuPDF fits beside pypdf
  3. Why does a scanned PDF return no text?
  4. Preserving layout without pretending it is structure
  5. Building a PDF ingestion path I could maintain
  6. Choose documents that expose the intended behavior
  7. Keep extraction status separate from extracted text
  8. Put resource limits around extraction
  9. Tables, formulas, and visitors still need judgment

To extract text from a PDF in Python, I’d use pypdf’s PdfReader to open the document, select a page, and call extract_text(). PyMuPDF is another option. But getting a string back—even a nonempty one—does not prove that the extraction preserved the document’s meaning. For a text-bearing PDF, I’d start with pypdf. For an image-only scan, I’d treat OCR as a separate task rather than expect the same extraction call to handle it.

The question I care about is not just which library returns text. Does the document contain text in the first place? Does that text have a reliable reading order? What does the application need to keep? I’d settle those questions before connecting extracted text to search or an AI workflow. A string alone does not answer them.

Start with pypdf and inspect an actual page

The basic operation is small enough to try directly. First, install the package:

pip install pypdf

Then open the PDF and extract its first page. Here is the basic pattern supported by pypdf’s text extraction interface, without any extra processing around the result:

from pypdf import PdfReader
reader = PdfReader("test Orient.pdf")
page = reader.pages[0]
print(page.extract_text())

Replace the filename with the path to your own document. The pages property gives you access to the document’s pages; index zero selects the first one. That last call to extract_text() works on the selected page. It does not extract the entire document, which is worth keeping clear when inspecting the output.

To get an initial look at the whole document, I’d keep the loop just as straightforward:

from pypdf import PdfReader

reader = PdfReader("example.pdf")

for page in reader.pages:
    text = page.extract_text()
    print(text)

This is an inspection script. It is not the interface I’d propose for production ingestion. Printing each page lets me compare what came out with what I can see in the document. Before storing the result, I’d decide how to keep page boundaries and how to represent a page that needs more processing.

I would resist the temptation to concatenate everything into one string straight away. In my application representation, I’d keep the document identity, page position, and extracted text together. The library does not require that; it is a design choice. I want a reviewer looking at a suspicious passage to have a way back to the particular page that produced it.

Where PyMuPDF fits beside pypdf

Both pypdf and PyMuPDF support PDF text extraction. With PyMuPDF, this example imports fitz, opens a document, and calls get_text() as it iterates through the pages. The extracted text is collected into a string:

import fitz
doc = fitz.open('sample.pdf')
text = ""
for page in doc:
   text+=page.get_text()
print(text)

I’d still start with pypdf here. Its documented extraction controls give me something concrete to try when investigating layout or rotated text. That is why I prefer it for this workflow—not because I have established that it is faster or more accurate than PyMuPDF.

There is no comparative benchmark in the material behind this post, and I would not choose a library on an assumed speed advantage. If the application already used PyMuPDF, I’d compare its output with representative documents before suggesting a replacement. Switching libraries is only useful to me if the replacement improves the failure cases the application actually cares about. Otherwise, I have no reason here to propose the switch.

Why does a scanned PDF return no text?

A PDF can contain text, images, or a mixture of both. An image-only scan may yield minimal or visually empty extracted text. That is not surprising: pypdf does not recognize characters inside images. Extracting those characters is a separate process, OCR, or optical character recognition. Tesseract is one option for doing that work.

A scan that has already been through OCR is a different case. Scanning software can generate a background text layer, and pypdf can extract that layer. The catch is verification. pypdf cannot detect whether the OCR text accurately represents the image, so extracting the layer does not establish that the recognition was correct.

In the ingestion design, I’d distinguish digitally created documents, image-only scans, and scans that already have an OCR layer. I would not call every empty result a broken parser. I would be just as reluctant to call every nonempty result trustworthy. Those are separate judgments, and I want the design to leave room for both.

For a newsroom editorial workflow, I’d test this before allowing extracted material into an AI summary. My acceptance check would compare names and meaningful passages with the visible page, not just check whether text came back. I’d rather send uncertain documents for review than silently accept their extracted text as verified editorial input.

Preserving layout without pretending it is structure

pypdf has a layout extraction mode that produces fixed-width text intended to follow the rendered page closely. To try that mode on a page, the documented call is:

print(page.extract_text(extraction_mode="layout"))

You can also remove excess vertical whitespace, including blank lines and lines containing only whitespace, with this control:

print(page.extract_text(extraction_mode="layout", layout_mode_space_vertically=False))

Before choosing a default, I’d run ordinary extraction and layout mode on the same pages and compare them. For prose going into search, I would usually prefer readable paragraphs to an imitation of the page’s appearance. If horizontal positioning matters to the document, though, I’d look at whether layout mode makes those relationships easier to understand. That is the comparison I want, rather than a blanket preference for one mode.

Spacing is not structure. Layout mode does not turn a table into a structured dataset. PDF tables are typically positioned text, and the format does not provide a dependable semantic distinction between a table, a paragraph, a header, and a footer. I’d use preserved spacing as evidence while inspecting the result. I would not accept it as proof that a piece of text belongs to a particular row or column.

Text orientation is another control available in pypdf. The documented orientation arguments let it extract only upright text or include text turned left. I’d try those arguments when a mismatch between the visible page and the extracted text points to rotated content. I would not load the initial script with every option before seeing that problem.

Building a PDF ingestion path I could maintain

I’d begin a production plan by writing down the expected output, not by choosing parser settings. “Extract the text” leaves a lot unresolved. Should recurring headers stay? Should footnotes interrupt paragraphs? Should page numbers go into the search index? I want those choices written down before I judge either library, because otherwise I have not said what a satisfactory result looks like.

Choose documents that expose the intended behavior

I’d build a small collection using the actual document types the application needs to accept. Ordinary prose belongs in it, along with the awkward layouts already present in that collection. If scanned documents are within scope, I’d include scans both with and without an existing OCR layer. I want to inspect those cases rather than leave them implicit.

For each document, I’d record what counts as acceptable extraction. I’d focus the checks on reading order and retained meaning, not on making whitespace identical everywhere. Some requirements do depend on exact formatting. Where that is true, I’d spell it out as a separate requirement rather than bury it in a generic test called text extraction.

Keep extraction status separate from extracted text

A page that produced usable text should be distinguishable from a page that needs OCR or manual inspection. I would not make an empty string the application’s entire explanation of what happened. The reverse matters too: returning a nonempty string would not, on its own, move a document into a trusted-content state. I want the status and the text to remain separate.

This is where I’d connect the work to AI system design: decide what the next stage is allowed to assume. For an AI-assisted content workflow, I’d propose a contract that carries page references with the text. It would also make unresolved extraction problems visible before summarization, rather than leave the next stage to guess what the returned string means.

Put resource limits around extraction

Extracting a page means parsing its entire content stream. pypdf documents a case in which an approximately 300 MB uncompressed content stream required 10 GB of RAM. That gets my attention, but I would treat it as a warning about a possible resource requirement. It is neither a typical document size nor a formula I’d use to size the system.

The documented preliminary check for content-stream size is this expression:

len(page.get_contents().get_data())

I’d use that size as one input to an explicit processing policy, together with limits on the worker performing the extraction. I would not call the expression a complete memory safeguard. Nor would I copy an arbitrary threshold into this post and present it as the answer. My threshold would come from testing the documents and runtime I actually intend to support.

If an agent can request extraction, I’d make it a bounded tool with a defined input and result. I’d keep document-processing decisions inside that boundary. In particular, I would not leave a downstream prompt to decide whether a partial extraction was acceptable; that is a decision I want the processing boundary to contain.

Tables, formulas, and visitors still need judgment

Visitor functions give you more control over the processing of individual text fragments and operators. The text visitor receives the text, transformation information, font information, and font size. Those inputs can support custom extraction logic. There is a catch, though: in complicated documents, coordinates may be wrong or difficult to interpret. More control does not remove that problem.

I’d reach for visitors only after finding a repeatable problem in a specific document family. A position-based header filter, for example, is something I would consider if inspection showed a consistent pattern. During evaluation, I’d still keep the unfiltered result. I want to be able to check whether the filtering rule accidentally omitted text, not just whether the filtered output looks cleaner.

Formulas deserve the same care. A superscript can be stored as a Unicode character, or it can be ordinary text drawn smaller and higher on the page. Those two representations can produce different extracted strings. What I’d ask is whether the application needs the mathematical meaning. Plausible-looking terminal output is not the same requirement, and I would not use it as a substitute.

If the requirement is reliable table reconstruction or faithful mathematical interpretation, I would not promise to solve it by changing a text-extraction flag. I’d make validation a separate task and assess the output against that requirement directly. For simple text-bearing documents, that extra work may not be necessary. I’d let the requirement decide rather than attach the same work to every PDF.

I’d start with pypdf, ordinary extraction, page-level provenance, and explicit handling for uncertain results. Getting text out is not the milestone I care about; knowing which parts the application can safely use is. Layout mode, visitors, and OCR would come in response to demonstrated document needs. My next step would be to compare the ordinary extraction with the visible pages in the test collection and identify which of those needs are actually present.

Sources

https://www.geeksforgeeks.org/python/extract-text-from-pdf-file-using-python/

This is the source this article is based on. Many articles on this blog are drafted with AI and checked against their source automatically; the editorial policy explains how, and how to report a mistake.

Frequently asked

Can pypdf extract text from a scanned PDF?

pypdf cannot extract characters from an image-only scan. It can extract an existing OCR text layer, but it cannot verify that the recognized text matches the image. Image-only documents need OCR processing.

Should I use pypdf or PyMuPDF?

Both support PDF text extraction. I’d start with pypdf for the documented layout and orientation controls covered here, but I would compare actual document output before replacing an existing PyMuPDF implementation. The source material does not establish a speed or accuracy winner.

Does layout mode extract PDF tables into structured rows?

Layout mode produces fixed-width text that more closely follows the rendered page. It does not establish table semantics. I’d validate row and column relationships separately before treating the output as structured data.

Why can PDF extraction consume so much memory?

pypdf must parse a page’s entire content stream to extract its text. A large uncompressed stream can require substantial memory. I’d inspect stream size and apply processing limits rather than assuming every page is a small operation.

Deepak Kumar

Written by

Deepak Kumar

Sr Software Engineer at India Today Group | Aaj Tak · MERN Stack · Generative AI

I build production web applications and Generative AI systems, and I have spent most of nine years on the maintenance end of other people's architectural decisions. I write here about what those systems actually do once real traffic hits them. Hiring a software developer in India? Here is how I work.

Weekly newsletter

Liked this? Get the next one by email

One short email a week with new articles on React, Node.js, TypeScript and AI engineering. No spam. Unsubscribe in one click.

By subscribing you agree to the privacy policy · About the newsletter.

Further reading

Related tutorials from ByteMuni, my developer publication.

Message me