Why PDFs Are the Hardest Part of RAG (And How to Parse Them Better)

Posted on Mon 23 November 2026 in Tutorial

The Moment My RAG App Fell Apart

The RAG API we built earlier worked beautifully, as long as I fed it clean text. Then I did what every user eventually does: I uploaded a real PDF. A quarterly report, 40 pages, with columns, tables, charts, and a header on every page.

The answers were strange. One reply quoted a sentence that stopped halfway and continued with text from a different column. Another confidently cited "Confidential - Internal Use Only" as if it were a key finding, because that footer appeared on every page. A question about a number in a table returned nonsense, because the table had been flattened into a stream of unrelated values.

The LLM wasn't the problem. The retrieval wasn't the problem. The text going into the pipeline was already broken. In RAG, parsing happens before chunking, before embeddings, before everything. If the text is wrong at the start, nothing downstream can fix it. Garbage in, garbage out.

This post explains why PDFs are so hard, and gives you a practical process for parsing them well.

Why PDFs Are So Difficult

The root cause is what a PDF actually is. It's tempting to think of a PDF as a document with paragraphs, headings, and tables. It isn't. A PDF is a page description format, designed to make a page look identical on every screen and printer. Internally, it mostly stores instructions like "draw this character at these coordinates, in this font."

Think of it as a photograph of a document, made of individually positioned letters. The file knows where each character sits on the page. It often doesn't know:

  • Which characters form a word or a paragraph
  • What the reading order is
  • Which text is a heading, a footer, or a caption
  • Where a table begins, or which cell a number belongs to

Your parser has to reconstruct all of that by guessing from positions. Sometimes it guesses well. Often, it doesn't.

Not All PDFs Are the Same

Before choosing tools, figure out what kind of PDF you're dealing with:

  • Born-digital PDFs (exported from Word, LaTeX, web pages): have a real text layer, so extraction works, but layout can still be tricky
  • Scanned PDFs: are just images of pages, with no text at all, so you need OCR (optical character recognition)
  • Hybrid PDFs: scans that were run through OCR once, so they contain a hidden text layer of varying quality
  • Slide decks exported to PDF: short fragments, odd reading order, and information in diagrams
  • Forms and invoices: fields and tables where position carries the meaning
  • Academic papers and reports: multiple columns, footnotes, equations, figures

One collection often contains all of these, which is why a single "extract text" call rarely works for everyone.

The Usual Ways PDF Parsing Goes Wrong

Knowing the failure modes helps you spot them quickly:

  • Scrambled reading order. In a two-column page, the parser reads straight across both columns, mixing sentences from each.
  • Repeated headers, footers, and page numbers in the middle of the text, polluting every chunk
  • Broken lines and hyphenation. Words split like informa- / tion, and sentences chopped at the end of each visual line.
  • Flattened tables. Rows and columns collapse into a long list of values, losing which number belongs to which label.
  • Multi-page and merged-cell tables that parsers split or misalign
  • Charts and images. The most important data may exist only as a picture.
  • Scanned pages that return nothing, or OCR that confuses similar characters (like 0 and O, or l and 1)
  • Footnotes and sidebars spliced into the main text
  • Weird characters, such as (cid:123) or the replacement character �, caused by fonts without proper text mapping
  • Equations and code blocks turned into garbled symbols
  • Non-English text. Some PDFs, including many Tamil documents, use legacy font encodings. Copying text from them can produce gibberish even though it looks perfect on screen. OCR on the rendered page often works better in these cases.
  • Hidden or invisible text, which brings a security angle we'll come back to

Step 1: Look Before You Embed

The single most useful habit: read what your parser actually produced, page by page, before sending anything to an embedding model. Most pipeline bugs are visible right there.

Start with a quick diagnostic that flags suspicious pages, such as pages with almost no text (likely scans):

import pymupdf   # PyMuPDF (older versions are imported as: import fitz)

def diagnose_pdf(path: str) -> None:
    doc = pymupdf.open(path)
    for page_number, page in enumerate(doc, start=1):
        text = page.get_text()
        n_chars = len(text.strip())
        n_images = len(page.get_images())
        note = "  <- possibly scanned, may need OCR" if n_chars < 50 and n_images > 0 else ""
        print(f"page {page_number:3}: {n_chars:6} chars, {n_images} images{note}")

