PDF and Web Page to Markdown for LLMs: A Practical Guide to Structured Document Parsing

    Retrieval-augmented generation (RAG) systems and local knowledge bases depend heavily on clean document input. This article explains why PDFs and web pages are difficult to feed directly into LLMs, outlines the requirements for table-heavy and figure-heavy technical documents, and describes a practical parsing pipeline covering watermark removal, header/footer filtering, mixed table detection, and image extraction with relative-path references. It also reviews common limitations of open-source document-to-Markdown tools and provides output-quality recommendations for chunking, tables, image captions, and RAG preprocessing.

    1. Why LLMs Need Markdown Documents

    When building a retrieval-augmented generation (RAG) system or a local knowledge base, document input quality often determines the ceiling on final results. PDFs and web pages are two of the most common knowledge sources, but they are not naturally friendly to large language models:

    • Inherent problems with PDFs: A PDF is essentially a layout format, not a data format. It records where text appears on a page, but does not preserve logical structure. Overlapping text, broken line breaks, disordered multi-column layouts, and fragmented tables are all amplified during chunking and embedding, significantly reducing retrieval precision.
    • Problems with web pages: HTML often contains navigation bars, advertisements, script code, footers, and other noise. The main content is buried among irrelevant tags. Feeding raw HTML directly into a model wastes context window space and introduces interference.

    By contrast, Markdown has clear advantages. It expresses structural hierarchy in plain text—headings, lists, tables, code blocks, and image references—with clear semantics, low token overhead, and close alignment with the pretraining corpora used by LLMs. As a result, converting PDFs and web pages into Markdown has become a key preprocessing step in LLM document engineering.

    Typical use cases include building knowledge bases from technical documentation, multi-document full-text retrieval, cross-document knowledge graph construction, and injecting structured fragments as context into intelligent coding tools to help LLMs generate more accurate code.

    2. Core Requirements in Typical Scenarios

    For documents such as chip datasheets and enterprise technical manuals that are heavy on tables and figures, a usable parsing solution should satisfy at least the following requirements:

    1. Tables must be restored in a human-readable form. The generated Markdown is not only consumed by models; people also need to read and search it directly. Borderless tables, such as register bitfield tables and revision history tables, are especially prone to failure. Many tools work inconsistently and depend heavily on luck.
    2. Images should be saved as local files. A specification running to over a thousand pages may contain hundreds of block diagrams and architecture diagrams. The ideal approach is to extract images into a sibling directory and reference them in Markdown using relative paths. This allows local knowledge base tools to preview images seamlessly and support click-to-zoom without switching back and forth between readers.
    3. Noise must be removed. Watermark text often overlaps the body text, and direct extraction can produce large amounts of garbled content. Headers and footers repeat on every page; when mixed into the body, they both pollute the reading experience and waste tokens.
    4. Structural hierarchy must be preserved. Heading levels and section numbering are among the most important semantic boundaries during chunking, and they must be reconstructed accurately after parsing.

    3. Core Design of the Parsing Pipeline

    A high-quality PDF parsing pipeline for LLMs typically includes the following processing steps:

    3.1 Watermark Removal

    Watermarks inside PDFs usually exist in two forms: independent text objects, often with skewed transformations, light gray color, or repeated character patterns, and background images. The processing strategy is to start with text-object analysis: detect repeated short strings and unusual rotation or opacity attributes, mark them as watermarks, and remove them. For image-based watermarks, use pixel-level comparison across pages to identify fixed overlay regions. If this step is handled poorly, the output will contain patches of garbled fragments that seriously contaminate the corpus.

    Headers and footers are characterized by fixed positions and repetition across pages. A common method is to define narrow bands at the top and bottom of each page by coordinates, then count the frequency with which text in those regions appears across pages. Strings that repeat across multiple pages—such as the document title, chapter name, or patterns like “Page X”—are identified as headers or footers and filtered out. Care should be taken to preserve cases where the first body line accidentally falls into a band; the repetition condition can help distinguish such text from true headers or footers.

    3.3 Mixed Table Detection

    Table detection needs to combine two types of signals:

    • Ruled tables: These rely on line and border detection. Cell structure can be inferred from the intersections of horizontal and vertical lines. This type of table is relatively easier to handle.
    • Borderless tables: These rely on text alignment analysis. By analyzing the horizontal coordinate distribution of text lines, left-aligned columns can be clustered into column boundaries, and rows can then be split based on sudden changes in line spacing. Instruction encoding tables and bitfield tables mostly fall into this category, and they are the difficult part of detection.

    A practical engineering recommendation is to use a layout analysis model, such as an object-detection or Transformer-based layout model, as a fallback for high-value documents. Rule-based methods can handle common formats, while model-based methods can handle difficult pages.

    3.4 Image Extraction and Reference Generation

    The key to image extraction is not simply “getting the images out,” but “placing them in the right location”:

    1. # Example: extract images and generate relative-path references
    2. for page in doc.pages:
    3. for img in page.images:
    4. fname = f"assets/page{page.number}_img{img.index}.png"
    5. img.save(output_dir / fname)
    6. # Insert the reference at the image's original position
    7. page_content.insert(img.anchor_pos, f"![figure]({fname})\n")

    Note that some low-level PDF libraries have limited image extraction capabilities and can only retrieve certain embedded objects. They often cannot handle vector graphics, masked images, or soft-mask transparent images. When the extraction failure rate is high, you can fall back to rendering page regions as bitmaps to ensure that diagrams are not lost.

    4. Common Limitations of Mainstream Open-Source Solutions

    There are now several mature open-source document-to-Markdown tools, including benchmark projects from major vendors. However, in professional document scenarios involving heavy figures, heavy tables, and watermarks, they commonly have three significant shortcomings:

    1. Images are not extracted or are extracted incompletely. The parsing libraries underlying some tools have limited image support. Even when options for preserving data are enabled, the output may still contain no images at all. For datasheets with hundreds of diagrams, this is a critical problem.
    2. Watermarks and headers/footers are mixed into the body text. Watermark text in confidential documents overlaps with the body and produces large amounts of garbled content. Headers and footers are retained as-is, polluting the output.
    3. Borderless table detection is unstable. Such tables have no border lines to rely on, and purely rule-based methods vary widely in success rate.

    These limitations show that general-purpose tools solve 80% of common documents, while the remaining 20% of professional documents require a customized pipeline. Understanding a tool’s underlying implementation—which PDF parsing library it uses and whether it relies on lines or alignment for table recognition—is necessary to predict whether it will be usable in your scenario.

    5. Output Quality Recommendations for RAG

    • Maintain semantically complete chunk boundaries. Preserve heading hierarchy during parsing, and split by headings rather than fixed character counts. This can significantly improve retrieval hit rate and answer accuracy.
    • Convert tables into real tables rather than screenshots. Markdown tables allow models to understand the relationship between values and table headers directly. Image-based tables lose this capability.
    • Add captions to images. Preserve the caption below each image where available to support matching during multimodal retrieval.
    • Establish a quality spot-check mechanism. Randomly sample and manually verify parsing results, focusing on tables, formulas, and code snippets, and build a regression test set.

    6. Conclusion

    Parsing PDFs and web pages into Markdown is fundamentally a structural reconstruction from layout to semantics. The core work lies in cleaning up watermarks, headers, and footers; detecting tables with a mixed strategy; creating localized references for images; and accurately restoring heading hierarchy. General open-source tools can provide a quick start, but professional document scenarios often require targeted enhancements based on their underlying capabilities. Only when this preprocessing step is done well can downstream chunking, embedding, and RAG performance truly meet expectations. For a large language model, one clean Markdown document is worth more than ten beautifully formatted PDFs.