Document Conversion for LLMs: Preserving Structure Across File Formats

    Converting PDFs, word-processing documents, presentations, and web content into Markdown can preserve the structure needed for reliable retrieval, summarization, and question answering. This article outlines a six-step preprocessing pipeline, explains format-specific challenges, and covers quality checks, security controls, and the limits of text conversion for images and audio.

    Uploading PDFs, word-processing documents, and presentations directly to a large language model may seem convenient, but document structure often gets lost at the first step. Multi-column text becomes interleaved sentences, headers and footers repeatedly interrupt the body, tables turn into unaligned cells, heading hierarchies disappear, and lists collapse into ordinary paragraphs.

    The model does not necessarily receive the original layout as a reader sees it. Its input may consist of extracted text segments and positional information. The less coherent that input is, the more likely retrieval, summarization, and question answering are to associate information with the wrong context.

    A more reliable approach is to convert documents into a lightweight structured representation, such as Markdown, before passing them to the model. Headings preserve hierarchy, lists express parallel items, and table syntax retains row and column relationships. Layout noise can then be handled during conversion rather than left for the model to interpret.

    Why Use Markdown?

    Markdown is an intermediate representation that both people and models can read, not a final typesetting format. Its limited syntax keeps ambiguity relatively manageable and makes version comparison, manual review, and downstream chunking easier.

    Headings can become section paths during retrieval. Tables can preserve the relationship between column names and cell values. Code blocks and quotations remain distinguishable from surrounding prose. For retrieval-augmented generation (RAG), this also provides a practical benefit: the same representation can support human review and serve as indexing text, without maintaining two entirely different extraction outputs.

    The boundary matters. Conversion aims to preserve usable semantic structure, not high-fidelity print layout. Fonts, exact coordinates, complex text boxes, decorative lettering, and strict pagination are generally outside its scope. If a workflow requires pixel-level reproduction, retain the original file or use a dedicated layout pipeline rather than expecting a plain-text intermediate format to reproduce a designed document.

    A Practical Six-Step Pipeline

    The workflow can be divided into six stages, each producing an output that can be inspected.

    1. Ingest and Register Files

    Record the source, file format, page or slide count, encryption status, and presence of scanned pages.

    Files can first be placed in object storage and processed asynchronously through a task queue, so large documents do not block online requests. General-purpose object storage, message queues, and logging services can support the basic upload–convert–write-back workflow without tying conversion to a proprietary API.

    2. Identify the Document Type

    Do not rely on the filename extension alone. Word-processing documents, presentations, fixed-layout documents, web pages, and e-books have different internal structures. Some primarily encode styles and outlines, others drawing instructions and coordinates, and others a tree of markup elements.

    If identification fails, return a clear error rather than attempting a speculative conversion. Fluent-looking text with the wrong reading order is not a successful result.

    3. Extract Text and Structure

    Prefer direct text extraction when a usable text layer exists. Use optical character recognition (OCR) for scanned or image-based pages.

    During extraction, retain reading order, style hierarchy, and table regions. Presentations should be exported in slide order, with speaker notes separated from slide content so that notes do not accidentally enter material intended for external readers.

    4. Reconstruct Structure

    Map heading styles to Markdown headings, bullets to lists, and recognized tables to table syntax.

    Merge paragraphs split across pages, and remove repeated headers, footers, and page numbers. Label suspected tables of contents, footnotes, and watermarks separately rather than indiscriminately appending them to the body text.

    5. Clean and Normalize

    Normalize whitespace, punctuation, and line breaks. Repair common words split by line-end hyphenation, but do not rewrite technical terminology.

    Assign stable anchors or paths to sections, such as “Chapter 2 / Section 2.3,” to support downstream references.

    6. Chunk, Add Metadata, and Check Quality

    Split content at heading boundaries. Place oversized tables in separate chunks while retaining their headers.

    Attach the filename, section, and page number or slide number to each chunk. At a minimum, quality checks should verify that:

    • The heading sequence is coherent.
    • Sampled tables retain correct row and column alignment.
    • Randomly selected paragraphs can still be located in the source document.

    The intermediate output does not need to depend on a particular command-line tool. Clearly defined formatting conventions are sufficient:

    1. # Document Title
    2. - Source: Internal Policy
    3. - Section Path: General Provisions / Scope
    4. ## Scope
    5. Body text...
    6. | Item | Condition | Description |
    7. | --- | --- | --- |
    8. | A | ... | ... |

    Challenges by Document Type

    Fixed-Layout Documents

    Fixed-layout documents are particularly prone to conversion errors. When a text layer exists, the main challenges are multiple columns, floating text boxes, and reading order. Without a text layer, the challenges shift to recognition errors and table-line detection.

    Financial tables, tables with headers spanning pages, and merged cells cannot be handled reliably by simply scanning left to right and top to bottom. Reconstruct table regions separately from ordinary paragraphs. Mark regions with uncertain row and column relationships as low confidence so they can be reviewed manually or handled by downstream rules.

    Word-Processing Documents

    Document styles are often more reliable than visual appearance. Actual heading styles should take precedence over heuristics such as larger or bold text. Otherwise, tables of contents, cover text, and emphasized sentences may be incorrectly promoted to headings, distorting chunk boundaries.

    Comments, tracked changes, and hidden text should generally be excluded from the model-facing body unless the workflow explicitly requires review history.

    Presentations

    Presentations often have low text density and highly flexible layouts. Text boxes on the same slide have no inherent reading order, while diagrams and arrows encode relationships that are difficult to express as sentences.

    The conversion target should be a clear text outline for each slide, not a recreation of its visual design. Complex diagrams can retain a placeholder such as “This slide contains a flowchart; text extraction is incomplete.” This helps prevent the model from treating disconnected labels as a complete process.

    Web Pages and E-Books

    Web pages and e-books generally provide better structure, but navigation, advertisements, recommended reading, and repeated site footers still need to be removed. Keep the main content so that template text does not overwhelm the index.

    Images, Audio, and External Recognition Services

    A converter typically handles existing text and basic structure. Diagrams embedded in images, scanned stamps, complex formulas, recordings, and video soundtracks do not become accurate simply through a text export.

    Image understanding, formula recognition, and speech transcription are separate capabilities. They often require dedicated recognition services and may involve external network calls.

    Before deployment, define:

    • Which pages may be sent to an external recognition service.
    • Whether recognition failures leave content blank or block processing.
    • Whether recognition results are written back into the document representation for review.

    A file converted to Markdown should not be treated as proof that every image or recording within it has been correctly interpreted.

    Quality, Security, and Downstream Use

    Keep the Original as Evidence

    Maintain two representations: the original file as evidence and Markdown as model input. Answer citations should be traceable to sections and page numbers.

    For critical policies, contracts, and reports, increase manual sampling, focusing on numbers, negations, and tables. Maintain a small set of fixed test documents and rerun them whenever conversion rules or recognition components change to detect silent regressions.

    Protect Data Throughout Conversion

    The conversion pipeline has access to the full document. Before upload, remove unnecessary hidden content, revision history, and personal information. Limit storage and logs to fields needed for troubleshooting, and require approval based on data classification before sending content to external recognition services.

    Prompts should not encourage the model to invent tables when structure is missing. A system prompt can explicitly require the model to state that evidence is insufficient when a retrieved segment is marked low confidence or contains an incomplete table.

    Treat Markdown as a Preprocessing Output

    When connecting converted content to a question-answering system or knowledge base, treat Markdown as a preprocessing artifact, not the sole source of truth.

    After retrieval, use section paths to organize context and pass tables as complete units where possible. Avoid splitting a table row into two chunks merely to meet a fixed character count. These practices carry the benefits of structure preservation through to the final answer rather than stopping at a file that can be opened.

    Conclusion

    Structured conversion before LLM ingestion preserves the headings, lists, and tables that provide a useful foundation for reasoning. It does not replace high-fidelity layout rendering or specialized image and audio recognition.

    An observable pipeline covering ingestion, extraction, reconstruction, normalization, chunking, and quality assurance is more likely to produce an engineering-ready result than an attempt at a perfect one-shot export.