From PDF and Web Pages to Markdown: A Practical Guide to Document Parsing

    This article explains why document parsing is a critical bottleneck in the LLM era and how to convert PDFs and web pages into clean, machine-readable Markdown. It covers a five-layer parsing pipeline, practical strategies for handling watermarks, headers and footers, borderless tables, and image semantics, key differences in web parsing, and engineering practices for quality validation at scale.

    1. Why Document Parsing Matters in the LLM Era

    Engineers working on firmware development, chip specification review, and device driver adaptation deal with technical documents that often run to thousands of pages. PDFs are the dominant format. They are fine for human reading, but the problems become obvious once the workflow moves to multi-document retrieval, knowledge graphs, and LLM-based Q&A: overlapping text layers, broken line wraps, tables that fall apart across pages, and images that lose their connection to the surrounding text.

    If you feed raw extracted PDF text directly into a retrieval-augmented generation (RAG) pipeline, chunking will cut through the middle of semantic units, and embedding will treat titles, headers, and watermarks as meaningful body content. The retrieved fragments end up both inaccurate and incomplete.

    Markdown has become the de facto standard at this stage for a simple reason: it is plain text, its structure is explicit, it can be version-controlled, and downstream parsers can reliably recognize heading levels, lists, tables, and code blocks. Converting PDFs and web pages into Markdown is essentially translating a format designed for human visual layout into a structure designed for machine understanding.

    It is worth stressing that the ceiling on conversion quality is set by the parsing pipeline, not by the LLM at the end of the chain. Garbage in, garbage out is especially visible in document parsing.

    2. A Layered Design for a General Parsing Pipeline

    A robust conversion pipeline can be split into five layers. Each layer solves one class of problems and can be replaced and evaluated independently.

    Layer 1 is layout reconstruction. It identifies text blocks, image blocks, and table regions on the page and preserves their relative positions. Errors in reading order judgment are the root cause of most downstream problems; multi-column layouts, marginal notes, and floating figures all interfere with order detection.

    Layer 2 is noise removal. This covers watermarks, headers and footers, page numbers, copyright notices, and repeated revision-history headers. The typical detection criteria combine three signals: repetition across pages, fixed position, and consistent font size and style.

    Layer 3 is structure mapping. Layout blocks are mapped to Markdown syntax: titles become heading levels, paragraphs are merged into continuous text, lists become ordered or unordered lists, and tables become pipe tables or HTML tables.

    Layer 4 is asset extraction. Images and formulas are saved as local files and referenced in Markdown via relative paths, so they can be clicked to zoom and previewed in place in local note-taking tools.

    Layer 5 is post-processing and validation. This includes line-break repair, hyphenated word restoration, duplicate punctuation cleanup, and table column-count consistency checks.

    A schematic pipeline skeleton looks like this:

    1. def parse_to_markdown(page):
    2. blocks = layout_analyze(page) # Layer 1: layout and reading order
    3. blocks = drop_repeated_furniture(blocks) # Layer 2: headers and footers
    4. blocks = remove_watermark(blocks) # Layer 2: watermarks
    5. md_parts = []
    6. for b in blocks:
    7. if b.type == "table":
    8. md_parts.append(table_to_markdown(b)) # Layer 3
    9. elif b.type == "image":
    10. path = save_image(b) # Layer 4
    11. md_parts.append(f"![{b.caption}]({path})")
    12. else:
    13. md_parts.append(text_to_markdown(b))
    14. return postprocess("\n\n".join(md_parts)) # Layer 5

    3. Four Common Problems: Causes and Handling Strategies

    3.1 Watermarks Overlapping Body Text

    Confidential documents often carry diagonal watermarks tiled across the page. This text genuinely exists in the PDF text layer, so extraction treats it as body content and emits large amounts of repeated, semantically meaningless characters that severely pollute embeddings. Three strategies work: first, run cross-page frequency statistics on text content and flag unusually frequent short strings as watermarks; second, use the text direction matrix and prioritize filtering blocks whose skew angle clearly deviates from the page’s main orientation; third, use color and transparency attributes and prioritize filtering light-gray, low-opacity layers. Combining all three is far more reliable than any single rule.

    3.2 Headers, Footers, and Fixed Decorative Text

    Headers and footers sit at fixed positions, repeat across pages, and typically contain the document name, section name, page number, or revision number. The recommended approach is to run a document-level duplicate-line analysis first, register text that appears in the same positional region on more than a certain proportion of pages as a noise template, and then remove it page by page. Be careful to preserve genuine cross-reference numbers that appear in the body text, so they are not deleted by mistake.

    3.3 Unstable Table Detection

    The most valuable content in technical documents is often borderless tables: register bit-field tables, instruction encoding tables, and change-history tables. These tables have no visible separators, so line-based detection misses them unpredictably. A more robust approach relies on text alignment plus whitespace gaps: cluster by horizontal coordinate to determine whether stable column boundaries exist; check whether adjacent rows have a consistent column count; then confirm using features such as whether cell text wraps and whether it is left-aligned. For merged cells and tables that continue across pages, output HTML tables to preserve rowspan/colspan semantics, and avoid pipe tables, which can be broken by parsers when column counts do not match.

    3.4 Linking Images to Their Semantics

    Microarchitecture diagrams, interconnect topology diagrams, and power sequencing diagrams in chip documentation carry a great deal of information. During parsing, bind the figure caption (the Figure/Table title line) to the image and write it into the alt text so that later retrieval can match it. Store all images in an asset directory alongside the Markdown file and reference them with relative paths, which keeps links valid when the whole document is moved.

    4. What Makes Web Parsing Different

    The difficulty with web pages is not layout but template noise and dynamic rendering. Navigation bars, sidebars, recommendation widgets, and comment sections must be removed during main-content extraction; a common approach is to score content blocks based on text density and link density. Code blocks and inline code must be preserved exactly, otherwise indentation and symbols in example code get destroyed. Tables are often used for layout on the web, so layout tables must be distinguished from data tables. If content is loaded dynamically by scripts, rendering must complete before the main content is extracted.

    5. Quality Validation and Engineering Recommendations

    Do not ingest the output directly after conversion. Add an automated validation step: check whether heading levels are continuous, whether table column counts are consistent, whether image reference paths actually exist, and whether the character count per page is abnormally low (which may mean the page is entirely an image or parsing failed). When batch-processing thousands of pages, split parsing tasks into retryable units, log failed pages separately, and use logging services and monitoring alerts to locate problem pages. This is far more efficient than rerunning an entire document at once. Store outputs on a local filesystem or object storage, and keep the mapping between original files and conversion results so they can be traced back.

    6. Limitations and Outlook

    Complex multi-column layouts, large cross-page tables, handwritten annotations, and scanned documents without a text layer remain difficult. Scans require optical character recognition (OCR) first, and recognition errors propagate downstream. Future improvements concentrate on three areas: better layout models for detecting borderless tables and reading order; joint image-text semantic reconstruction that also structures text inside figures; and a self-evaluation mechanism in the parsing result that lets the pipeline proactively flag low-confidence fragments for human review. Building parsing as an observable, evaluable, and iterable data pipeline rather than a one-off conversion script is the prerequisite for LLMs to genuinely understand technical documents.