PDF and Web-to-Markdown Conversion: Engineering a Reliable Parsing Pipeline
Converting technical documents to Markdown requires more than extracting text. This article examines the limitations of general-purpose PDF converters and presents a four-stage pipeline for removing watermarks, filtering headers and footers, reconstructing tables, and preserving images. It also covers quality checks, deployment considerations, and limitations when preparing engineering documentation for retrieval-augmented generation and local knowledge bases.
1. Why LLM Workflows Need Markdown Rather Than Raw PDFs
Teams developing firmware, drivers, and low-level software routinely work with chip datasheets, architecture reference manuals, and extension specifications. These documents often run to thousands of pages, arrive as PDFs, and contain dense register bit-field tables and architectural diagrams.
PDF is designed primarily for human viewing. It preserves visual layout, but that creates three structural problems for machine processing:
- Unreliable reading order. Multiple columns, floating captions, and margin notes can disrupt text extraction, splitting sentences or placing text in the wrong sequence.
- Lost table semantics. A register table is a two-dimensional semantic structure. Flattening it into text can break the relationships among bit positions, field names, reset values, and access attributes.
- Separation of text and images. Block diagrams often convey more information than the surrounding prose. When images are discarded, downstream answers may reference descriptions without retaining the visual evidence behind them.
Markdown helps address these problems through explicit heading levels, table syntax, and relative image references. For retrieval-augmented generation (RAG), this allows chunking along semantic boundaries, preserves structural signals during embedding, and improves the completeness of retrieved context.
In local-first knowledge bases with bidirectional links, images stored alongside the Markdown document can also be opened and enlarged without switching between separate readers.
2. Where General-Purpose Converters Fall Short
Many open-source conversion tools rely primarily on parsing the PDF text layer. Their output may be adequate for ordinary documents, but engineering specifications expose three recurring weaknesses.
Missing Images
A specification may contain hundreds of block diagrams and timing diagrams, yet the converted output may include none of them. Enabling an option to preserve embedded data does not necessarily help: the underlying parser may read only text and basic geometry, without adequately traversing image objects.
Watermarks and Repeated Layout Elements
Confidential documents often contain diagonal text watermarks that overlap the body text in the PDF text layer. After extraction, these can appear as interleaved characters and substantial noise.
Document identifiers and confidentiality labels in headers, along with page numbers and copyright notices in footers, may also be inserted into the output on every page. Across a long document, this produces hundreds or thousands of irrelevant lines and reduces semantic density.
Unstable Detection of Borderless Tables
Revision histories, instruction encoding tables, and register bit-field tables often use whitespace alignment rather than visible borders. Line-based detection can therefore be unreliable, and some conversion workflows produce inconsistent results across runs. This is a serious problem for knowledge bases that require reproducible builds.
General-purpose converters remain useful, but they should not be treated as a complete solution. Domain-specific preprocessing and postprocessing are needed around them.
3. A Four-Stage Parsing Pipeline
Stage 1: Remove Watermarks and Overlays
PDF watermarks often have recognizable characteristics: partial transparency, nonzero rotation, unusually large fonts, light-gray coloring, or highly repetitive text.
A practical approach combines clustering of repeated text within each page with geometric filtering:
def is_watermark(span, page_text_counter):# 1) Prioritize rotated or tilted text blocksif abs(span.angle) > 5:return True# 2) Detect oversized, low-contrast textif span.size > 60 and span.luminance > 0.85:return True# 3) Detect short strings repeated frequently on the same pageif page_text_counter[span.text] >= 3 and len(span.text) <= 12:return Truereturn False
If a document is scanned, or its watermark has been rasterized, text-layer filtering cannot remove it. An optional, more expensive path uses a layout analysis model to identify overlaid regions and perform image restoration. Measure the benefit before enabling this path broadly.
Stage 2: Filter Headers, Footers, and Repeated Layout Elements
Headers and footers are fundamentally a cross-page repetition problem. Statistical detection can replace an exhaustive collection of document-specific rules:
from collections import Counterdef detect_repeating_bands(pages, y_tol=8, ratio=0.6):top, bottom = Counter(), Counter()for page in pages:for line in page.lines:if line.y < y_tol * 2:top[normalize(line.text)] += 1elif line.y > page.height - y_tol * 2:bottom[normalize(line.text)] += 1n = len(pages)drop_top = {t for t, c in top.items() if c / n >= ratio}drop_bottom = {t for t, c in bottom.items() if c / n >= ratio}return drop_top, drop_bottom
The normalize function should replace variable components—such as page numbers, dates, and document versions—with placeholders. Otherwise, “Page 12” and “Page 13” are treated as unrelated strings and escape detection.
A repetition ratio of at least 0.6 is a practical starting threshold. An allowlist is also necessary to avoid removing legitimate repeated content, such as table headers.
Stage 3: Use Hybrid Table Detection
Reliable table recognition should combine three signals rather than depend solely on visible borders:
- Geometric cues: Text baselines within a region have very low spacing variance, and left or right boundaries align closely.
- Text alignment: Clustering token-start x-coordinates reveals distinct column positions.
- Cross-page consistency: Repeated headers and matching column structures on adjacent pages indicate a continuing table that should be joined rather than split.
Convert the result into Markdown pipe tables. Fill vertically merged cell values downward so each row remains interpretable on its own:
| Bit Field | Field Name | Access | Reset Value | Description ||-----------|------------|--------|-------------|-------------|| 31:16 | ADDR | RO | 0x0000 | Base address || 15:8 | LEN | RW | 0xFF | Transfer length |
For tables with more than 12 columns, generate an additional vertical key-value representation. Very wide tables are easily broken during chunking, while a vertical representation can provide more robust retrieval.
Stage 4: Extract Images and Rebuild References
Image extraction should not depend exclusively on a general-purpose text parser. Instead, traverse page image objects and drawing instructions directly, using three steps: region deduplication, area filtering, and caption matching.
for img in page.images:if img.width * img.height < 4096: # Filter out icons and bulletscontinueif iou(img.bbox, seen_boxes) > 0.8: # Remove duplicate image placementscontinuename = f"images/{doc_id}_p{page.no}_{idx}.png"save(img, name)caption = nearest_caption(page, img.bbox) # Match the nearest "Figure x-y" captionemit(f"")
Store images in an images directory alongside the Markdown file and reference them through relative paths. This convention supports seamless previews in local knowledge bases.
For knowledge bases backed by object storage, upload the images and write stable short URLs instead. The build pipeline should also check for broken references.
4. Operational Features and Quality Checks
A production-ready pipeline needs more than parsing logic:
- Idempotency and incremental processing: Cache intermediate artifacts using the document content hash as a key. A failure on one page should not block the entire document.
- Traceability: Attach source-page anchors to Markdown paragraphs so reviewers can verify content and trace citations.
- Structural fidelity checks: Compare output counts of headings, tables, and images with those in the source document. Raise an alert when preservation ratios fall below configured thresholds.
- Preprocessing and postprocessing hooks: Support custom terminology replacements, such as consistently expanding abbreviations to reduce ambiguity for language models.
- Batch orchestration: For large conversion workloads, use containerized execution and a task queue. Centralize logs and metrics in logging and monitoring services to make failed documents easier to diagnose.
In a Baidu AI Cloud deployment, the source describes a typical architecture using object storage for original PDFs and extracted images, a container platform for stateless conversion tasks, a message queue for task distribution, and logging and monitoring services for observability. This approach avoids maintaining a large infrastructure stack in-house.
5. Expected Results and Remaining Limitations
After the complete pipeline is applied, a thousand-page specification can have watermark noise eliminated, header and footer noise reduced by an order of magnitude, borderless tables consistently reconstructed as pipe tables, and diagrams retained together with their captions.
The immediate benefit is more structurally complete RAG retrieval. Relationships among fields, bit ranges, and reset values are less likely to be broken in the context supplied for question answering. Cleaner output also provides a stronger foundation for cross-document bidirectional links and knowledge graph construction.
The limitations remain important:
- Scanned documents and image-only pages still require OCR, and recognition errors propagate downstream.
- Complex nested tables and equations spanning multiple columns remain difficult to reconstruct.
- Layout analysis models incur substantial inference costs and are not suitable as the default path for every document.
A tiered strategy is therefore more practical: run lightweight rules first, then route documents that fail quality checks through the heavier processing path.
6. Next Steps
Three areas offer useful directions for further development.
First, layout analysis models can replace manually tuned thresholds, turning heuristics such as a repetition ratio of 0.6 into model-based decisions.
Second, richer semantic annotations can improve retrieval. For example, OCR text placed beside an image reference allows searches to match text inside diagrams.
Third, parsing quality should become part of continuous integration. Every rule change should run against a regression corpus to avoid fixing one document while breaking several others.
Reliable document conversion is a maintained engineering pipeline, not a one-off script. Treating it that way is essential to making technical documentation meaningfully usable by large language models.
