PDF and Web to Markdown: A Structured Parsing Practice for Technical Documents

    This article explains why converting PDFs and web pages to Markdown is a document structure recovery problem rather than a format swap. It covers a unified intermediate representation, page-type detection and reading-order recovery for PDFs, protection of technical symbols during line-break repair, header/watermark/footer removal based on layout evidence, image extraction with captions and provenance, table parsing with structural validation, web main-content extraction, structure-aware chunking for retrieval-augmented generation, and a quality acceptance checklist for engineering deployment.

    1. The Goal Is Not a Format Change, It Is Structure Recovery

    In firmware development, chip verification, and low-level software maintenance, developers constantly consult large technical documents. These contain register definitions, instruction encodings, timing constraints, block diagrams, and revision histories. Web documentation typically mixes navigation menus, body text, code blocks, and dynamically loaded content.

    When such material is handed directly to a large language model, the problem is usually not “there is no text.” The problem is that the relationships between pieces of text are not expressed correctly. For example:

    • A two-column page is concatenated line by line, so two paragraphs alternate with each other.
    • A register bit-field table degrades into continuous text, and bit ranges, field names, and access attributes lose their correspondence.
    • An architecture diagram retains only its caption; the module connections in the figure are gone entirely.
    • Headers, watermarks, and navigation menus repeatedly enter the body text and pollute retrieval results.
    • Section headings are separated from their body text, so chunks produced after splitting lack necessary context.

    Markdown can express headings, lists, links, code blocks, and simple tables with relatively low format complexity, which makes it a suitable text carrier for model input. But it does not automatically fix a wrong reading order, and it cannot fully express every diagram relationship.

    A more reliable goal is: restore the logical structure of the document first, then generate Markdown, while preserving images, complex tables, and source information.

    2. Establish a Unified Intermediate Representation

    PDFs and web pages have different underlying structures. If each is converted straight to Markdown, unified cleaning, chunking, and acceptance checking become difficult later. It is better to define an intermediate representation first and normalize both document types into content blocks.

    A content block can contain:

    1. block_id: identifier of the content block
    2. type: heading, paragraph, table, image, code, or list
    3. text: text content
    4. source_id: identifier of the source document
    5. location: PDF page number and coordinates, or web element locator
    6. heading_path: section path the block belongs to
    7. asset_ref: associated image or other attachment
    8. quality_flags: parsing uncertainties and manual review status

    These fields are an engineering design example, not an existing interface of any particular tool.

    A unified intermediate representation brings three direct benefits. First, Markdown becomes only one output form rather than the single data store. Second, stable associations can be built between tables, images, and text. Third, when a parsing error is found, you can go back to the original page or web page to verify it, instead of facing a piece of text that has lost its source.

    The overall pipeline can be organized as:

    1. document acquisition
    2. -> type detection
    3. -> text and layout parsing
    4. -> content block normalization
    5. -> noise removal and structure repair
    6. -> figure and table association
    7. -> Markdown generation
    8. -> quality checks
    9. -> structure-aware chunking for retrieval

    3. PDF Parsing: Detect the Page Type First, Then Choose a Path

    3.1 Separate Text-Based, Scanned, and Mixed Pages

    A text-based PDF usually has an extractable text layer, but the order of that layer does not necessarily match the visual reading order. A scanned PDF consists mainly of page images and requires optical character recognition to obtain text. A mixed document may contain both a text layer and scanned regions on different pages, or even on the same page.

    Therefore, the parsing strategy should classify by page or region as much as possible, not only by file. You can combine several signals: the number of extractable characters, how those characters are distributed, how much of the page is covered by images, and whether the text contains obvious garbling.

    If a page already has a reliable text layer, prefer the original character information. Blindly re-recognizing an entire document may increase compute cost and introduce new character errors. For scanned pages or local image regions, run recognition and keep the coordinates and quality information of the recognition results.

    3.2 Recover Reading Order from the Layout

    A PDF is closer to a description of “draw content at specified positions on a page” than a natural section tree. Parsing should use text block coordinates, line spacing, font characteristics, and region segmentation to recover the order.

    Typical processing steps:

    1. Aggregate characters into text lines.
    2. Aggregate text lines into paragraphs or candidate regions.
    3. Detect multi-column layouts, headings spanning columns, and standalone notes.
    4. Determine reading order from region relationships.
    5. Associate figure captions and table captions with their objects.

    For paragraphs and tables that span pages, continuation relationships must also be detected. Do not mechanically insert a new section or cut an incomplete definition just because a page ended.

    3.3 Repair Line Breaks Without Damaging Technical Symbols

    A visual line break in a PDF does not necessarily mean the end of a paragraph. Ordinary paragraphs can be joined semantically, but code, formulas, lists, and field definitions should keep their own structure.

    Content that especially needs protection:

    • hexadecimal values and addresses;
    • bit ranges and bit masks;
    • underscores inside field names;
    • signs, comparison operators, and units;
    • code indentation;
    • hyphens inside identifiers.

    A hyphen at the end of an English line may be typesetting hyphenation, or it may be part of a legitimate identifier. When the two cannot be reliably distinguished, keep the original text and flag the uncertainty rather than deleting the hyphen unconditionally.

    4. Removing Headers, Watermarks, and Footers: Use Layout Patterns, Not Keyword Guessing

    Repeated text consumes model context and can also bias retrieval toward useless content. But overly aggressive cleaning rules will delete important warnings, version notes, or confidentiality markings.

    Header and footer detection should combine multiple signals:

    • whether the text appears at a similar position on multiple pages;
    • whether it sits outside the body region;
    • whether it has a stable font, size, or alignment;
    • whether it consists mainly of page numbers, short titles, or fixed statements.

    Watermarks are more complex. Text watermarks may show rotation, repeated overlay, and unusual placement; image watermarks may be fused with scanned body content and cannot be solved by deleting text objects alone.

    Use a tiered strategy: remove high-confidence noise automatically, and send disputed regions to a review queue. Confidentiality statements can be moved out of the repeated body text, but they should be preserved in document metadata. Removing repeated content does not remove access control, and it certainly does not mean the document may be distributed publicly.

    5. Image Parsing: Preserve Visual Evidence, Separate Description from Inference

    Missing images cannot be blamed on any single underlying parsing method. Visual content in a PDF may be an embedded bitmap, or a combination of lines, text, and vector graphics. Whether the conversion pipeline supports these objects, whether it outputs asset files, and whether it associates captions all affect the result.

    5.1 Choose an Extraction Method per Object Type

    For embedded bitmaps, save the original image asset. For block diagrams or timing diagrams built from vector objects, extracting bitmap assets alone may not yield the complete content; in that case, render the corresponding page region and produce a standalone viewable image.

    Region capture must retain edge labels, legends, and annotations. Avoid capturing only the graphical body while losing the explanatory text that determines the meaning.

    5.2 Keep the Caption and the Source

    An image reference in Markdown should appear together with its caption, for example:

    1. ### 4.2 Data Transfer Path
    2. ![Data transfer path diagram](assets/figure_0042.png)
    3. Figure 4-2: Data transfer path. Source: page 86 of the document.

    The file name and content here are illustrative only.

    Note that an image link does not guarantee the model has understood the image. A text-only model may be unable to read the image asset, and a model with vision capability still needs to actually receive the image as input.

    5.3 Clearly Separate Supplementary Notes from the Original Text

    If you add machine-generated descriptions for an image, mark them separately and avoid presenting them as conclusions of the original document. For module connections, signal directions, timing relationships, and formulas, keep the original image for verification.

    When key register attributes, signal polarity, or hardware constraints are involved, do not fill in missing facts based on an image description alone.

    6. Table Parsing: Keep Field Relationships Intact

    The value of a technical table comes from the relationships between cells, not from the characters alone. Borderless tables rely on alignment and spacing to organize information, so they are usually harder to recover than regular grid tables.

    6.1 Combine Geometric and Semantic Signals

    Candidate table regions can be identified through column alignment, row spacing, repeated text patterns, and field types. In register tables, bit ranges, field names, access attributes, and reset values often have relatively stable distributions.

    These patterns only support detection; they must not be used to invent values. For example, a gap in bit ranges must not be declared a reserved field without verification, and a failed reset-value extraction must not default to zero.

    6.2 Use Markdown for Simple Tables, Keep Structural Data for Complex Ones

    A regular table can be expressed as:

    1. | Bit range | Field | Access | Reset value | Description |
    2. |---|---|---|---|---|
    3. | 3:0 | MODE | R/W | 0 | Work mode selection |
    4. | 7:4 | RESERVED | Reserved | Not stated | Handle per original constraints |

    For merged cells, nested headers, or complex tables spanning pages, pure Markdown may not express everything. You can additionally store two-dimensional cell data, merge relationships, and a screenshot of the original region, then provide a summary and an asset reference in Markdown.

    When merging across pages, check the table caption, column structure, and continuation markers. Do not merge just because adjacent pages have the same number of columns.

    6.3 Validate Tables Separately

    Key checks:

    • whether row or column counts change abnormally;
    • whether headers correspond to the data columns;
    • whether bit ranges show suspicious overlaps;
    • whether values contain obvious recognition errors;
    • whether reset values are inconsistent with field widths;
    • whether fields clearly present in the original are missing.

    These checks locate uncertainties; they do not automatically modify document facts.

    7. Web Parsing: Extract Main Content and Recover Semantic Structure

    Web pages usually have fairly explicit element structure, but extracting the whole page text still pulls in menus, footers, recommended content, and interactive controls.

    7.1 Confirm the Content Is Complete First

    Some pages include the body in the initial response; others display content only after scripts execute. Before parsing, determine whether page rendering is required and check whether the body has actually finished loading.

    For pages that require permission, respect the authorization scope and access policy. Do not bypass authentication or other access restrictions.

    7.2 Identify the Main Content Region

    The body range can be judged from paragraph density, link ratio, heading distribution, and element semantics. But in technical documentation, tables of contents, code blocks, and parameter tables may also have unusual density, so “many links” or “short body text” must not be treated as invalid content.

    A safer approach is to locate the main content container first, then remove clear navigation and decorative regions while keeping in-body section indexes and cross-references.

    7.3 Preserve Key Semantics

    The conversion should keep heading levels, ordered and unordered lists, code blocks, tables, image captions, and in-body links. Code content needs protection against lost indentation and escaping errors; relative asset addresses should be resolved against the page source and handled according to the storage policy.

    Whether collapsed notes, paginated content, and embedded regions are included needs explicit rules. Different crawl times on a dynamic page can produce different results, so record the acquisition time and content version.

    8. Structure-Aware Chunking for Retrieval-Augmented Generation

    After Markdown is produced, blindly splitting by a fixed character count will cancel out the benefits of structured conversion.

    A better approach is to split by section and semantic unit first, then subdivide units that are too long:

    • keep a heading together with the explanation that immediately follows it;
    • keep a register entry’s name, address, field table, and access constraints together;
    • when a table is too long, group rows and repeat the header for each group;
    • keep the caption, the original explanation, and the image reference in the same chunk;
    • do not separate a caution from the object it constrains.

    Each chunk should carry the document identifier, version, section path, source location, and parsing status. Retrieval results should not only provide content but also answer “which version of the material, which page, or which section did this come from.”

    For exact queries on addresses, field names, and bit ranges, semantic vectors alone may be insufficient. Combining keyword retrieval with semantic retrieval, then filtering results by source reliability and context completeness, works better. Model answers should cite evidence; when evidence is incomplete, uncertainty should be stated explicitly.

    9. Quality Acceptance and Engineering Deployment

    A successful conversion does not mean a reliable result. Build acceptance checks around these dimensions:

    1. Text coverage: whether body text, notes, or appendices are missing.
    2. Reading order: whether multi-column content and cross-page paragraphs are joined correctly.
    3. Structure fidelity: whether heading levels, table column relationships, and code indentation are preserved.
    4. Image coverage: whether key diagrams have asset files, captions, and sources.
    5. Noise control: whether repeated navigation, headers, and watermarks are effectively isolated.
    6. Source traceability: whether a chunk can return to the original evidence.
    7. Usage outcome: whether real retrieval questions find the correct clause.

    Sampling should cover scanned pages, two-column pages, borderless tables, cross-page tables, and complex diagrams, not just pages that are easy to parse. For low-quality results, allow manual correction and reprocessing of the affected parts.

    In engineering terms, also retain the original files, parsing results, asset attachments, and the version of the processing rules. Large documents can be processed page by page or section by section, then the section tree and cross-page relationships restored. When parallel execution is needed, keep stable identifiers so output order does not depend on task completion order.

    For restricted material, converted files, image attachments, and retrieval indexes should all inherit the permission requirements of the original document, with clear boundaries for storage, logging, backups, and external model calls.

    10. Conclusion

    Converting PDFs and web pages to Markdown is essentially a document structure recovery effort. A reliable solution cannot stop at character extraction; it must handle reading order, image evidence, table relationships, noise filtering, and source traceability at the same time.

    For high-precision material such as chip specifications, follow one core principle: it is better to keep an uncertainty and request review than to produce content that looks clean but is distorted. On that basis, structure-aware chunking, precise retrieval, and evidence citation are what genuinely improve the trustworthiness of large language models working with technical documents.