diagnose_pdf("report.pdf")

Also open a few pages and read the extracted text next to the original page. Five minutes of this will teach you more than any benchmark.

A quick licensing note: PyMuPDF and its companion tools are dual-licensed (an open-source license with strong requirements, or a commercial license). Check the terms before using them in a commercial product. Alternatives with different licenses exist, so it's worth reading the license of every parser you adopt.

Step 2: Choose a Parser That Matches Your Documents

Parsing tools fall into a few families:

Basic text extractors (such as pypdf, pdfminer.six, pypdfium2, plain PyMuPDF). Fast and simple. They give you characters and rough lines, with little understanding of layout. Fine for clean, single-column, born-digital documents.

Layout- and structure-aware converters (such as PyMuPDF4LLM, Docling, Marker, Unstructured, MinerU). They try to recover headings, lists, reading order, and tables, often outputting Markdown. They're heavier, and some use machine learning models that run best with a GPU.

Table specialists (such as pdfplumber and Camelot). Strong for tables with visible lines and a clear grid.

OCR engines (such as Tesseract, PaddleOCR, EasyOCR). Needed for scans. Check language support carefully, especially for Tamil and other Indian languages.

Managed document-AI services (such as LlamaParse, Mistral OCR, Azure Document Intelligence, AWS Textract, Google Document AI). Often the highest quality for messy, complex documents, but they cost money per page, and your documents leave your environment, which matters for confidential data.

Vision-language models. You render each page as an image and ask a multimodal LLM to transcribe it into Markdown. This is flexible and can handle charts, handwriting, and odd layouts. But it costs more, it's slower, and it can invent text or numbers that aren't on the page, so you must validate the output on anything important.

A Warning About Benchmarks

You'll find many "best PDF parser for RAG" comparisons online. Use them as starting points only, for three reasons:

  • Results swing wildly by document type. Published benchmarks show the same parser doing very well on one kind of document (like legal text) and much worse on another (like invoices).
  • Many comparisons are written by vendors who sell one of the products being compared, and some openly say so.
  • A parsing score isn't a RAG score. Converting a document well doesn't automatically mean your system answers questions well. That has to be measured separately.

The only comparison that really matters is the one run on your documents and your questions.

Step 3: Convert to Markdown, Not Flat Text

Flat text throws away structure. Markdown preserves the important parts: headings, lists, and tables. Preserved structure lets you chunk by section later, which gives better retrieval than slicing every 800 characters.

Two examples of structure-aware conversion:

# Option A: PyMuPDF4LLM (fast, good for born-digital PDFs)
import pymupdf4llm

markdown_text = pymupdf4llm.to_markdown("report.pdf")
# Option B: Docling (stronger layout and table understanding, heavier)
from docling.document_converter import DocumentConverter

converter = DocumentConverter()
result = converter.convert("report.pdf")
markdown_text = result.document.export_to_markdown()

Run both on a few of your real documents, and compare the output with the original pages. Which one handles your two-column layouts and tables better?

Step 4: Clean the Text

Even good parsers leave junk behind. A short cleaning pass pays off a lot, especially for repeated headers and footers, which otherwise end up in every chunk and quietly distort retrieval.

import re
from collections import Counter

def normalize_key(line: str) -> str:
    # Treat "Page 3 of 40" and "Page 4 of 40" as the same repeated line
    return re.sub(r"\d+", "#", line.strip())


def remove_repeated_lines(pages: list[str], min_fraction: float = 0.5) -> list[str]:
    """Drop headers, footers, and page numbers that repeat across many pages."""
    if len(pages) < 3:
        return pages

    counts = Counter()
    for page in pages:
        keys = {normalize_key(line) for line in page.splitlines() if line.strip()}
        counts.update(keys)

    cutoff = max(2, int(len(pages) * min_fraction))
    repeated = {key for key, count in counts.items() if count >= cutoff}

    cleaned = []
    for page in pages:
        kept = [line for line in page.splitlines() if normalize_key(line) not in repeated]
        cleaned.append("\n".join(kept))
    return cleaned


def fix_hyphenation(text: str) -> str:
    # Join words split across lines: "informa-\ntion" -> "information"
    return re.sub(r"(\w)-\n(\w)", r"\1\2", text)

