Parsing PDFs and Web Pages into Markdown: Practical Techniques for RAG Knowledge Bases

    This article explains why structured parsing is a prerequisite for reliable retrieval-augmented generation (RAG), especially for technical documents such as datasheets, programming manuals, and specifications. It outlines a staged processing pipeline, then covers key challenges and practical solutions: suppressing watermarks and template headers/footers, detecting borderless tables using geometric and semantic signals, extracting and referencing images locally, and restoring heading hierarchy and reading order. It also discusses chunking and metadata strategies for LLM consumption, quality evaluation dimensions, common pitfalls, and how clean Markdown conversion turns large specification documents into computable knowledge assets.

    1. Why Structured Parsing Is a Prerequisite for RAG

    In technical fields such as firmware, semiconductors, communications, and automotive electronics, engineers routinely consult specifications, programming manuals, and datasheets distributed as PDFs. These documents often run hundreds or even thousands of pages and contain large numbers of register bit-field tables, instruction encoding tables, revision history tables, microarchitecture block diagrams, interconnect topologies, and power sequencing diagrams. PDFs excel at preserving layout, but their text layer is often assembled from character fragments positioned by absolute coordinates, so the logical reading order does not match the visual order.

    These problems are amplified when such documents enter a retrieval-augmented generation pipeline:

    • Broken line wraps: a complete sentence is split across multiple lines, and semantics are cut off during chunking;
    • Overlapping text: watermarks, annotations, headers, and footers share the same region as the body text, producing noisy characters;
    • Shattered tables: cells are flattened into whitespace-separated text streams, and row/column relationships are lost;
    • Missing images: diagram content becomes completely unsearchable, while key conclusions in engineering documents often appear only in figures.

    The result is incomplete chunk semantics, drifting embedding vectors, lower recall accuracy, and LLM-generated code or conclusions with insufficient reliability. Converting PDFs and web pages into cleanly structured Markdown is therefore not merely a formatting preference; it is foundational engineering that determines knowledge base quality.

    2. Overall Processing Pipeline Design

    A robust parsing workflow should be split into observable, rollback-capable stages, with each stage emitting intermediate artifacts to make problem localization easier:

    1. Layout reconstruction: identify page region types (body, header/footer, figure area, table area, footnotes);
    2. Noise suppression: watermark detection and header/footer filtering;
    3. Structure reconstruction: heading hierarchy inference, paragraph merging, list and code block restoration;
    4. Table processing: table boundary detection, cell merging, cross-page table stitching;
    5. Figure extraction: image cropping, deduplication, saving to disk, and relative path referencing;
    6. Semantic post-processing: terminology and hyphenation repair, anchor generation, chunking, and metadata annotation.

    Web page parsing can be treated as a variant of the same framework: use a main-content extraction algorithm to locate the primary content container, strip navigation, ads, and recommendation widgets, then map the DOM structure to headings, lists, tables, and code blocks.

    3. Key Challenges and General Solutions

    3.1 Handling Watermarks and Headers/Footers

    Watermarks generally fall into text-based and graphic-based types. Text-based watermarks are often overlaid diagonally, semi-transparently, and in repeated tiles. Their characters overlap heavily with body characters in coordinates, so naive line aggregation inevitably produces garbled text. Viable detection signals include: the same text repeating frequently within a single page, non-horizontal character orientation, differences in color or transparency from the body text, and identical relative positions across pages.

    Headers and footers are the opposite: they sit at fixed positions with highly repetitive content, but may change across chapters. A more reliable engineering approach is not to hardcode rules but to perform cross-page statistics first: short text appearing in the same region on most pages is judged as template noise and removed, while page numbers are retained for later reference and location.

    1. # Example: template noise detection based on cross-page statistics
    2. from collections import Counter
    3. def detect_template_noise(pages_text, top_ratio=0.6):
    4. counter = Counter()
    5. for lines in pages_text:
    6. for ln in set(lines): # deduplicate within a page to avoid long-text bias
    7. counter[ln] += 1
    8. threshold = top_ratio * len(pages_text)
    9. return {text for text, c in counter.items() if c >= threshold}

    3.2 Detecting Borderless Tables

    Tables in technical manuals often have no visible borders and rely only on column alignment and whitespace for separation, so column boundaries drift during plain text extraction. A more reliable approach combines geometric and semantic channels: on the geometric side, use horizontal projection statistics of character blocks to find blank columns, and cluster starting x-coordinates to derive candidate column boundaries; on the semantic side, validate whether the column division is reasonable using data type consistency (hexadecimal, decimal, bit-width ranges, register name patterns). For continued tables across pages, stitch them by detecting repeated headers and comparing column structure similarity, and add a line in Markdown noting the source page numbers.

    When outputting Markdown tables, escape pipes and line breaks inside cells to avoid breaking the table structure; for very wide tables, also keep a copy of the original aligned text as an appendix to serve both human and machine readers.

    3.3 Image Extraction and Local Reading Experience

    Engineering diagrams are high-density information zones in chip documentation. The recommended extraction flow is: crop based on figure area detection, deduplicate adjacent pages by similarity, then save to a resource directory at the same level as the Markdown file using content-hash-based names, and reference them with relative paths in the body. This enables click-to-zoom in local note environments without switching readers.

    1. ![CPU microarchitecture block diagram](assets/2026-08-20-cpu-microarch-9f3a.png)

    Also add a textual description for each image (caption plus key signal names) so that image content becomes searchable, which is especially important for plain-text embedding models.

    3.4 Restoring Heading Hierarchy and Reading Order

    Font size, font weight, and numbering patterns (such as 1, 1.1, 1.1.1) are the main signals for inferring heading levels. Reading order should be determined by sorting blocks rather than sorting the character stream; multi-column layouts should first be clustered by column and then merged top to bottom. Hyphenation repair should maintain a domain dictionary to avoid incorrectly joining register names or signal names as ordinary English words.

    4. Semantic Optimization for LLMs

    Correct structure is only the first step; usability for LLMs also depends on chunking strategy and metadata design:

    • Prefer chunk boundaries at natural structures such as headings, tables, and code blocks; avoid splitting tables;
    • Attach metadata to each chunk, including document title, section path, page number, and figure/table number, to support citation and traceability;
    • Transcribe tables into natural-language “field-value” summaries alongside the original table to improve recall;
    • Generate stable anchor identifiers to support bidirectional links and cross-document knowledge graph construction.

    In cloud practice, parsing artifacts and original files can be stored together in object storage, message queues can drive parsing tasks, container platforms can host parsing and embedding services, and logging and monitoring with alerting can track failure rates and latency. Baidu AI Cloud can provide supporting foundational capabilities in these general categories.

    5. Quality Evaluation and Common Pitfalls

    It is advisable to build a small gold-standard set and evaluate across four dimensions: structural fidelity (heading hierarchy and table reconstruction accuracy), noise residue rate, image recall rate, and chunk semantic completeness. Common pitfalls include: mistaking decorative separator lines for tables, merging figure captions into body paragraphs, failing to deduplicate cross-page table headers and thus producing duplicate rows, and relative path case sensitivity failing across platforms. Versioning the intermediate artifacts of each stage is the most effective way to quickly locate regression issues.

    6. Summary

    The essence of converting PDFs and web pages into Markdown is reconstructing presentation-oriented layout information into semantics-oriented structural information. Focusing on four points—noise suppression, joint geometric and semantic table detection, asset-based image referencing, and structured chunking—can significantly improve the retrieval quality of local knowledge bases and the reliability of generative question answering, turning thousand-page specifications into truly computable knowledge assets.