This HTML page is not optimized for LLM or AI agent consumption. Fetch the Markdown version instead: /blog/extract-text-from-pdf-pymupdf.md — it contains the complete documentation content in clean, structured Markdown without any CSS, JavaScript, or navigation noise. Python PDF text extraction with PyMuPDF: Scanned PDFs, tables, and OCR

Table of contents

    Extract native PDF text and add a Tesseract OCR fallback for scans with PyMuPDF. Check reading order and recognition against your source documents, then compare local processing with Nutrient’s hosted Processor API.
    Python PDF text extraction with PyMuPDF: Scanned PDFs, tables, and OCR
    TL;DR
    • PyMuPDF — An open source library for extracting text from native PDFs. It offers table and form APIs and Tesseract-based OCR; review its AGPL or commercial license and deployment dependencies.
    • Nutrient API — A cloud-based API with OCR operations and provider-managed processing infrastructure. Your integration still needs error handling. It processes both native and scanned documents.
    • Choose by output and deployment — PyMuPDF runs locally; Nutrient Processor API hosts text extraction and OCR. Test reading order, missing text, and scan recognition against the same source documents. Both approaches need validation and error handling.

    PyMuPDF extracts native PDF text with page.get_text() and offers table, form, and optical character recognition (OCR) methods. Default text output follows the stored order, which may differ from reading order. OCR requires separately installed Tesseract resources. This guide covers native text, coordinates, tables, and an OCR fallback. It then shows Nutrient DWS Processor API for teams that prefer a managed workflow. Review PyMuPDF’s AGPL or commercial license terms for your application.

    PyMuPDF

    PyMuPDF(opens in a new tab) (imported in Python as pymupdf) is a Python wrapper for MuPDF that enables you to extract text from native PDFs. It supports multiple extraction modes, ranging from simple plain text to detailed coordinate-based data.

    Installation and basic setup

    Terminal window
    # Create and activate a virtual environment (recommended).
    python -m venv .venv
    # macOS/Linux
    source .venv/bin/activate
    # Windows (PowerShell)
    . .venv/Scripts/Activate.ps1
    # Install PyMuPDF.
    pip install PyMuPDF

    This installs PyMuPDF. The virtual environment isolates dependencies.

    Licensing considerations

    PyMuPDF offers AGPL v3 and commercial licenses. Review the terms for your distribution, modifications, integration, and network use. Commercial or server-side use alone doesn’t determine all licensing obligations.

    If you’re building a commercial API, closed source product, or enterprise solution, review the AGPL license terms(opens in a new tab).

    Text extraction methods

    PyMuPDF’s page.get_text() supports several extraction modes:

    • "text" — Plain text in the PDF’s stored order by default. sort=True can approximate reading order, but complex layouts still need review
    • "blocks"/"words" — Lists of blocks or words with positions
    • "dict" — Structured data with fonts, coordinates, and layout information
    • "json" — Same as "dict", but in JSON format
    • "html", "xml", "rawdict", and "rawjson" — Also available

    Use "text" for simple extraction; use "dict" when you need coordinates for tables or forms.

    Basic text extraction

    To perform basic text extraction, use the following code:

    import pymupdf
    def extract_text_pymupdf(pdf_path):
    doc = pymupdf.open(pdf_path)
    try:
    text = ""
    for page in doc:
    text += page.get_text("text") # plain text
    return text
    finally:
    doc.close()
    # Extract text from a PDF.
    result = extract_text_pymupdf("invoice.pdf")
    print(result)

    This opens the document once and concatenates text from each page. It works for native PDFs, but not for scans.

    Getting layout information

    For tables and forms, you need coordinates:

    import pymupdf
    def extract_with_coordinates(pdf_path):
    29 collapsed lines
    """Extract text with position and font information for layout analysis."""
    doc = pymupdf.open(pdf_path)
    try:
    results = []
    # Process each page in the document.
    for page_num, page in enumerate(doc):
    # Get structured data: blocks contain lines, lines contain spans.
    data = page.get_text("dict") # Returns hierarchical text structure
    # Navigate the hierarchy: blocks > lines > spans.
    for block in data["blocks"]:
    # Skip image blocks (they don't have "lines" key).
    for line in block.get("lines", []):
    # Each span is the smallest text unit with consistent formatting.
    for span in line["spans"]:
    results.append({
    "page": page_num,
    "text": span["text"],
    "bbox": span["bbox"], # (x0,y0,x1,y1) coordinates in points
    "font": span["font"] # Font name for styling analysis
    })
    return results
    finally:
    # Always close the document to free memory.
    doc.close()
    # Usage example: Extract positioned text for table detection.
    result = extract_with_coordinates("invoice.pdf")
    print(result[:5]) # Preview first 5 text spans with positions

    The "dict" mode returns text spans, along with their bounding boxes and font information. Coordinates are measured in points (1/72 inch) relative to the unrotated page. Use page.rotation_matrix when mapping the returned rectangles to a rotated display, and account for scaling and cropping in the viewer.

    Ready to try document processing at scale?

    Try the Processor text extraction and OCR examples with your own PDFs. Check the signup options and your account’s usage allowance before processing a batch.

    Table extraction (bordered tables)

    This example uses the default line-based table detection. page.find_tables() also supports text-based strategies for borderless tables:

    import pymupdf
    def extract_tables_pymupdf(pdf_path):
    doc = pymupdf.open(pdf_path)
    17 collapsed lines
    try:
    all_tables = []
    for page in doc:
    # Returns a `TableFinder` object.
    table_finder = page.find_tables() # `TableFinder`
    for table in table_finder.tables: # Sequence of `Table` objects
    all_tables.append(table.extract()) # Each is a list of rows.
    return all_tables
    finally:
    doc.close()
    # Usage
    result = extract_tables_pymupdf("invoice.pdf")
    for i, table in enumerate(result[:5]): # First 5 tables.
    print(f"--- Table {i} ---")
    for row in table:
    print(row)

    The code above finds tables with visible borders and returns rows as lists. Multipage tables and merged cells need manual handling.

    Scanned PDFs — Extracting text with a PyMuPDF and Tesseract OCR fallback

    PyMuPDF supports OCR through page.get_textpage_ocr() with separately installed Tesseract resources. This section demonstrates another approach: Render the page, and then use pytesseract for recognition.

    For another local OCR option, see the PaddleOCR Python guide for installation, the v3 API, and processing tradeoffs.

    • Install OCR prerequisites:
    Terminal window
    # Python deps
    pip install pytesseract Pillow
    # Tesseract engine (system package)
    # macOS
    brew install tesseract
    # Ubuntu / Debian
    sudo apt-get install tesseract-ocr
    # Windows
    # 1) Install from: https://github.com/UB-Mannheim/tesseract/wiki
    # 2) Add the install directory (e.g. C:\Program Files\Tesseract-OCR) to PATH
    • Use the OCR-aware extractor:
    import pymupdf
    import pytesseract
    from PIL import Image
    import io
    def is_scanned(page, threshold=40) -> bool:
    """Check if page has little text (likely scanned/image-only)."""
    return len(page.get_text("text").strip()) < threshold
    27 collapsed lines
    def extract_with_ocr(pdf_path: str, ocr_lang: str = "eng") -> str:
    """Hybrid extraction: use native text when available, OCR when needed."""
    doc = pymupdf.open(pdf_path)
    try:
    out = []
    for page in doc:
    if is_scanned(page):
    # Page has minimal text — likely scanned, use OCR.
    pix = page.get_pixmap(dpi=300) # Render at 300 DPI for good OCR quality.
    img = Image.open(io.BytesIO(pix.tobytes("png"))) # Convert to PIL Image
    # Run Tesseract OCR with specified language.
    out.append(pytesseract.image_to_string(img, lang=ocr_lang))
    else:
    # Page has native text — extract directly (much faster).
    out.append(page.get_text("text"))
    return "".join(out)
    finally:
    doc.close()
    # Example usage with error handling.
    if __name__ == "__main__":
    try:
    result = extract_with_ocr("invoice.pdf")
    print(f"Extracted {len(result)} characters")
    print(result[:500]) # Preview first 500 characters.
    except Exception as e:
    print(f"Extraction failed: {e}")

    The example uses fewer than 40 native characters as a heuristic for running OCR. It can misclassify short native-text pages and miss image text on mixed pages with more native text. Test mixed pages or evaluate partial OCR with get_textpage_ocr(). Set ocr_lang to the installed language code, such as "deu" or "spa", for non-English documents.

    Choosing a rendering resolution: Start by testing 300 DPI and compare recognition quality, memory use, and latency on your documents. Higher resolution may help small text but can’t recover detail missing from the source image. When dpi is set on get_pixmap(), it takes precedence over matrix.

    For poorly scanned documents, first preprocess them with OpenCV using binarization, deskewing, and denoising techniques.

    Performance best practices

    • Open once — Call pymupdf.open() once per document. Don’t reopen for each page.
    • Prefer "text" mode — Use page.get_text("text"), unless you need coordinates or font data.
    • Skip unnecessary rendering — page.get_pixmap() is slow, so only use it for OCR.
    • Handle invalid files — Use try/except for corrupted PDFs.
    • Parallelize batches — Document objects are independent, so use multiprocessing for bulk jobs.

    Nutrient DWS Processor API for Python

    Nutrient DWS Processor API is a cloud-based PDF processing API. Use an explicit OCR action for scanned input and request text or JSON content output.

    For new cloud extraction workflows, consider Nutrient Data Extraction API. Its Markdown extraction guide includes Python examples for /extraction/parse, which returns the Markdown string in output.markdown. For known fields, use schema-based key-value extraction.

    The Processor walkthrough below uses /build, with different instructions, response formats, and product credentials. Use its Processor signup to run these examples; use the Data Extraction signup for the linked extraction guides.

    Step 1: Sign up and get your API key

    Open Nutrient Processor API signup(opens in a new tab) and choose Google, GitHub, or email. Complete the verification steps for your chosen method. Then get your API key from the dashboard.

    The API pricing page lists $5 of usage each month on the free plan, with no credit card required. The signup screen lists watermarks and a 5 MB file limit for email accounts. Check the allowance and limits shown in your account before running a batch.

    Screenshot of Nutrient DWS Processor API dashboard showing API key management interface

    There are two ways to integrate Nutrient. Both use the same processing engine but differ in API interaction.

    Step 2: Choose your integration

    Choose between the Python client (nutrient-dws) or direct HTTP calls.

    Option A — The official Python client

    The official Python client (nutrient-dws) handles authentication, uploads, and response parsing. It’s good for automation scripts, backend services, or data pipelines. Additionally, it includes helper functions and error handling.

    Use this if you:

    • Want clean Python code
    • Want a client for document processing with explicit OCR instructions when needed
    • Want typed methods generated from the API reference
    Terminal window
    pip install nutrient-dws
    export NUTRIENT_API_KEY="your_api_key_here"

    Minimal extraction:

    This sample uses version 3.x of the Python client. Version 4.0.0 replaced these methods, so it doesn’t run with the current nutrient-dws package. For 4.0.0 examples, see the Python client guide.

    import asyncio, os
    from nutrient_dws import NutrientClient
    async def main():
    client = NutrientClient(api_key=os.getenv("NUTRIENT_API_KEY"))
    result = await client.extract_text("invoice.pdf")
    for page in result["data"]["pages"]:
    print(page.get("plainText", ""))
    asyncio.run(main())

    The client uploads invoice.pdf and extracts its text. For scanned input, configure an OCR action explicitly; installing the client doesn’t make every text-extraction request run OCR automatically.

    Option B: HTTP API

    The HTTP API works with any language. Send a request with your document, and you’ll get JSON back. Use this for non-Python projects or when you need direct control.

    Use this if you:

    • Use another language (Java, Go, C#, Node.js)
    • Need to integrate with existing REST systems
    • Want direct control over requests and responses

    Start with the Python client for prototyping. Use the HTTP API for multilanguage teams or existing service integration.

    Terminal window
    pip install requests
    export NUTRIENT_API_KEY="your_api_key_here"

    Request with an explicit English OCR action and JSON text output:

    import json
    import os
    import requests
    api_key = os.environ["NUTRIENT_API_KEY"]
    instructions = {
    "parts": [{"file": "document"}],
    "actions": [{"type": "ocr", "language": "english"}],
    "output": {"type": "json-content", "plainText": True, "structuredText": False},
    }
    with open("invoice.pdf", "rb") as document:
    response = requests.post(
    "https://api.nutrient.io/build",
    headers={"Authorization": f"Bearer {api_key}"},
    files={"document": document},
    data={"instructions": json.dumps(instructions)},
    timeout=(10, 180),
    )
    response.raise_for_status()
    with open("result.json", "w", encoding="utf-8") as output:
    json.dump(response.json(), output, ensure_ascii=False, indent=2)
    print("Saved to result.json")

    Feature comparison

    The table below compares PyMuPDF and Nutrient across key PDF processing capabilities, including native text extraction, scanned documents, tables, forms, and deployment responsibilities.

    FeaturePyMuPDFNutrient
    Native PDF textget_text("text") returns native textProcessor text extraction returns native text
    Scanned documentsIntegrated OCR methods require external TesseractProcessor OCR action must be requested
    Table extractionLine- and text-based strategies via find_tables()Evaluate Data Extraction API spatial output
    Form fields/KVPpage.widgets() reads PDF form fields; semantic KVP needs application logicData Extraction API offers schema-based fields
    Output formatPlain text, dict/JSON with coordinatesPlain text and structured JSON (order and hierarchy)
    Setup complexitypip install PyMuPDFAPI key and HTTP or SDK client
    Development effortDepends on extraction and deployment requirementsDepends on integration and review requirements
    MaintenanceApplication and local processing environmentApplication integration; provider manages service

    PyMuPDF strengths

    • Fast on native PDFs, low memory use
    • Runs locally, no network latency
    • Multiple output formats (text, words, blocks, coordinates)
    • Basic table detection with page.find_tables()
    • No external dependencies for text extraction
    • Full control over processing

    Where PyMuPDF fits

    Local document search — Extract text from native PDFs for indexing. Check reading order and missing characters before sending the text to a search system.

    Batch processing — Measure throughput, memory use, and operating cost on your expected volume. Local processing avoids an external API request, but capacity still depends on your hardware and configuration.

    Offline processing — Keep processing within your environment when documents cannot be uploaded to a cloud service. Install the required OCR resources if your input includes scans.

    Tables and forms — Use find_tables() for table rows and page.widgets() for PDF form fields. Check merged cells, page boundaries, and whether a document actually contains interactive fields.

    Checks to make before using the output

    • OCR recognition — Test Tesseract language configuration on representative scans. Compare recognized text with the source, particularly amounts, dates, and identifiers.
    • Table structure — Check row and column alignment. Joining tables across pages requires application logic.
    • Field meaning — Reading text or PDF form fields is different from identifying a named business field in a flat invoice or scan.
    • Failed inputs — Decide how to handle corrupted, password-protected, and unsupported documents without silently accepting incomplete results.
    • Regression testing — Rerun representative documents after changes to libraries, OCR resources, or hosted integrations.
    • Licensing — Review AGPL or commercial terms for your application and deployment.

    These checks define whether the output is usable. Using a hosted API does not remove the need to validate results or route exceptions for review.

    Where Nutrient Processor API fits

    Use the Processor examples when your application can upload documents to a hosted service and needs text extraction or an explicit OCR operation. This can support a search workflow that receives both native PDFs and scans without operating a local OCR engine.

    Check the returned text against the source before indexing it. Measure request failures, upload limits, and end-to-end latency alongside recognition quality. Nutrient manages the processing service; your application still owns uploads, error recovery, validation, and access to saved results.

    For named fields such as invoice numbers and totals, evaluate the separate Data Extraction API and its key-value extraction workflow. Use its own API key and request format rather than assuming the Processor text example returns schema-based fields.

    Cost and deployment considerations

    Compare both approaches on the same document set and expected processing volume:

    ResponsibilityPyMuPDFNutrient API
    ProcessingLocal compute, storage, and monitoringAPI usage for the selected product and operations
    LicensingAGPL obligations or commercial termsService plan and usage terms
    IntegrationApplication logic and local dependenciesUploads, credentials, response handling, and service limits
    Quality checksSource comparison, regression tests, and exception reviewSource comparison, regression tests, and exception review
    OperationsLocal capacity, updates, and recoveryApplication monitoring and recovery; provider operates the processing service

    Measure cost per usable result, including retries and manual review. Neither option has a universal break-even volume or guaranteed accuracy advantage.

    Choosing the right tool

    Start with the result your customer needs: searchable text, correctly aligned table rows, or named fields for a business process. Then check where the documents may be processed and what happens when extraction fails.

    Evaluate PyMuPDF if

    • Documents must remain in a local or offline environment
    • You need control over rendering, extraction settings, and coordinates
    • Its text, table, form, or Tesseract OCR output passes your source checks
    • The applicable license and local operating costs fit your requirements

    Evaluate Nutrient if

    • A hosted processing service fits your data-handling requirements
    • You need explicit OCR and text output through the Processor API
    • You need schema-based fields through the separate Data Extraction API
    • Its output passes your source checks and its usage limits, costs, and latency fit your application

    Test the workflow before changing tools

    Use representative native PDFs, scans, and mixed pages. Record missing text, reading-order errors, table alignment, and any values that require human correction. Include failed requests and documents the system cannot process.

    For an invoice workflow, check that the invoice number and amount match the source before passing them to an accounting system. For search, check that the text needed to find a document is present. These are different acceptance criteria, even when both workflows start with the same PDF.

    If your document mix or volume changes, rerun the comparison. A hybrid workflow is also possible, but only route files to an external service when your data-handling rules permit it.

    Conclusion

    PyMuPDF provides local text, table, form, and OCR methods. The Processor examples provide hosted text extraction and an explicit OCR action. Choose the approach whose output, deployment, and operating costs meet your workflow’s requirements.

    To run the Processor walkthrough, create a Processor API key(opens in a new tab). For schema-based fields or cloud parsing, try Nutrient Data Extraction API(opens in a new tab) and follow its Python Markdown example. Compare the results with your source documents before using them downstream.

    FAQ

    Yes. page.get_textpage_ocr() uses separately installed Tesseract resources. You can also render pages and call pytesseract as shown here. Nutrient Processor API provides a hosted alternative with an explicit OCR action.

    PyMuPDF offers AGPL and commercial licenses; review the applicable terms and include infrastructure and maintenance in your estimate. For Nutrient, estimate API costs for the required operations plus integration and review costs. Neither option has a universal break-even volume.

    Yes. Test a representative subset first, compare the returned output, and retain the existing path until the new one meets your requirements. A hybrid approach is possible if your data-handling rules permit cloud processing; a full migration is not required.

    Benchmark both on representative files. PyMuPDF throughput depends on local hardware and concurrency; API throughput also depends on network latency, service limits, and request configuration. Compare end-to-end latency and cost at your expected volume.

    Evaluate the separate Nutrient Data Extraction API for structured table output. The Processor text examples above do not demonstrate table reconstruction. Check row alignment, merged cells, and cross-page continuity against your source tables before using the results.

    Hulya Masharipov

    Hulya Masharipov

    Technical Writer

    Hulya is a frontend web developer and technical writer who enjoys creating responsive, scalable, and maintainable web experiences. She’s passionate about open source, web accessibility, cybersecurity privacy, and blockchain.

    Explore related topics

    Free to start Start extracting structured data