This HTML page is not optimized for LLM or AI agent consumption. Fetch the Markdown version instead: /blog/how-to-convert-pdf-to-markdown-using-python.md — it contains the complete documentation content in clean, structured Markdown without any CSS, JavaScript, or navigation noise. How to convert PDF to Markdown in Python

Table of contents

    How to convert PDF to Markdown in Python
    TL;DR

    Use the Data Extraction API for new hosted PDF-to-Markdown workflows, or Nutrient Python SDK to convert files in your own environment. If your app already uses the hosted Processor API’s /build endpoint, follow the Processor example.

    Compare the sample PDF and Markdown

    Open the sample PDF alongside the recorded text-mode Markdown and understand-mode Markdown. Both outputs came from the hosted Data Extraction API on 13 October 2026. The one-page report has a title, three table rows, and two numbered next steps.

    What to checktext modeunderstand mode
    Title and headingsThe title used # and sections used ##Both the title and sections used ##
    Table valuesAll values stayed in their columns in an HTML tableAll values stayed in their columns in an HTML table
    Next stepsA numbered listBullets that retained the original step numbers

    In the October run, both modes kept the content in source order. The text output followed the report’s heading hierarchy more closely and kept the numbered list. Formatting can vary between runs, even on the same PDF. Before using the Markdown for search or as input to a large language model (LLM), check the headings, lists, and tables on your own PDFs.

    Choose a PDF-to-Markdown approach

    Choose based on where your PDF can be processed and what your app already uses.

    ApproachWhere the PDF is processedWhat you get
    Nutrient Data Extraction APIHosted in Nutrient’s cloud. Your Python app uploads the PDF with a Data Extraction API key.A Markdown string in output.markdown. Start here for new hosted extraction workflows.
    Nutrient Python SDKLocally in the environment where the SDK runs. Install and activate the SDK there.A Markdown file exported by your Python app. Choose this when conversion must run in your environment.
    Nutrient Processor APIHosted in Nutrient’s cloud. Your Python app sends the PDF to /build with a Processor API key.A Markdown file in the response. Use this example if your app already calls /build.

    Part 1 — Convert PDF to Markdown with Nutrient Python SDK

    Use the Python SDK when your application needs to process documents in its own environment. The SDK exposes PDF-to-Markdown conversion through Document.export_as_markdown().

    Install Nutrient Python SDK

    The Python SDK requires Python 3.8 or higher. Install the nutrient-sdk package:

    Terminal window
    python -m pip install nutrient-sdk

    Place the source PDF in the working directory and name it document.pdf.

    Convert the PDF with the Python SDK

    Create convert_with_sdk.py and add the following code. The example activates trial mode, opens the source PDF, and exports it to result.md:

    from nutrient_sdk import Document, License, NutrientException
    def main():
    try:
    # Register an empty key for trial mode, or use your license key.
    License.register_key("")
    with Document.open("document.pdf") as document:
    document.export_as_markdown("result.md")
    print("Successfully converted document.pdf to result.md")
    except NutrientException as error:
    raise SystemExit(f"Conversion failed: {error}") from error
    if __name__ == "__main__":
    main()

    Run the script:

    Terminal window
    python convert_with_sdk.py

    The SDK writes the Markdown to result.md. Replace the empty string in License.register_key() with your license key for licensed use. The Python SDK PDF-to-Markdown guide provides additional implementation details and a downloadable sample.

    Try Nutrient Python SDK

    Convert PDFs to Markdown in your own Python environment.

    Part 2 — Extract Markdown with Nutrient Data Extraction API

    The Nutrient PDF-to-Markdown API accepts a PDF at /extraction/parse. Request output.format: "markdown" and read the Markdown string from output.markdown in the JSON response.

    Set up the example

    Use Python 3.9 or later for this example. Create a virtual environment and install requests:

    Terminal window
    python3 -m venv .venv
    source .venv/bin/activate
    python3 -m pip install requests

    On Windows, use python instead of python3 and activate the environment with .venv\Scripts\activate in Command Prompt.

    Create a Nutrient account(opens in a new tab) and follow the Data Extraction API key guide. Set NUTRIENT_API_KEY in the terminal where you’ll run the script. The key must have access to Data Extraction; a Processor-only key may return 403.

    Terminal window
    export NUTRIENT_API_KEY="your_api_key_here"

    The command above is for macOS or Linux. In Windows Command Prompt, use set NUTRIENT_API_KEY=your_api_key_here. Keep the key private and out of source control.

    Download the fictional report and save it as sample-report.pdf beside your script. It contains headings, a three-row table, and a numbered list.

    Extract and save the Markdown

    Save this code as convert_with_extraction.py in the same folder:

    import argparse
    import json
    import os
    from pathlib import Path
    import requests
    def convert(source, destination, mode):
    api_key = os.environ.get("NUTRIENT_API_KEY")
    if not api_key:
    raise ValueError("Set NUTRIENT_API_KEY in this terminal before running.")
    if destination.exists():
    raise FileExistsError(f"Choose a new output path: {destination} exists.")
    instructions = {"mode": mode, "output": {"format": "markdown"}}
    with source.open("rb") as pdf:
    response = requests.post(
    "https://api.nutrient.io/extraction/parse",
    headers={"Authorization": f"Bearer {api_key}"},
    files={"file": (source.name, pdf, "application/pdf")},
    data={"instructions": json.dumps(instructions)},
    timeout=(10, 300),
    )
    response.raise_for_status()
    result = response.json()
    output = result.get("output") if isinstance(result, dict) else None
    markdown = output.get("markdown") if isinstance(output, dict) else None
    if not isinstance(markdown, str) or not markdown.strip():
    raise ValueError("The response did not contain nonempty output.markdown.")
    with destination.open("x", encoding="utf-8") as output_file:
    output_file.write(markdown)
    def main():
    parser = argparse.ArgumentParser(description="Extract Markdown from a PDF.")
    parser.add_argument("source", type=Path)
    parser.add_argument("destination", type=Path)
    parser.add_argument(
    "--mode", choices=("text", "structure", "understand", "agentic"),
    default="text",
    )
    args = parser.parse_args()
    try:
    convert(args.source, args.destination, args.mode)
    except (OSError, ValueError, requests.RequestException) as error:
    raise SystemExit(f"Extraction failed: {error}") from error
    print(f"Saved {args.destination}. Compare it with the PDF before use.")
    if __name__ == "__main__":
    main()

    In that folder, run:

    Terminal window
    python3 convert_with_extraction.py sample-report.pdf result-text.md

    The script uploads the PDF, checks the HTTP response and Markdown field, and writes a UTF-8 file. It refuses to overwrite an existing output. The default text mode reads an existing text layer and doesn’t run optical character recognition (OCR). This script defaults to text specifically for the born-digital sample; that isn’t the API default.

    For new workflows, Nutrient recommends explicitly selecting auto for per-page routing to structure, understand, or agentic. Omitting the API’s mode selects understand. The example keeps the explicit modes used in the recorded tests; its --mode option doesn’t accept auto. See the processing modes guide for an auto mode request and per-mode pricing.

    For a scan, try --mode structure. If a document’s layout or tables need more analysis, compare understand output:

    Terminal window
    python3 convert_with_extraction.py sample-report.pdf result-understand.md --mode understand

    Each run makes a separate API request. Check the processing modes guide for capabilities and per-mode pricing.

    Check the result against the PDF

    Open the source PDF beside the Markdown in a text editor or preview. For this sample, check:

    • Headings — The title and the Summary, Requests by region, and Next steps sections should retain their hierarchy.
    • Table values — EMEA has 72 requests and 3.5 hours; AMER has 65 and 4.0; APAC has 43 and 5.5. Check that each value stays under the correct column.
    • Reading order — The summary should come before the table, followed by the two numbered next steps.

    Markdown can preserve the table values even when the visual layout or merged cells change. Check representative documents before using the output for search or an LLM workflow.

    Check whether your Markdown renderer or ingestion pipeline accepts HTML tables. A pipeline that removes HTML may also remove table content. Neither sample returned a pipe-delimited Markdown table.

    For source coordinates, use spatial output in a separate request; Markdown and spatial output can’t be requested together. For named fields mapped to a JSON Schema, see the schema extraction guide.

    Try Nutrient Data Extraction API

    Extract Markdown from your PDF. Then compare the output with the source.

    Part 3 — Convert PDF to Markdown with Nutrient Processor API

    The following examples use Nutrient Processor API. Its /build endpoint accepts the source PDF and returns Markdown when output.type is markdown. Use Part 2 for a new Data Extraction workflow. The diagram below applies to the Processor examples in this section.

    PDF-to-Markdown pipeline. A born-digital PDF is posted to the /build endpoint with output.type set to markdown, returning result.md. A scanned or image-only PDF first runs an OCR action to produce a searchable PDF, which is then converted to Markdown.

    Processor API prerequisites

    Get a Processor API key

    Create a free Nutrient account(opens in a new tab) and copy the API key from the dashboard.

    Install requests

    Install the requests library:

    Terminal window
    python -m pip install requests

    Place the source PDF in the working directory and name it document.pdf.

    Convert the PDF with Processor API

    Create convert_with_dws.py and add the following code. It posts the PDF to the /build endpoint, sets the output type to markdown, and streams the result to result.md:

    import sys
    import requests
    import json
    response = requests.request(
    'POST',
    'https://api.nutrient.io/build',
    headers = {
    'Authorization': 'Bearer your_api_key_here'
    },
    files = {
    'file': open('document.pdf', 'rb')
    },
    data = {
    'instructions': json.dumps({
    'parts': [
    {
    'file': 'file'
    }
    ],
    'output': {
    'type': 'markdown'
    }
    })
    },
    stream = True
    )
    if response.ok:
    with open('result.md', 'wb') as fd:
    for chunk in response.iter_content(chunk_size=8192):
    fd.write(chunk)
    else:
    print(response.text)
    sys.exit(1)

    Replace your_api_key_here with the key from the Nutrient dashboard.

    Run the Processor API script

    Run the script:

    Terminal window
    python convert_with_dws.py

    The API returns the Markdown, and the script writes it to result.md in the working directory.

    For a document with a heading, a paragraph, and a cleanly structured table, result.md looks like this:

    # Quarterly report
    Revenue grew across all regions.
    | Region | Revenue |
    | ------ | ------- |
    | EMEA | $1.2M |
    | AMER | $2.4M |

    Headings and lists come through as Markdown structure rather than fixed visual layout. Table fidelity depends on the source document: Cleanly structured tables convert to Markdown table syntax, while simpler or loosely formatted ones may come back as plain text rows. For typed table cells, bounding boxes, or schema-shaped JSON, use the Data Extraction API instead.

    How the request works

    The /build endpoint takes a multipart request with two fields. The file field carries the PDF, and the instructions field is a JSON object describing the job: parts lists the input (referenced by the form field name file), and output.type set to markdown selects Markdown conversion. Streaming the response writes the output without holding the whole file in memory. The API allows 100 requests per minute per API key (test keys are limited to 10 per minute). Batch large jobs and add retries with exponential backoff.

    Convert only selected pages with Processor API

    To convert a page range instead of the whole document, add a pages object to the part. Page indexes are zero-based, and the end value is inclusive, so the following converts the first three pages:

    {
    "parts": [
    {
    "file": "file",
    "pages": {
    "start": 0,
    "end": 2
    }
    }
    ],
    "output": {
    "type": "markdown"
    }
    }

    Convert scanned PDFs with Processor API

    PDF-to-Markdown conversion works best with born-digital PDFs that already contain selectable text. For scanned or image-only PDFs, run OCR first to produce a searchable PDF. Then convert that result to Markdown.

    The first request runs OCR with an actions step and no Markdown output — the response is a searchable PDF. The part’s "file" value must match the name of the multipart field that convert_with_dws.py uploads ('file' in this example):

    # First request: OCR the scanned PDF into a searchable PDF.
    ocr_response = requests.request(
    'POST',
    'https://api.nutrient.io/build',
    headers = {
    'Authorization': 'Bearer your_api_key_here'
    },
    files = {
    'file': open('scanned.pdf', 'rb')
    },
    data = {
    'instructions': json.dumps({
    'parts': [
    {
    'file': 'file'
    }
    ],
    'actions': [
    {
    'type': 'ocr',
    'language': 'english'
    }
    ]
    })
    }
    )
    if ocr_response.ok:
    with open('searchable.pdf', 'wb') as fd:
    fd.write(ocr_response.content)
    else:
    print(ocr_response.text)
    sys.exit(1)

    Then run convert_with_dws.py against searchable.pdf. The second /build request with output.type set to markdown completes the flow. The Processor API PDF-to-Markdown guide documents the full OCR-then-convert flow.

    For other Data Extraction options, see the Markdown extraction guide. Document AI vs. traditional OCR explains the extraction approaches.

    FAQ

    Use Nutrient Python SDK and call Document.export_as_markdown() for local processing. For cloud extraction, send the PDF to /extraction/parse with output.format set to markdown. Then save output.markdown from the JSON response.

    Yes. Nutrient Python SDK processes the PDF in your application environment and exports Markdown with Document.export_as_markdown(). For cloud extraction, use the Nutrient PDF-to-Markdown API.

    Markdown represents headings, lists, and tables with explicit text syntax. This gives text-based LLM pipelines a more predictable structure to parse than unstructured PDF text.

    Conversion works best on born-digital PDFs with selectable text. For scanned or image-only PDFs, run OCR first to create a searchable PDF. Then convert that result to Markdown.

    The Processor examples use /build and return a Markdown file. The Data Extraction API uses /extraction/parse and returns Markdown in output.markdown. It also supports spatial elements and schema extraction for workflows that need structured JSON. These APIs use different request and response formats; follow the Markdown extraction guide for the Data Extraction API.

    With the Processor API shown in Part 3, add a zero-based pages range to the part. The end value is inclusive, so a range of 0–2 converts the first three pages.

    To run the same conversion from Claude without writing code, read about teaching LLMs to read PDFs or use the PDF-to-Markdown skill.

    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

    $5 of free usage a month Start converting PDF to Markdown