Why LLM-Generated Documents Break After Download: Root Causes and Fixes
This article explains why documents generated by large language models often break after export, covering raw markup symbols, distorted styling, and lost formulas or diagrams. It compares web document and OOXML models, then presents five practical fixes: a structured intermediate representation, a style whitelist with explicit layout parameters, editable or high-resolution formulas and charts, server-side transcoding instead of browser downloads, and an export quality validation loop. A final checklist helps teams turn unreliable output into deliverable documents.
1. Problem Overview: Three Frequent Failure Types
Across developer communities and Q&A platforms, a common workflow is to use AI coding tools to generate technical documents and then export them as office documents. The reported failures cluster into three categories:
- Raw markup symbols: Pasting a conversational answer directly into an office document leaves hash signs, asterisks, and other markup characters visible in the body text. The generation side outputs structured markup by default, while office documents do not parse this syntax.
- Broken styling after export: When a prompt asks the model to produce a page with a download button, the resulting document opens in office software with unexpected fonts, excessive line spacing, chaotic heading levels, and truncated sections.
- Missing formulas and diagrams: Mathematical formulas and flowchart source code in technical derivations become plain text or blank space after export, and cannot enter the office document’s built-in formula editor.
Based on feedback volume, the three categories roughly follow a 4
3 distribution. Formula and diagram issues are more common among technical roles, because losing this content reduces both readability and professionalism at the same time.
2. Root Cause Analysis: Why Web-to-Office Conversion Is Inherently Lossy
To understand why these failures keep recurring, compare the architecture of the two document models:
| Dimension | Web Document Model | Office Document Model (OOXML) |
|---|---|---|
| Layout | Flow layout, dependent on the browser rendering engine | Fixed page model, measured in points/twips |
| Styling | External/inline style sheets with a large number of properties | Style definitions for paragraph and character properties, relatively limited |
| Math formulas | Rendered into page nodes by a front-end formula library | A separate formula markup language |
| Diagrams | Vector graphics or canvas elements | Drawing vector markup |
| Consistency | Depends on browser version | Depends on office software version, relatively stable |
The core conflict is that in “web import mode,” office documents try to map style properties to paragraph and character properties. However, many layout properties—multiple line heights, specific Chinese font families, inner and outer margins, flex layouts—have no one-to-one equivalent in the office document specification, so they are ignored or downgraded during conversion. Two engineering realities add to this: first, when a browser triggers a download using the office document media type, what is actually passed is still markup text, which the parser handles with “fault-tolerant import”; second, model output length and page rendering timing are not controlled, so content can be truncated before it is closed.
3. Fix 1: Convert Markup Text into a Structured Intermediate State
Do not expect office documents to understand markup syntax. The correct approach is to add a “document intermediate representation” layer—for example, an object tree of structured paragraphs, headings, lists, tables, and code blocks—and then have the rendering side output either web or office documents.
# Example: parse markup text into an intermediate structure to avoid raw symbolsdef parse_to_ast(md_text):blocks, buf = [], []for line in md_text.splitlines():if line.startswith("#"):if buf: blocks.append({"type": "paragraph", "text": "\n".join(buf)}); buf = []level = len(line) - len(line.lstrip("#"))blocks.append({"type": "heading", "level": level, "text": line[level:].strip()})elif line.strip() == "":if buf: blocks.append({"type": "paragraph", "text": "\n".join(buf)}); buf = []else:buf.append(line)if buf: blocks.append({"type": "paragraph", "text": "\n".join(buf)})return blocks
With an intermediate structure, heading levels, list indentation, and code block shading can be mapped reliably, and raw symbol leakage disappears at the source.
4. Fix 2: Style Whitelist and Explicit Layout Parameters
Since layout properties cannot be mapped, explicitly declare only mappable properties. In practice, maintain a whitelist: font family and size, bold and italic, paragraph alignment, spacing before and after paragraphs, single or fixed line spacing, and table borders and shading. Remove everything outside the whitelist before export to prevent the parser from making unpredictable guesses.
/* Export-specific styles: keep only mappable properties */.doc-body { font-family: sans-serif; font-size: 11pt; line-height: 1.4; }.doc-body h1 { font-size: 18pt; font-weight: bold; margin: 12pt 0 6pt; }.doc-body table { border-collapse: collapse; }.doc-body td, .doc-body th { border: 1px solid #999; padding: 4pt; }
Change line spacing from “multiple” to “fixed value or single,” avoid declaring only a single commercial font family, reduce heading sizes by level while keeping space before greater than space after. This significantly mitigates excessive line spacing and chaotic heading levels.
5. Fix 3: Make Formulas and Diagrams Editable Objects or High-Resolution Images
The essence of missing formulas and diagrams is that page nodes cannot enter the office document’s formula editing state. There are two engineering paths:
- Convert to native office document formula markup: Convert formula source into the corresponding formula markup language and embed it in the document, preserving secondary editing capability. Suitable for derivation content.
- Pre-render as high-resolution vector graphics or images: Use a server-side rendering engine to produce images uniformly, set pixel density according to document width, and ensure no blur when scaling. Suitable for flowcharts and architecture diagrams.
At the same time, constrain the model at the prompt level: wrap formulas with consistent delimiters and declare diagram types in code blocks, so the parser can split them accurately and reduce misjudgment.
6. Fix 4: Replace Browser Downloads with Server-Side Transcoding
Browser-side downloads are limited by rendering timing and media types, so stability is insufficient. A more reliable approach is to submit content to the server, generate a compliant document with a headless rendering engine, and return a time-limited download URL through object storage. For large documents, use asynchronous tasks and message queues for decoupling, write task status and failure reasons to a logging service, and use monitoring alerts to locate timeouts and conversion failures. For batch archiving, transcoding instances can be scaled horizontally on a container platform, with elastic scaling based on queue length.
Submit content -> Parse intermediate structure -> Render with style whitelist -> Process formulas/diagrams -> Generate document -> Object storage -> Download URL
7. Fix 5: Build an Export Quality Validation Loop
An engineering solution must be measurable. Add automated validation to the pipeline: whether residual markup symbols count is zero, whether heading levels are continuous, whether table cells overflow, whether images are missing, and whether document size is abnormally small (a truncation signal). If validation fails, automatically retry or fall back to a plain text plus images version, and push sampled results to a monitoring dashboard, forming a “generate—export—validate—fix” loop.
8. Implementation Checklist
- Generation side: constrain output structure; use consistent markup for formulas and diagrams;
- Middle layer: parse into a structure tree and remove unmappable styles;
- Rendering side: whitelist styles plus explicit line spacing and font sizes;
- Server side: unified transcoding, asynchronous tasks, object storage distribution;
- Operations side: logging, monitoring alerts, quality sampling, and fallback strategies.
After this pipeline transformation, raw symbol leakage, style distortion, content truncation, and missing formulas/diagrams can all be brought under control, turning document output from “a matter of luck” into “deliverable.”