Be careful with automatic cleaning. fix_hyphenation will also merge genuine hyphenated words that happen to break at a line end ("well-\nknown" becomes "wellknown"), and the repeated-line remover can delete a legitimate line that appears on many pages. Always spot-check the cleaned output, and keep the raw parse around so you can compare.

Step 5: Treat Tables as First-Class Citizens

Tables are where many RAG systems quietly fail, because the answer lives in the relationship between a row label and a column header, and flattened text destroys that relationship.

A few approaches:

  • Extract tables separately with a table-aware tool:
import pdfplumber

with pdfplumber.open("report.pdf") as pdf:
    for page_number, page in enumerate(pdf.pages, start=1):
        for table in page.extract_tables():
            print(f"Table on page {page_number}:")
            for row in table:
                print(row)
  • Keep each table intact as its own chunk, in Markdown or CSV form, with its caption and the surrounding heading. Never let a chunk boundary cut a table in half.
  • Repeat the header row when you must split a large table, so every piece still says which column is which.
  • Consider turning rows into sentences for embedding ("Q3 2026 revenue: 4.2 million rupees"), since embeddings represent prose better than grids of numbers.
  • Preserve units, footnotes, and captions. "4.2" means nothing without "million rupees" and the year.
  • Check multi-page tables carefully, since many parsers split them.

Step 6: Handle Scanned Pages With OCR

If your diagnostic shows pages with images but almost no text, those pages need OCR. The usual process is to render each page to an image at a reasonable resolution, then run OCR on it:

import io
import pymupdf
import pytesseract          # also requires the Tesseract program itself to be installed
from PIL import Image

def ocr_page(page, lang: str = "eng") -> str:
    pixmap = page.get_pixmap(dpi=300)               # higher DPI usually helps OCR
    image = Image.open(io.BytesIO(pixmap.tobytes("png")))
    return pytesseract.image_to_string(image, lang=lang)

doc = pymupdf.open("scanned.pdf")
text = ocr_page(doc[0], lang="eng")      # for Tamil, use lang="tam" if the Tamil data is installed

Some practical notes:

  • Install the right language data. For Tamil, the language pack must be installed, and quality varies with print quality and font.
  • OCR makes mistakes, especially on low-quality scans, small text, and unusual fonts. Always spot-check.
  • Clean scans help. Straightening skewed pages and improving contrast can noticeably improve results.
  • Keep the page image or a reference to it, so users (and you) can verify answers against the original.
  • Managed OCR services and vision models may do better on difficult scans, at a cost.

Step 7: Detect Bad Extraction Automatically

You can't read every page of every document, so add automatic checks that flag suspicious output, and use a fallback parser (such as OCR) for those pages:

import unicodedata

def looks_garbled(text: str) -> bool:
    if not text.strip():
        return True                                   # nothing extracted at all
    if "\ufffd" in text or "(cid:" in text:
        return True                                   # classic encoding failures

    # Count letters, combining marks (important for Tamil and other Indic scripts),
    # and whitespace as "normal text"
    normal = sum(
        unicodedata.category(ch)[0] in ("L", "M") or ch.isspace()
        for ch in text
    )
    return normal / len(text) < 0.7                   # rough threshold, tune on your data

Two honest caveats. First, this is a rough heuristic, and number-heavy tables may trigger false alarms, so tune the threshold on your own documents. Second, text from legacy Tamil fonts can look like perfectly valid Latin letters while being meaningless, so the heuristic won't catch it. For Tamil and other Indian-language documents, test explicitly by copying a paragraph from the PDF and reading it, or compare against OCR output.

A common production pattern is a fallback chain: try a fast parser first, check the quality, and only send the difficult pages to a slower, more capable one.

Step 8: Chunk by Structure and Keep Metadata

Once you have clean Markdown, chunk along the document's own structure instead of by raw character counts:

  • Split at headings and sections so each chunk covers one topic
  • Keep tables, lists, and code blocks whole
  • Use overlap sparingly, as in the earlier chunk overlap post, mostly for long continuous prose
  • Attach metadata to every chunk: document name, page number, section title, and content type (text, table, figure)
  • Prefix each chunk with its context before embedding, such as "Document: Q3 Report > Section: Revenue by Region". This gives each chunk the context it lost when it was separated from its heading.

Here's how the ingestion step from the RAG API post changes to carry that metadata:

