Layout-Aware Document Parsers
Using Unstructured, Docling and vision LLMs to parse documents by their visual structure.
A layout-aware parser looks at a page the way a person does. It detects titles, paragraphs, lists, tables, figures, headers and footers from their position and appearance, not just from the raw text stream. The output is structured content (usually Markdown or typed elements) that is ready for chunking. This lesson compares three approaches: Unstructured, Docling and vision LLMs.
Why structure matters for RAG
- Better chunks. Knowing where sections begin lets you chunk along real boundaries (Structure-Aware Chunking).
- Intact tables. Tables come out as tables, with headers attached to their values.
- Less noise. Headers, footers and page numbers are labelled and can be dropped.
- Richer metadata. Each element knows its page, its type and its parent heading.
Unstructured
Unstructured is an open-source library that splits many file types (PDF, DOCX, PPTX, HTML, email, images) into typed elements such as Title, NarrativeText, ListItem and Table.
pip install "unstructured[pdf,docx]"
from unstructured.partition.auto import partition
elements = partition(filename="employee-handbook.pdf", strategy="hi_res")
for el in elements[:15]:
print(f"{el.category:15} page={el.metadata.page_number} {el.text[:70]!r}")
# Keep content, drop page furniture
content = [el for el in elements if el.category not in ("Header", "Footer", "PageNumber")]
# Tables also carry an HTML version that keeps rows and columns
tables = [el.metadata.text_as_html for el in elements if el.category == "Table"]
The hi_res strategy uses a layout detection model and is slower; fast uses the text layer only. Unstructured also includes a chunker that respects element boundaries (unstructured.chunking.title.chunk_by_title).
Docling
Docling is an open-source converter from IBM Research. It is strong at reading order, tables and scientific papers, and exports clean Markdown or JSON.
pip install docling
from docling.document_converter import DocumentConverter
converter = DocumentConverter()
result = converter.convert("research-paper.pdf") # also accepts a URL, DOCX, PPTX, HTML
markdown = result.document.export_to_markdown()
print(markdown[:1500])
Docling downloads its layout and table models on first use and runs locally, so no document leaves your machine. Converting long PDFs on a CPU can take a few seconds per page; batch the work during indexing.
Vision LLMs
A vision-capable LLM reads a page image and writes Markdown. It handles things rule-based parsers struggle with: complex forms, nested tables, handwritten notes, charts and unusual layouts. It is also the most expensive option per page. The pattern below sends a single page as a PDF and asks for Markdown:
import base64, io
import anthropic
from pypdf import PdfReader, PdfWriter
client = anthropic.Anthropic()
PROMPT = """Convert this page to Markdown.
- Keep the reading order, headings (#, ##), lists and tables (as Markdown tables).
- Skip running headers, footers and page numbers.
- For charts or images, write one sentence in square brackets describing what they show.
Output only the Markdown."""
def page_to_markdown(path: str, page_index: int) -> str:
writer = PdfWriter()
writer.add_page(PdfReader(path).pages[page_index])
buffer = io.BytesIO()
writer.write(buffer)
data = base64.standard_b64encode(buffer.getvalue()).decode("utf-8")
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=8000,
output_config={"effort": "low"},
messages=[{"role": "user", "content": [
{"type": "document", "source": {"type": "base64", "media_type": "application/pdf", "data": data}},
{"type": "text", "text": PROMPT},
]}],
)
return response.content[0].text
Comparison
| pypdf / PyMuPDF | Unstructured | Docling | Vision LLM | |
|---|---|---|---|---|
| Speed | Very fast | Medium | Medium | Slow |
| Cost | Free | Free (open source) | Free (open source) | Per page (API) |
| Tables | Poor | Good | Very good | Very good |
| Scans and forms | No | With OCR | With OCR | Excellent |
| Charts and images | No | Detected only | Detected only | Can describe them |
| Runs offline | Yes | Yes | Yes | No |
Hosted parsing services such as LlamaParse, Azure Document Intelligence, Google Document AI and Amazon Textract offer similar features as paid APIs.
A practical strategy: route by difficulty
You do not have to pick one parser for everything. A cheap first pass can decide which pages need an expensive one:
from pypdf import PdfReader
def parse_pdf_smart(path: str) -> list[str]:
reader = PdfReader(path)
pages = []
for i, page in enumerate(reader.pages):
text = page.extract_text() or ""
looks_bad = len(text.split()) < 30 or text.count(" ") > 40
pages.append(page_to_markdown(path, i) if looks_bad else text)
return pages
Always keep the page number of every element. Page-level citations ("see page 14") are much more useful to users than file-level citations.
Key takeaways
- Layout-aware parsers recover headings, tables and reading order, which improves chunking and retrieval.
- Unstructured gives typed elements; Docling gives high-quality Markdown; both run locally.
- Vision LLMs handle the hardest pages but cost more, so route only difficult pages to them.
- Keep page numbers and element types as metadata.