Parsing PDFs and Web Pages into Markdown: A Practical Guide for RAG Knowledge Bases
This article walks through a practical pipeline for converting PDF documents and web pages into structured Markdown, with a focus on engineering specifications such as processor architecture notes, chip datasheets, and configuration standards. It explains why layout fidelity matters for retrieval-augmented generation (RAG), the three main failure modes of generic converters (missing graphics, watermark and header noise, unstable table detection), and a staged workflow covering layout normalization, watermark removal, repeated-noise filtering, reading-order reconstruction, table rebuilding, image extraction, and symmetric handling of web content. It also covers chunking and indexing advice for large language models, an automated quality checklist, and current limitations. Readers will gain a repeatable approach to building a local, searchable technical knowledge base.
1. Why Convert Specification Documents to Markdown
In firmware, driver, and chip bring-up work, teams deal with long technical documents every day: processor architecture notes, chip datasheets, extension configuration specifications, and similar material. These documents are usually distributed as PDFs, often hundreds or even thousands of pages long, with dense register bit-field tables, instruction encoding tables, and system block diagrams inside. PDF works well for final layout and printing, but poorly for reprocessing: the text layer often contains broken lines and overlapping glyphs, tables fall apart when copied, and cross-document search and link navigation are a poor experience.
More importantly, large language models do not handle this kind of layout well. The quality of retrieval-augmented generation (RAG) depends heavily on chunking and vectorization quality, and chunking quality in turn depends on whether the document structure has been faithfully restored. If raw PDF text is extracted and pushed straight into a vector store, lost heading hierarchy, tables flattened into a single line, and figure captions misaligned with body text all produce semantically incomplete retrieved fragments, which ultimately hurts generation accuracy. Converting PDFs and web pages into structured Markdown is therefore a prerequisite step for building a local knowledge base.
Markdown is valuable for three reasons: it is plain text, it can be version controlled, and its structure carries explicit semantics. Heading levels, lists, code blocks, tables, and image references can all be reliably recognized by parsers, which makes the content easy for people to read and cross-link, and easy for programs to split semantically along heading boundaries.
2. Core Pain Points in Parsing Quality
Common general-purpose conversion tools perform acceptably on office documents, but on engineering specifications three typical problems appear.
The first is a complete loss of graphical information. Some solutions rely on text extraction libraries with limited image support; even with embedded-data output enabled, they cannot export architecture diagrams or timing diagrams as separate files, so the most critical information in the document is discarded.
The second is noise text mixed into the body. Confidential documents are often overlaid with diagonal watermarks, and once watermark characters overlap the body text they generate large amounts of meaningless fragments. Meanwhile, headers, footers, page numbers, and revision numbers on every page repeat continuously, diluting useful information and interfering with the embedding model’s semantic judgment.
The third is unstable table recognition. Tables in engineering documents frequently use borderless or partially bordered styles, and merged cells are common, so recognition results come down to luck: for the same document, a register bit-field table is sometimes restored as a proper table and sometimes degrades into ordinary paragraphs.
3. A Practical Processing Pipeline
A robust conversion flow should be split into multiple observable, rollback-friendly stages, with each stage emitting intermediate artifacts for troubleshooting.
3.1 Layout Normalization and Watermark Removal
Start with layout analysis of each page, separating the body area, the margin area, and the overlay layer. Watermarks typically have a fixed angle, a fixed font size, and a repeating pattern, so they can be located and removed through text-direction clustering and repetition statistics; for scanned watermarks, differences between color channels can help suppress them. Keeping the original coordinate information at this stage is recommended, since later table and image localization can reuse it.
3.2 Filtering Headers, Footers, and Repeated Noise
Cross-page comparison is the most effective way to filter headers and footers: count where each text block appears in the document and how often. If a fragment repeats in the same relative position on the vast majority of pages, treat it as layout noise. Filtering rules should be configurable to avoid deleting glossary headers or other terms that legitimately repeat in the body.
3.3 Reconstructing Reading Order
The text stream order in a PDF often disagrees with the visual reading order, which is especially obvious with two-column layouts and tables continued across pages. Build a directed graph from block-level coordinates, cluster by column first and then sort by vertical position, and emit a single linear sequence. This step directly determines whether heading levels and paragraph ownership are correct.
3.4 Mixed Table Detection and Structure Restoration
Table recognition is best handled with a two-stage “detect first, then rebuild” strategy: first use line and whitespace distribution to identify table regions and whether they are borderless, then infer row and column boundaries from cell spacing, and finally handle the row and column spans of merged cells. Output should keep standard Markdown table syntax; for bit-field tables with too many columns or too much nesting, split them into a “field name - bit width - description” list structure that serves both machine parsing and human reading.
# Example: normalized output after table structure restorationdef normalize_table(rows):header, body = rows[0], rows[1:]cols = len(header)lines = ["| " + " | ".join(header) + " |","| " + " | ".join(["---"] * cols) + " |"]for r in body:r = (r + [""] * cols)[:cols] # pad/truncate to keep the column count consistentlines.append("| " + " | ".join(c.replace("\n", " ") for c in r) + " |")return "\n".join(lines)
3.5 Image Extraction and Local References
Crop and export the bitmaps and vector elements on each page by region, using a stable naming scheme of “document identifier + page number + sequence number”, store them in a sibling attachment directory, and reference them from the body with relative paths. In a local note-taking environment, images then preview directly and open at full size on click, with no need to switch between multiple viewers.

3.6 Symmetric Handling of Web Content
The goal for web parsing is the same structural fidelity: extract the main content container first, and strip navigation, ads, and recommendation blocks; map semantic tags to Markdown elements while preserving heading levels and lists; resolve and localize lazy-loaded image URLs; and keep the original fences and escaping for code blocks and formulas so they are not broken by a second rendering pass.
4. Chunking and Indexing Advice for Large Language Models
Once structure restoration is done, chunking should follow the principle of “heading boundaries first, length as fallback”: generate semantically complete fragments bounded by level-two and level-three headings, and when a fragment is too long, split it again by paragraph while keeping the heading path as prefix metadata. Tables and images are best treated as independent fragments with a short context note, for example “this table appears in a given chapter and describes the bit-field definition of a given register”, which compensates for the semantics a table loses when detached from the body text. Metadata should include at least the document source, chapter path, page number, and figure or table number, so fragments can be traced back and reordered.
5. Quality Validation and Engineering
An automated validation checklist is worth building: whether heading levels are continuous, whether table column counts are consistent, whether image references resolve, whether the proportion of noise characters stays below a threshold, and whether tables continued across pages were merged correctly. For batch processing, a container platform can handle parallel task scheduling, object storage can hold the original documents and attachments, and logging and monitoring with alerting can track failure rates and latency distribution; the parsing service itself can be deployed and elastically scaled on the relevant general-purpose capabilities of Baidu AI Cloud.
6. Limitations and Directions for Improvement
The current approach has boundaries in three places: complex formulas and handwritten annotations still degrade easily; extreme multi-column layouts or nested tables spanning pages need manual correction; and scanned documents depend on optical recognition quality, so low-resolution pages are hard to restore reliably. Practical directions include introducing layout models to improve region classification accuracy, using cell-level coordinates for finer table reconstruction, and building a human-review feedback loop for high-frequency documents, so that rules and models correct each other.
