Parsing PDFs and Web Pages into Markdown: A Practical Pipeline for LLM-Ready Documentation

    This article presents a practical approach to converting PDFs and web pages into Markdown so that dense technical documents become easier to search, version, and use in retrieval-augmented generation workflows. It covers a six-stage pipeline, robust removal of watermarks and headers, reconstruction of borderless and cross-page tables, image extraction with local-friendly references, web-specific parsing differences, and quality evaluation with chunking strategies. Readers will find implementation-oriented guidance, sample logic, and the current limitations of layout-driven parsing.

    1. Why Raw PDFs Are a Poor Fit for LLMs

    In firmware and low-level software development, engineers deal with chip specifications, extended programming manuals, datasheets, and errata every day. These documents often run from hundreds to thousands of pages, carry extremely high information density, and contain large numbers of register bit-field tables, instruction encoding tables, change history tables, and microarchitecture diagrams.

    PDFs are good for reading and printing, but poor for retrieval and reprocessing. Overlapping text layers, broken line breaks, tables split across pages, and captions mixed with body text all degrade the quality of downstream chunking and vectorization.

    Converting documents to Markdown delivers three benefits:

    • Explicit structure: headings, lists, code blocks, and tables become parseable syntax elements.
    • Linkability and version control: plain text makes cross-document references and diff comparisons straightforward.
    • Natural fit with retrieval-augmented generation: structured text is easier to split into semantically complete chunks.

    The key point is that conversion quality is determined by the parsing pipeline, not by any single command-line switch.

    2. Overall Pipeline Design

    A robust conversion pipeline should be split into six stages, each independently testable and rollback-friendly:

    1. Layout reconstruction: identify page region types (body text, header, footer, figures, tables, footnotes).
    2. Noise cleaning: remove watermarks, repeated headers and footers, page numbers, and copyright notices.
    3. Structure rebuilding: restore heading hierarchy, paragraph order, and reading order (including double-column and cross-page cases).
    4. Table processing: detect table boundaries and reconstruct merged cells and continued tables.
    5. Image extraction: export block diagrams and architecture diagrams, rename them to readable filenames, and write relative paths.
    6. Post-processing and indexing: generate anchors, a table of contents, tags, and chunks for retrieval.

    In practice, keep intermediate artifacts (layout coordinates, raw text blocks) so that quality regressions can be traced without rerunning everything from scratch.

    3. Key Step 1: Robust Cleaning of Watermarks, Headers, and Footers

    Confidential documents commonly use diagonal tiled watermarks whose text overlaps the body. Direct extraction produces large amounts of meaningless characters. Feasible strategies, ordered from lowest to highest cost:

    • Text-layer filtering: identify watermarks by font size, color, transparency, rotation angle, and repetition frequency, then build a character-level blocklist.
    • Positional priors: headers and footers usually sit in fixed proportional regions at the top and bottom of the page; combine this with a “repeats across pages” feature for statistical detection.
    • Content templates: turn repeated copyright pages, change record pages, and disclaimer pages into template fingerprints, and skip the whole page on a match.

    Example logic:

    1. def is_noise(block, page_h, seen_pages):
    2. # In a fixed page margin region and repeated across multiple pages
    3. in_margin = block.y1 < page_h * 0.06 or block.y0 > page_h * 0.94
    4. repeated = block.text_hash in seen_pages
    5. rotated = abs(block.rotation) > 30
    6. return (in_margin and repeated) or rotated

    Thresholds should be configurable, and blocks flagged as “possibly deleted by mistake” should be logged, so that the first line of body text or a table caption is not misclassified as noise.

    4. Key Step 2: Mixed Table Detection and Structure Reconstruction

    The difficulty in chip documentation lies in borderless tables: bit-field tables express structure through column alignment rather than lines, change history tables continue across pages, and register tables contain merged cells. A stable approach fuses multiple signals:

    • Geometric signals: character spacing, column alignment consistency, and row baseline clustering.
    • Text signals: fixed column names (such as Bits, Name, Description, Reset Value) as anchors.
    • Cross-page signals: continued tables usually repeat the header, so a header fingerprint can stitch multiple pages back into one table.

    For output, provide two forms: a compact human-friendly table, and structured data that preserves full semantics (such as a list of row objects), the latter used to generate high-quality chunks. For bit-field tables with very many columns and long cell text, keep the main table in Markdown and push overly long descriptions down into “anchor + paragraph” form, balancing readability and retrieval granularity.

    1. {"table_id":"reg_ctrl","header":["Bits","Name","Description"],
    2. "rows":[["31:16","Reserved","—"],["15:8","WCNT","Watchdog counter"]],
    3. "continued_from":null}

    5. Key Step 3: Image Extraction and Local Reading Experience

    Architecture diagrams, interconnect topology diagrams, and power timing diagrams often carry information that body text cannot replace. If the parser does not export images, it discards half the document’s value. Practical points:

    • Extraction granularity: export whole layout regions by preference, avoiding fragmenting a single block diagram; render vector graphics to bitmaps by region.
    • Naming convention: use “document ID-page number-sequence-semantic hint” so images are easy to search and deduplicate.
    • Reference style: store images alongside the Markdown and reference them with relative paths, so clicking zooms in directly in local note-taking software without switching readers.
    • Caption binding: write the figure title and figure number into an italic paragraph below the image, forming a “figure-caption-body reference” loop.
    1. ![SoC interconnect topology](./assets/SoC-interconnect-p12-fig3.png)
    2. *Figure 3-2 SoC Interconnect Topology*

    6. Differences and Key Points for Web Parsing

    Web pages and PDFs have different parsing goals: web noise comes from navigation, ads, sidebars, and scripts, so locating the main content comes first. The recommended flow is to identify the main content region first (scoring text density, link density, and tag semantics together), then convert uniformly to Markdown, and finally handle relative links and resource addresses, downloading images locally and rewriting them to relative paths. For paginated articles, merge them into a single document; for code blocks and formulas, preserve fences and original characters to avoid escape damage to semantics. If the target site has access restrictions, respect its terms and control crawl frequency.

    7. Quality Evaluation and Chunked Indexing

    Evaluation should be independent of the conversion implementation. Build a small gold-standard set (several borderless tables, cross-page tables, double-layer watermarks, and double-column pages each), with metrics including table structure reconstruction accuracy, residual noise character ratio, image recall, and heading level correctness.

    For chunking, use heading hierarchy as the primary boundary, do not cut tables or figures across chunks, and keep a “document name + section path” prefix inside each chunk so that context remains traceable after vector recall. Storing source documents and image assets in cloud object storage, decoupling parsing tasks with a message queue, and scaling parsing concurrency horizontally on a container platform can significantly improve throughput for large document batches, while logs and monitoring alerts help locate failed pages.

    8. Limitations and Outlook

    Layout-driven parsing still has boundaries today: extremely complex multi-column layouts, scanned documents, text inside hand-drawn diagrams, and long tables spanning chapters still require manual spot checks and rule tuning. A viable direction is combining layout models with a rule engine, using rules to guarantee determinism and models to improve generalization, and accumulating manual corrections into reusable templates. Once parsing, cleaning, chunking, and indexing form a closed loop, a local knowledge base can support not only keyword retrieval but also feeding accurate passages to intelligent coding tools, helping generate code and configuration closer to hardware facts.