DEV Community

Yehor Kramskoi
Yehor Kramskoi

Posted on

From PDF links to RAG-ready Markdown chunks in Python (arXiv example)

Most RAG pipelines break at the first step: turning PDFs into text that still has structure. Plain text extraction loses headings, merges table cells and drops the page numbers you need for citations. Then you chunk that soup and wonder why retrieval is bad.

This post walks through a small pipeline that keeps the structure:

  1. Resolve a PDF URL (arXiv /abs/ pages, direct links).
  2. Convert pages to Markdown, keeping headings, lists and tables.
  3. Split into overlapping chunks with page markers.
  4. Estimate tokens before you pay for embeddings.

Step 1 and 2: PDF to Markdown locally

pymupdf4llm does a good job of keeping layout as Markdown. Note that it's built on PyMuPDF, which is AGPL-licensed, so check that fits your project.

# pip install httpx pymupdf4llm
import httpx, pymupdf, pymupdf4llm

def resolve(url: str) -> str:
    # arXiv abstract pages -> direct PDF links
    return url.replace("arxiv.org/abs/", "arxiv.org/pdf/")

def pdf_to_markdown(url: str, max_pages: int = 3) -> str:
    data = httpx.get(resolve(url), follow_redirects=True, timeout=60).content
    doc = pymupdf.open(stream=data, filetype="pdf")
    pages = list(range(min(max_pages, doc.page_count)))
    parts = []
    for i in pages:
        md = pymupdf4llm.to_markdown(doc, pages=[i])
        parts.append(f"--- Page {i + 1} ---\n\n{md.strip()}")
    return "\n\n".join(parts)

markdown = pdf_to_markdown("https://arxiv.org/abs/1706.03762")
print(markdown[:500])
Enter fullscreen mode Exit fullscreen mode

The page markers (--- Page 1 ---) cost almost nothing in tokens and let you cite "page 3" in answers later.

Step 3: chunk on paragraph boundaries with overlap

Fixed-size character windows cut sentences in half. Splitting on blank lines and packing paragraphs up to a size limit keeps chunks readable. The overlap carries the end of one chunk into the next, so a fact split across the boundary is still retrievable.

def chunk_markdown(md: str, size: int = 1200, overlap: int = 150) -> list[str]:
    paragraphs = [p.strip() for p in md.split("\n\n") if p.strip()]
    chunks, current = [], ""
    for p in paragraphs:
        if current and len(current) + len(p) + 2 > size:
            chunks.append(current)
            current = current[-overlap:] + "\n\n" + p  # carry the tail over
        else:
            current = f"{current}\n\n{p}" if current else p
    if current:
        chunks.append(current)
    return chunks

chunks = chunk_markdown(markdown)
print(len(chunks), [len(c) for c in chunks][:5])
Enter fullscreen mode Exit fullscreen mode

Step 4: estimate tokens before embedding

For budgeting, about 4 characters per token is close enough for English:

tokens = sum(len(c) for c in chunks) // 4
print(f"{len(chunks)} chunks, ~{tokens} tokens")
Enter fullscreen mode Exit fullscreen mode

Use a real tokenizer (for example tiktoken for OpenAI models) if you need exact numbers.

Doing it for many PDFs without running it yourself

The local version is great for one file. For batches of URLs (papers, filings, manuals), you also need retries, size limits, Google Drive links and parallel downloads, and you don't want PyMuPDF's AGPL in your own codebase. I wrapped the same pipeline as an Apify Actor, PDF to Markdown for RAG & LLM. Disclosure: I built it. It costs $0.002 per page plus $0.02 per run, and it returns the Markdown, chunks, word count and token estimate for each document.

# pip install apify-client
from apify_client import ApifyClient

client = ApifyClient("<YOUR_APIFY_TOKEN>")
run = client.actor("sequined_lacework/pdf-to-markdown-rag").call(run_input={
    "urls": ["https://arxiv.org/abs/1706.03762"],
    "maxPagesPerDoc": 3,
    "chunkSize": 1200,
    "chunkOverlap": 150,
})
for doc in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(doc["title"], doc["processed_pages"], "/", doc["total_pages"], "pages,",
          len(doc["chunks"]), "chunks, ~", doc["estimated_tokens"], "tokens")
Enter fullscreen mode Exit fullscreen mode

Real output for the "Attention Is All You Need" paper, first 3 pages, in 18 seconds:

{
  "source_url": "https://arxiv.org/abs/1706.03762",
  "resolved_url": "https://arxiv.org/pdf/1706.03762",
  "title": "Attention Is All You Need",
  "total_pages": 15,
  "processed_pages": 3,
  "word_count": 1412,
  "estimated_tokens": 2313,
  "status": "ok"
}
Enter fullscreen mode Exit fullscreen mode

That run produced 11 chunks of 780 to 1,170 characters. Headings stay as Markdown (## **Abstract**), and every page starts with a --- Page N --- marker.

Feeding the chunks to your vector store

Whatever store you use, keep the page number as metadata so answers can cite it:

import re

def page_of(chunk: str, last_page: int) -> int:
    m = re.findall(r"--- Page (\d+) ---", chunk)
    return int(m[-1]) if m else last_page

records, page = [], 1
for i, chunk in enumerate(chunks):
    page = page_of(chunk, page)
    records.append({"id": f"1706.03762-{i}", "text": chunk, "metadata": {"page": page}})
# then: your_vector_store.upsert(records)  (Chroma, Qdrant, pgvector, Pinecone...)
Enter fullscreen mode Exit fullscreen mode

If you use Claude Desktop or Cursor, the Actor also works as an MCP tool, so the assistant can fetch and chunk a PDF on request: https://mcp.apify.com/?actors=sequined_lacework/pdf-to-markdown-rag.

Top comments (0)