* * * GUIDES * * *

Convert a PDF to Markdown in Python.

LLM pipelines want markdown, not PDF soup. pypdf gives you raw text with the structure destroyed — and nothing at all from scans. This converts any PDF to real markdown, tables included.

01 / SETUP

pip install pennyocr
export PENNYOCR_API_KEY=pk_live_...

02 / CONVERT

from pennyocr import PennyOCR

result = PennyOCR().ocr("report.pdf")  # markdown is the default
print(result.text)

03 / KEEP PAGE BOUNDARIES (FOR CITATIONS)

page_results carries per-page markdown, so chunks can cite real page numbers:

for page in result.page_results:
    print(f"--- page {page.page} ---")
    print(page.text[:200])

04 / STRAIGHT INTO A RAG PIPELINE

Markdown chunks split along real structure. With LangChain:

from langchain_text_splitters import MarkdownHeaderTextSplitter

splitter = MarkdownHeaderTextSplitter([("#", "h1"), ("##", "h2")])
chunks = splitter.split_text(result.text)

05 / BIG PDFS BY URL, WITH A COST CAP

For documents that live at a URL, skip the download and cap your spend up front:

import os, requests

r = requests.post("https://api.pennyocr.com/v1/ocr/url",
    headers={"Authorization": f"Bearer {os.environ['PENNYOCR_API_KEY']}"},
    json={"url": "https://example.com/big.pdf", "pages": "1-50", "max_cost_usd": 0.05})
print(r.json()["text"][:500])

A 500-page PDF costs $0.375. Tables come out as HTML inside the markdown — the format LLMs parse most reliably.