collection.upsert(
    ids=[f"{doc_id}-p{page}-{i}" for i in range(len(chunks))],
    documents=[f"Document: {doc_title} > {section}\n{chunk}" for chunk in chunks],
    metadatas=[
        {"source": doc_id, "page": page, "section": section, "type": "text"}
        for _ in chunks
    ],
)

Page numbers also make citations possible. Instead of "according to the documents," your answer can say "see page 14 of the Q3 report," which makes it far easier to verify.

Step 9: Don't Ignore Charts and Images

If key information lives in charts or diagrams, plain text extraction will miss it completely. Options include:

  • Keep captions and surrounding text, which often summarize the point of the figure
  • Describe figures with a vision model and index the description, while treating the description as unverified, since models can misread charts
  • Use the underlying data when it's available (such as an accompanying spreadsheet) instead of reading numbers off a picture
  • Link back to the page image, so a human can check

For high-stakes numbers, always prefer the source data over a model's reading of a graphic.

Step 10: Measure Parsing Quality

Don't guess whether a parser change helped. Treat it like any other change, as in the earlier eval post:

  1. Spot-check pages. Pick about ten pages from different documents, including your hardest ones (multi-column, tables, scans), and compare the output against the original.
  2. Build a small question set with known answers that deliberately lives in awkward places: inside tables, in footnotes, on scanned pages, in the second column.
  3. Hold everything else constant (chunking, embeddings, top_k) and change only the parser.
  4. Measure retrieval first: did the right chunk come back? Then measure answer quality.
  5. Track cost and speed, since a parser that's slightly better but ten times slower or pricier may not be worth it.
  6. Check failures by category, such as tables, scans, or columns, since each has a different fix.

Security and Privacy: PDFs Are Untrusted Input

PDFs bring a few risks that are easy to overlook:

  • Hidden text and prompt injection. A PDF can contain text that's invisible to a human (white text on white, tiny fonts, metadata, or text outside the visible page), but a parser will happily extract it. That text can contain instructions aimed at your model, which is exactly the indirect prompt injection scenario from the earlier post. Treat all extracted text as untrusted, and consider inspecting or filtering suspicious content.
  • Confidential data. Managed parsing services and vision APIs send your documents to a third party. Check the provider's data handling terms before using them on sensitive files, as discussed in the post on what happens to your data.
  • Malicious or malformed files. Parsers handle complex file formats, and bugs exist. Process uploaded files with size limits and timeouts, ideally in an isolated environment.
  • Access control. If different users can see different documents, store permissions as metadata and filter retrieval by them in code.

Production Tips

  • Parse once, cache the result, keyed by a hash of the file, so you never re-parse an unchanged document
  • Ingest in the background, since large PDFs can take minutes, rather than inside a web request
  • Log parsing stats (characters per page, tables found, OCR pages, failures), following the observability post, so you notice when a new document type breaks things
  • Handle failures per page, so one corrupt page doesn't discard the whole document
  • Version your parser and settings, and re-ingest when you upgrade them, since the output changes
  • Re-embed after changes, as parsed text affects every downstream vector

Quick Checklist

  • Remember that parsing comes first, and bad text can't be fixed downstream
  • Identify your PDF types: born-digital, scanned, hybrid, tables, columns
  • Read the parser's output yourself before embedding anything
  • Choose tools based on your own documents, not on leaderboards
  • Check licenses, especially for commercial use
  • Convert to Markdown to preserve headings and tables
  • Remove repeated headers and footers, and fix hyphenation, then spot-check
  • Treat tables as separate, intact chunks with headers and captions
  • Use OCR for scanned pages, with the right language data
  • Detect garbled output and use a fallback parser
  • Chunk by structure, with page, section, and type metadata
  • Treat extracted text as untrusted, and watch for hidden content
  • Measure parsing changes with real questions, not impressions

Closing Thought

It's easy to blame the model when a RAG app gives bad answers, but with PDFs the damage is usually done long before the model sees anything. The file looks perfect to a human and arrives as a scrambled pile of positioned characters. The good news is that this is the most fixable layer in the whole pipeline: read the output, pick a parser that fits your documents, clean it, keep the structure, and measure the results. A day spent on parsing will often improve your answers more than a week spent tweaking prompts or swapping models.