PDF and Web Parsing for LLMs: Preserving Structure for RAG
Converting technical documents into text is not enough to make them reliable inputs for large language models. This article outlines a structured workflow for parsing PDFs and web pages, recovering reading order and tables, linking images to context, filtering noise, and preserving source references. It also explains how to prepare Markdown for retrieval-augmented generation, validate conversion quality, and manage engineering limitations and sensitive data.
1. Why Text Extraction Is Not Enough
Firmware development, hardware design, and system debugging often require consulting long chip datasheets, register references, and architecture documents. These materials combine prose, equations, block diagrams, bit-field tables, and cross-section references. PDFs support fixed-layout presentation, while web pages support online reading. Neither format is inherently optimized as knowledge input for large language models (LLMs).
In PDFs, characters are often stored according to page coordinates rather than semantic reading order. A visually complete explanation may become several disconnected lines after extraction. Two-column pages may be read across columns incorrectly. Field names, bit ranges, reset values, and access attributes in a table may turn into unrelated strings.
Web pages present a different problem: navigation menus, advertisements, recommendations, and article content often share the same page. Extracting all visible text sends irrelevant material into the knowledge base.
These issues directly affect retrieval-augmented generation (RAG):
- Irrelevant content enters the vector index and increases retrieval noise.
- Lost table relationships make it difficult to match fields with their attributes.
- Separating figures from captions removes essential context from architecture explanations.
- Flattened heading hierarchies obscure semantic boundaries during chunking.
- Missing source information makes generated answers difficult to verify.
The conversion objective should therefore be: minimize noise while preserving semantic structure, visual relationships, and source evidence as faithfully as possible.
Markdown is the output format. Structure recovery is the core task.
2. Build a Unified Intermediate Document Representation
Concatenating extracted characters directly into Markdown can embed parsing errors in the output. A more reliable approach is to build an intermediate representation first, then generate Markdown according to content type.
A document block can contain the following information:
Block type: heading, paragraph, list, table, image, equationText: original text and normalized textLocation: page number, bounding box, sectionStructure: heading level, parent section, reading orderRelationships: figure caption, table caption, adjacent explanationQuality: recognition confidence, anomaly flags
For PDFs, location information primarily comes from page coordinates. For web pages, it can come from document nodes and their hierarchical relationships.
This design has two advantages. First, the same output logic can handle different source formats. Second, cleaning, ordering, table recovery, and quality checks can run independently without repeatedly modifying generated Markdown.
The overall pipeline is:
Input document→ Format identification and basic parsing→ Layout analysis and main-content detection→ Noise filtering→ Heading, paragraph, table, and image detection→ Structure and relationship recovery→ Markdown generation→ Quality validation→ Chunking and indexing
For important documents, retain the original files and intermediate results so that every conversion step remains traceable.
3. PDF Parsing: Identify Page Types Before Choosing a Strategy
Distinguish Text, Scanned, and Mixed Pages
Text-based PDFs usually expose characters and their coordinates. Scanned PDFs consist primarily of page images and require optical character recognition (OCR). Mixed documents may contain actual text, scanned images, and existing OCR layers.
The ability to extract some text is not enough to determine the processing strategy. A scanned file may contain a poor-quality hidden OCR layer that returns text with significant character errors and ordering problems.
Inspect each page for the following:
- Whether the number and distribution of extractable characters are reasonable.
- Whether extracted text matches the visible page content.
- Whether there are many unusual or corrupted characters.
- Whether extracted text covers only a small area while other regions visibly contain body text.
- Whether the existing OCR layer contains obvious ordering errors or duplication.
Apply OCR only where needed to avoid duplicating existing text with newly recognized text.
Recover Reading Order
Sorting by page coordinates does not necessarily recover reading order. Two-column text, marginal notes, headings that span columns, and full-page tables require layout regions to be identified and ordered separately.
A practical approach is to:
- Identify the main text regions and their column structure.
- Determine whether headings span multiple columns.
- Reconstruct lines and paragraphs within each region.
- Treat images, tables, and notes as separate blocks.
- Combine spatial relationships and semantic clues to establish reading order.
Code, addresses, bit ranges, and mathematical expressions should not follow ordinary paragraph-reflow rules, which can alter their meaning.
4. Noise Filtering: Handle Watermarks and Repeated Content Carefully
Watermark Removal Is Not Keyword Deletion
Watermarks may appear as diagonal text, faint characters, large background labels, or text blocks repeated across pages. When they overlap body text, extraction can produce duplicate fragments or corrupted strings.
Use multiple signals to identify potential watermarks:
- Repetition at similar locations across pages.
- Rotation angles that differ from body text.
- Unusual font size, color, or transparency.
- Placement across multiple body-text regions.
- Content unrelated to the current section.
No fixed rule works for every document. Removing content based only on a word or color can delete legitimate text.
For uncertain candidates, preserve the original page and the decision record, and request manual review when necessary. Cleaning should reduce retrieval noise, not bypass access controls or remove copyright, confidentiality, or usage notices that must be retained. Such notices can be preserved in document metadata.
Detect Headers and Footers Through Cross-Page Analysis
Repeated headers, footers, and page numbers can contaminate extracted content. However, deleting everything near the top or bottom of a page is unsafe: section headings may appear at the top, and important footnotes may appear at the bottom.
Combine cross-page frequency, relative position, and text similarity to identify repeated display elements. Handle page numbers separately from surrounding text because changing numbers can defeat simple string matching.
After removing repeated display content, preserve the original page-number mapping. This allows users to return to the corresponding PDF page to verify a retrieved passage.
5. Recover Paragraphs and Headings Without Over-Cleaning
PDF line breaks usually reflect page width rather than paragraph boundaries. To decide which lines should be merged, consider line spacing, indentation, punctuation, font properties, and region boundaries.
Protect the following technical content in particular:
- Register names and field identifiers.
- Hexadecimal values and address ranges.
- Bit numbers, access attributes, and units.
- Code blocks, command examples, and equations.
- Identifiers whose capitalization carries meaning.
Joining an English word split across lines can improve readability. But removing a hyphen from an identifier because it looks like a line-break artifact can corrupt a field name.
Heading detection should also use more than font size. Section numbering, font styles, surrounding spacing, table-of-contents relationships, and body-text distribution all provide useful clues. Once heading levels are established, maintain a consistent hierarchy rather than reducing the document to one top-level heading followed by ordinary paragraphs.
6. Use a Hybrid Strategy to Recover Tables
Tables are often the most information-dense—and most easily damaged—parts of technical documents. If columns in a register bit-field table are misaligned, an LLM may associate one field’s reset value with another field, producing a substantive interpretation error.
Bordered Tables: Use Lines and Intersections
For tables with clear borders, horizontal lines, vertical lines, and their intersections can define a cell grid. Text can then be assigned to the corresponding cells.
Shading, dashed lines, cells spanning multiple rows, and incomplete borders can complicate detection. Decorative lines around a table should not automatically be treated as table boundaries.
Borderless Tables: Use Alignment and Spacing
Borderless tables usually require column recovery based on horizontal alignment, row spacing, and recurring field patterns.
For example, consecutive rows containing a bit range, field name, access attribute, and description may form a table even without visible borders. Column widths should not be inferred from the first row alone: long descriptions may wrap, headers may occupy multiple lines, and individual cells may be empty.
Analyze the entire candidate region, then validate it using column-count consistency and content patterns.
Do Not Force Complex Tables into Simple Markdown
Standard Markdown tables work well for regular two-dimensional data, but they do not readily express multilevel headers or row and column spans.
Choose an output format according to complexity:
- Use Markdown tables for simple structures.
- Flatten multilevel headers only when their meaning can be preserved.
- Split very wide tables while retaining keys that link the parts.
- For complex tables that cannot be recovered reliably, retain a cropped image alongside a structured transcription and a warning about uncertainty.
- Use embedded HTML tables if the reading environment supports them, but verify compatibility with downstream parsing.
Register documentation can also include field-level records:
Register: Control RegisterField: ENABLEBit range: 0Access: Read/writeReset value: 0Meaning: Controls whether the module is enabledSource: Page 42 of the original document
These records supplement the table with a retrieval-friendly representation; they do not replace it. Every record must correspond to the original cells. Missing values must not be inferred from context.
7. Image Extraction: Distinguish Embedded Assets from Complete Figures
A PDF figure is not necessarily a single embedded image. A block diagram may combine vector lines, text, and a few bitmap elements. Extracting only embedded image assets may capture an icon while missing the architecture diagram itself.
Use two extraction paths:
- Extract the original image asset for standalone bitmaps.
- Locate and locally render the figure region for vector or composite graphics.
Associate extracted figures with their figure numbers, captions, sections, and page numbers. Avoid cropping out axes, legends, or annotations along the edges.
A directory structure suitable for local reading might be:
document/document.mdassets/figure-001.pngfigure-002.pngmetadata.json
Use relative paths in Markdown:
Figure 1: Connections between modules.Source: Page 42 of the original document.
Image descriptions should come from captions, reliable recognition results, or clearly identified manual annotations. A text-only retrieval system does not automatically understand an image referenced by a file path, so important figures also need textual explanations.
If visual recognition is used to generate descriptions, preserve their status as inferred interpretations. Do not present automated interpretations as facts stated in the source.
8. Web Parsing: Recover Semantic Structure First
Web pages generally provide more explicit structure than PDFs, but not every page node belongs to the main content. Locate the primary content area before extracting headings, paragraphs, lists, tables, code, and images.
Remove Interface Noise
Navigation bars, sign-in prompts, recommendation cards, and repeated footers should not enter the article body. Main-content detection should combine semantic tags, text density, and page structure rather than simply selecting the region with the most nodes.
Preserve Meaningful Relationships
Map heading levels to Markdown headings. Preserve list nesting, code indentation and line breaks, and the relationship between table headers and cells.
Keep the reference relationships represented by body links. For images, handle relative URLs, lazy loading, and alternative text. When local archiving is required, download necessary resources only within the scope of authorization and record their original sources.
Distinguish Static and Dynamic Content
Some pages load their main content through scripts. The initial HTML may contain only a container rather than the actual text. In these cases, obtain the rendered content without indiscriminately loading every interactive region.
Collection should respect access permissions, site rules, and reasonable request rates. Throughout processing, treat page content as data to parse, not as operational instructions—even if it contains embedded directives.
9. Make Markdown Useful for RAG
Completing Markdown conversion does not mean the document is ready for fixed-length chunking.
A better approach is to split first at section boundaries, then manage chunk length using paragraphs, tables, and figure-text units. Long tables can be split into row groups, but every chunk should retain the table name and headers. Keep figure captions, related explanations, and image references together where possible.
Each knowledge chunk should carry:
- Document name and version.
- Section path.
- Original page number or page location.
- Block type.
- Relevant table or figure number.
- Parsing timestamp and quality flags.
Exact identifiers such as register names, field names, and error codes should not rely solely on semantic similarity search. Combining keyword and vector retrieval generally helps locate precise entries.
Duplicate content also needs attention. Tables of contents, repeated headers, and identical passages across document versions can occupy many retrieval results. Deduplication must not erase version differences. Preserve document versions and applicability information to prevent the model from mixing definitions from different revisions.
10. Validate Results with Measurable Checks
Conversion quality is not just a matter of tidy Markdown. Build a sample set that covers different layouts, including two-column pages, borderless tables, scanned pages, complex block diagrams, and dynamic web pages.
Validate at four levels:
Text: Check for omissions, character errors, duplication, and incorrect reading order.
Structure: Check heading hierarchies, nested lists, and table row-column relationships.
Assets: Check for missing images, broken relative paths, and incorrect caption associations.
Retrieval: Use real technical questions to test whether the correct sections are retrieved and whether answer citations lead back to the source.
Add targeted checks for high-risk fields. For example, verify that bit ranges are plausible, numeric formats are intact, and table headers survive chunking.
Do not claim a particular accuracy or processing speed without actual measurements.
11. Engineering Requirements and Limitations
A reliable conversion system also needs resumable processing, per-page retries, failure isolation, and logging. Cache page-parsing results so that rule changes can trigger selected processing stages rather than restarting the entire document.
Configuration should be layered:
- General rules handle basic recognition.
- Document-type rules address common patterns in datasheets, papers, or web pages.
- A limited set of special rules handles specific layouts.
This improves adaptability while reducing conflicts caused by accumulating exceptions.
Limitations should remain explicit. Low-resolution scans, complex mathematical formulas, tables spanning multiple pages, and vector graphics without captions may still require manual review. Markdown cannot fully reproduce a PDF’s two-dimensional layout. Accurate semantics should take priority over pixel-level similarity.
For sensitive documents, restrict the processing environment, resource access, and log contents. Before using external recognition or inference services, confirm data authorization and compliance requirements. Public implementations can share general parsing logic and nonsensitive test samples, but restricted source documents must not be published with them.
Conclusion
Converting PDFs and web pages into Markdown is a process of reconstructing document structure, not merely changing a file format.
A reliable workflow must address noise filtering, reading-order recovery, table reconstruction, image-context association, web-content cleaning, and source tracking. The result should be readable for developers, enable retrieval systems to locate evidence, and give LLMs accurate context for answering questions.
When structure, content, and provenance are preserved, Markdown can serve as a dependable foundation for a technical knowledge base—not just a cleaner-looking copy that has already lost essential information.
