RAG — Document Intelligence
PDF Parsing Pipelines for RAG Systems
Direct answer
A reliable PDF pipeline for RAG classifies each file (text-based or scanned), extracts it with a layout-aware parser that preserves reading order, headings and tables, converts the result to structured Markdown, chunks along that structure with the document and section title attached, and stores page numbers for citations. Most RAG accuracy problems with PDFs trace back to skipping one of those steps — especially table handling.
PDFs were designed to look right on paper, not to be read by machines. Inside, a page is a set of positioned glyphs: there is no reliable notion of a paragraph, a column or a table row. Naive text extraction therefore produces merged columns, numbers separated from their labels, and page headers repeated through the text — and a RAG system will answer confidently from all of it. This guide lays out a pipeline that handles real-world PDFs, the tools for each step, and how to check the output before it reaches your index.
Key facts, with sources
- Docling, an MIT-licensed project started by IBM Research Zurich and now hosted by the LF AI & Data Foundation, parses PDFs with layout, reading-order and table-structure analysis and exports Markdown, HTML or JSON. (Docling on GitHub)
- PyMuPDF4LLM converts PDFs to Markdown for LLM and RAG workflows, with layout analysis that runs without a GPU. (PyMuPDF docs)
- 'Not extracted' and 'wrong format' are two of the seven RAG failure points identified across three production case studies — both are often parsing problems. (Barnett et al., arXiv 2024)
Step 1: classify every PDF before parsing
Not all PDFs are the same problem. A text-based PDF (exported from Word or a web page) contains real characters you can extract. A scanned PDF is a picture of a page and contains no text until OCR runs. Many real collections mix both — and some files mix both on different pages.
Check each page: if it yields little or no extractable text but contains a full-page image, route it to OCR. Doing this per page rather than per file avoids running slow OCR on 200 clean pages because one appendix was scanned.
import pymupdf # PyMuPDF
def pages_needing_ocr(path: str, min_chars: int = 50) -> list[int]:
doc = pymupdf.open(path)
needs_ocr = []
for page in doc:
text = page.get_text().strip()
if len(text) < min_chars and page.get_images():
needs_ocr.append(page.number)
return needs_ocrStep 2: pick a parser that understands layout
Plain text extraction reads glyphs in storage order, which is not always reading order. Layout-aware parsers detect columns, headings, lists, tables and figures, and output structure you can chunk on. The right tool depends on your documents, hosting constraints and licence requirements — test two candidates on your own worst ten PDFs before committing.
| Tool type | Examples | Strengths | Watch out for |
|---|---|---|---|
| Fast text extractors | pypdf, pdfminer.six | Simple, lightweight, fine for clean single-column text | Columns, tables and reading order |
| Layout-aware open source | Docling, PyMuPDF4LLM, Unstructured | Headings, tables, Markdown output, runs locally | Slower; tune on your documents; check each licence (PyMuPDF is AGPL or commercial) |
| Cloud document AI | Azure Document Intelligence, AWS Textract, Google Document AI | Strong OCR, forms and tables at scale | Per-page cost, data leaves your infrastructure |
| Vision LLM parsing | Multimodal LLM reading page images | Handles messy layouts and charts | Cost per page, possible hallucinated text — verify numbers |
Step 3: handle tables explicitly
Tables are where PDF parsing most often fails silently. Flattened into text, a pricing table becomes a stream of numbers with no row or column labels, and the model will happily attach the wrong price to the wrong plan.
Keep tables as tables. Convert each one to Markdown (or HTML for merged cells), keep its caption and the heading above it, and store it as its own chunk rather than splitting rows across chunks. For very large tables, repeat the header row in each chunk. Optionally add a one-sentence summary of the table to help vector search match questions phrased in words rather than numbers.
Step 4: convert to Markdown and clean it
Markdown is a practical intermediate format: headings become # markers you can split on, tables keep their structure, and LLMs read it well. A layout-aware parser can produce it directly.
Then clean. Remove running headers and footers (the same line appearing on most pages), page numbers inside the text, and hyphenation at line breaks. Keep a mapping from each block to its page number — you'll need it for citations like 'Policy handbook, p. 14', which build user trust far more than an unlabelled answer.
from docling.document_converter import DocumentConverter
converter = DocumentConverter() # create once; models load on first use
def pdf_to_markdown(path: str) -> str:
result = converter.convert(path)
return result.document.export_to_markdown()
md = pdf_to_markdown("employee-handbook.pdf")
print(md[:500])Step 5: chunk along the document's structure
With clean Markdown, chunk on headings first, then on paragraphs or list items within long sections, aiming for a few hundred tokens per chunk with a small overlap. Never split a table row or a numbered procedure step across chunks.
Attach metadata to every chunk: source file, document title, section path, page range, document date or version, and access group. Prepend the title and section path to the chunk text itself before embedding, so a chunk reading 'Coverage ends after 90 days' still carries the context of which policy it belongs to.
import re
def chunk_markdown(md: str, doc_title: str, max_chars: int = 2000) -> list[dict]:
chunks, path = [], []
for block in re.split(r"\n(?=#{1,4} )", md):
heading = re.match(r"(#{1,4}) (.+)", block)
if heading:
level = len(heading.group(1))
path = path[: level - 1] + [heading.group(2).strip()]
prefix = " > ".join([doc_title, *path])
# Long sections fall back to paragraph splits; use a token counter if your limits are tight
parts = [block] if len(block) <= max_chars else block.split("\n\n")
for part in parts:
if part.strip():
chunks.append({"text": f"{prefix}\n\n{part.strip()}", "section": path[:]})
return chunksStep 6: check quality before indexing
Parsing errors are invisible once embedded, so check before indexing. Automate the cheap checks and sample the rest by hand: compare extracted character counts against page counts to catch empty or OCR-failed pages, flag chunks with unusually high ratios of digits or broken characters, verify every table chunk has a header row, and open twenty random chunks from your most important documents and read them.
Finally, test end to end with questions whose answers sit inside tables and multi-column pages. If those pass, most of the rest will.
| Check | Catches | Automate? |
|---|---|---|
| Chars per page below threshold | Missed OCR, image-only pages | Yes |
| Repeated identical lines across pages | Headers/footers leaking into chunks | Yes |
| Table chunks without header row | Broken table extraction | Yes |
| Garbled-character ratio | Encoding / font-mapping problems | Yes |
| Manual read of 20 chunks | Reading-order and column merges | No — do it per new document type |
| Table-answer questions in the eval set | End-to-end table failures | Yes, in CI |
When to hire senior help
Document pipelines fail in the long tail of formats, so senior help is most valuable after the prototype, when accuracy on real production documents must go from roughly 80% to reliably usable through validation rules, fallbacks, and human-in-the-loop design. Experienced practitioners also benchmark parsers on your actual documents before committing, which regularly changes tool choice and prevents costly re-processing later. If your stack includes React Native + Python + AI, a senior engineer who owns the full product beats coordinating multiple juniors.
Bottom line
Dhairya Senjaliya ships RAG — Document Intelligence projects worldwide — book a scoping call to discuss your specific situation.
Common pitfalls to avoid
- ✕Running scanned PDFs through a plain text extractor so tables collapse into word soup before they ever reach the retriever.
- ✕Evaluating a parser on clean digital PDFs when production traffic is scans, handwriting, and stamps, where published accuracy drops hardest.
- ✕Chunking by fixed token count straight across page and table boundaries, splitting table headers from the rows they describe.
- ✕Choosing an agentic parsing pipeline that costs 8x more per page for documents where a commodity OCR model at $1 to $4 per thousand pages would score the same.
Frequently asked questions
What is the best PDF parser for RAG?
There isn't one best tool for every collection. For locally hosted pipelines, layout-aware parsers such as Docling or PyMuPDF4LLM handle headings and tables far better than plain text extraction; cloud document AI services are strong for scanned forms at scale. Test two options on your ten hardest PDFs and compare the extracted tables.
How do I extract tables from PDFs for RAG?
Use a parser with table-structure detection, convert each table to Markdown or HTML, keep its caption and heading, and store it as its own chunk — repeating the header row if you must split it. Don't let tables be flattened into plain text.
Do I need OCR for my PDFs?
Only for pages without extractable text — scans, photos and some image-based exports. Detect them per page (little text plus a full-page image) and send just those pages through OCR to keep processing fast.
Should I convert PDFs to Markdown before chunking?
Usually yes. Markdown keeps headings and tables explicit, which makes structure-aware chunking simple, and LLMs read it well. Keep a separate mapping to page numbers so answers can cite their source page.
Can a vision LLM replace a PDF parser?
It can handle messy layouts and charts well, but costs more per page and can occasionally produce text that isn't on the page. Use it for the hard pages, and verify extracted numbers against a conventional parser when accuracy matters.
What accuracy can we expect extracting data from PDFs?
Leading models now score above 90 on composite parsing benchmarks for clean digital documents, but accuracy on handwriting, complex tables, and low-quality scans is meaningfully lower. Plan for confidence thresholds and human review on high-stakes fields rather than assuming full automation.
How much does document processing cost at scale?
Current OCR APIs run roughly $1 to $4 per 1,000 pages with batch discounts halving that, so parsing a million-page archive costs low thousands of dollars. The parsing bill is usually smaller than the downstream engineering needed to validate, chunk, and index the output.
Should we use OCR plus an LLM or an end-to-end document AI service?
End-to-end vision-language parsers now lead benchmarks like OmniDocBench and handle layout, tables, and formulas in a single pass, while classic OCR plus templates remains cheaper for uniform high-volume forms. Document variety decides it: heterogeneous documents favor model-based parsing, fixed layouts favor template pipelines.
Bottom line: Dhairya Senjaliya ships RAG — Document Intelligence projects worldwide. Book a scoping call at https://dhairyasenjaliya.com/#book-call.