Parsing PDFs and Web Pages into Markdown: A Practical Pipeline for Structured Knowledge Bases
This article presents a practical five-stage pipeline for converting PDFs and web pages into structured Markdown suitable for retrieval-augmented generation (RAG) and knowledge base ingestion. It explains why presentation consistency in PDFs comes at the cost of structural semantics, and how noise removal, structure detection, table reconstruction, image asset extraction, and semantic chunking address common retrieval degradation. The content includes engineering heuristics, code examples, quality metrics, and fallback strategies for reliable document parsing.
1. Why Structured Parsing Is the Foundation of a Knowledge Base
In firmware and low-level software development, engineers routinely work with chip specifications, extended data sheets, architecture reference manuals, and various data tables. These documents are typically distributed as PDFs, often hundreds or even thousands of pages long, densely packed with register bit-field tables, instruction encoding tables, revision history tables, microarchitecture block diagrams, interconnect topologies, and power sequencing diagrams.
The strength of PDF is “presentation consistency”: it guarantees that layout does not drift across devices. However, this consistency comes at the expense of structural semantics. Text is split into positioned fragments, line breaks are determined by layout rather than meaning, tables are broken into isolated cells, and figure captions lack a clear association with the body text. Feeding this content directly into a retrieval-augmented generation (RAG) pipeline causes three typical forms of degradation:
- Chunking boundaries fall in the middle of sentences, fragmenting semantic units;
- Embedding inputs mix in high-frequency noise such as watermarks, page numbers, and headers, diluting the topical signal;
- Tables and figures are discarded, causing a mismatch between “retrievable text” and “answerable facts.”
Therefore, the conversion goal should not be “turn a PDF into a Markdown file,” but “restore the layout into a structured document that both machines and humans can consume accurately.” This article breaks the task into a five-stage pipeline: noise cleaning → structure detection → table reconstruction → image assetization → semantic chunking and indexing.
2. Overall Pipeline Design
Raw input (PDF / HTML)↓ Normalization: unify encoding, strip scripts, preserve DOM or text layerNoise cleaning: watermarks, headers/footers, page numbers, repeated decorative text↓Structure detection: heading hierarchy, paragraphs, lists, code blocks↓Table reconstruction: unified modeling of bordered and borderless tables as matrices↓Asset extraction: images saved to disk + relative path references + caption binding↓Output: Markdown + sibling assets directory + metadata index
Three key design principles apply. First, reversibility and auditability: every cleaning step records what was removed and which rule matched, making it easy to trace erroneous deletions. Second, dual-consumer alignment: the output must be comfortable for humans to read and stable for machines to parse; when the two conflict, prioritize factual completeness. Third, graceful degradation: when confidence is insufficient at any stage, fall back to “preserve the original text + flag uncertainty” rather than silently discarding content.
3. Step 1: Removing Watermarks and Repeated Noise
Confidential documents often overlay diagonal text watermarks whose characters intersect with the body text, appearing after conversion as meaningless characters interspersed within sentences. An effective approach is not simple string replacement, but a joint decision based on geometry and frequency:
- Geometric features: watermarks typically use a larger font size, a fixed rotation angle (such as 30° or 45°), low opacity, and appear repeatedly across pages at regular positions.
- Frequency features: the same text fragment repeats at identical coordinates on the vast majority of pages, indicating a decorative layer rather than a content layer.
- Color and layer features: light gray or semi-transparent foreground that differs clearly from the main body text color.
# Illustration: noise candidate detection based on geometry and cross-page frequencydef is_noise(span, page_index, freq_map):rotated = abs(span.rotation) > 15repeated = freq_map.get(span.text, 0) > 0.8 * TOTAL_PAGESlight = span.color_luminance > 0.7return rotated and repeated and light
A conservative strategy is essential: delete only when multiple features match simultaneously, and log the action to a cleaning log. For cases where a watermark genuinely overlaps with body text, character-level coordinates can be retained, with a footnote in the output noting “possible watermark interference here,” avoiding irreversible information loss.
4. Step 2: Filtering Headers, Footers, and Layout Noise
Headers and footers typically take the form of “document title + section name + page number + classification level,” with high consistency across pages. The detection approach is to build a page-level template: compute the occurrence probability and coordinate variance of text within each vertical region (fixed-height bands at the top or bottom). Regions with high probability and low variance are identified as template areas and removed entirely.
Three types of accompanying noise also need handling: dot leaders on table-of-contents pages, repeated table headers across page breaks, and hyphenated word breaks in body text. Word-break repair should rely on dictionary and lemmatization checks—for example, a line ending in “micro-\narchitecture” is merged into “microarchitecture,” while Chinese line breaks like “位域-\n说明” are concatenated directly.
5. Step 3: Detecting and Reconstructing Mixed Tables
The difficulty with chip documentation lies in the large number of borderless tables: register bit-field tables rely on column alignment and whitespace spacing, instruction encoding tables contain merged cells, and revision history tables often continue across pages. No single detection strategy is reliably stable, so multi-signal fusion is required:
- Text-layer signals: perform column projection based on character coordinates, where blank columns form natural separators; row projection identifies row boundaries.
- Semantic signals: header keywords (such as “field,” “bits,” “description,” “default value”) and the density of units and hexadecimal constants.
- Cross-page signals: when a highly similar row structure appears at the top of an adjacent page, treat it as a continued table and concatenate.
During reconstruction, everything is abstracted into a two-dimensional matrix plus merge information, then serialized to Markdown; for complex tables with merged cells, an additional structured output (such as a list of rows) is produced for programmatic consumption.
def table_to_markdown(matrix, spans=None):header, body = matrix[0], matrix[1:]lines = ["| " + " | ".join(header) + " |","| " + " | ".join(["---"] * len(header)) + " |"]for row in body:cells = [c.replace("\n", "<br>") for c in row]lines.append("| " + " | ".join(cells) + " |")return "\n".join(lines)
Table quality must be measurable: use column-count consistency, empty-cell ratio, and cross-page continuation success rate as metrics. When values fall below thresholds, degrade to “verbatim text block + suspected table marker” to ensure no facts are lost.
6. Step 4: Image Extraction and Local Reading Experience
Block diagrams and architecture diagrams carry information absent from the text and must be assetized rather than discarded. The flow is: detect image and vector drawing regions → crop in reading order and deduplicate (keep only one copy when the same figure repeats across pages) → save to a sibling asset directory with content-hash filenames → reference via relative paths in Markdown → bind adjacent caption text as the image description.
*Figure 3-2 CPU Microarchitecture Block Diagram: shows the relationship among fetch, decode, out-of-order execution, and cache hierarchy.*
The combination of relative paths and a sibling directory allows the document to be previewed directly in local note-taking tools, with click-to-zoom, eliminating the need to switch back and forth between a PDF reader and an editor. It also brings captions into the retrieval corpus, improving hit rates for “answer from the figure” queries.
7. Step 5: From Markdown to High-Quality Retrieval
The ultimate purpose of structuring is to improve generation quality. The recommended chunking strategy is “recursive splitting by heading hierarchy + keeping tables and figures intact + moderate overlap.” Each chunk carries metadata: document source, section path, page range, and whether it contains a table or figure, enabling hybrid retrieval and citation traceability.
{"doc":"soc_spec","section":"3.2 Clock","pages":"45-47","has_table":true,"has_figure":true,"text":"..."}
For production deployment, batch conversion jobs can be scheduled by a container platform, with originals and outputs stored separately in object storage, task status and failure reasons written to a logging service, and monitoring alerts configured for parsing success rate and table accuracy. For web page input, first remove scripts and styles, collapse navigation and ad blocks, then rebuild hierarchy by headings and paragraphs; images follow the same assetization flow, allowing the web path to share the downstream index with the PDF path.
8. Limitations and Outlook
The boundaries of the current approach must be stated clearly: scanned documents without a text layer require optical recognition first, and recognition errors propagate into tables; extremely complex multi-level headers may still cause column misalignment; vector graphics with no extractable bitmap require full-page rendering and cropping. Viable directions for evolution include joint reasoning between layout models and semantic models, confidence scoring for table structures with a human review loop, and chapter-oriented incremental updates with deduplication.
By treating parsing quality as a first-class concern, PDFs and web pages can truly become retrievable, reasoning-ready, and continuously growing knowledge assets, enabling humans and models to achieve consistent and accurate understanding over the same structured document.
