Local PDF to Markdown: A Practical Guide for Technical Documents and RAG Pipelines
This guide explains how to convert local PDFs—including image-based PDFs and scans—into Markdown using a combination of PyMuPDF, layout analysis, OCR, and table recognition. It compares common tools, shows how to separate text and images with reading-order reconstruction, restore two-column layouts, render and OCR scanned pages, rebuild tables into GitHub Flavored Markdown, and optimize the output as RAG corpus with chunking and metadata. It also covers risks, compliance, and licensing considerations so technical documents become more searchable and better connected in a local knowledge base.
TL;DR: The Minimum Viable Approach
When importing technical documentation into a local knowledge base, converting PDFs to Markdown (including image-based PDFs and scans) usually requires a combination of PyMuPDF + layout analysis + OCR + table recognition. If the PDF is text-based and the images are clear, prefer using PyMuPDF to extract text blocks, image objects, and coordinates. If it is a scan or image-based PDF, first render each page to a 200–300 DPI image with PyMuPDF, then hand it off to a local OCR engine. For complex tables such as register maps and package dimension tables, try a table recognition tool first; if that fails, keep a screenshot of the original PDF and degrade the table to key-value text.
This approach can significantly improve the readability of the Markdown and the quality of RAG retrieval, but it does not guarantee lossless reconstruction for every complex layout, handwriting, or low-quality scan.
Tool Selection: Don’t Expect a Single Library to Do Everything
PDF documents vary widely, and a single tool often performs well on only one of: text extraction, image export, scan recognition, or complex table reconstruction. You can evaluate options along these dimensions.
| Tool / Approach | Text Extraction | Image Export | Scanned OCR | Complex Tables | Fully Local | License / Compliance Notes |
|---|---|---|---|---|---|---|
| PyMuPDF | Strong | Strong, export by xref | Needs OCR | find_tables can attempt | Yes | AGPL / commercial dual license, verify for commercial use |
| pdfplumber | Strong, preserves coordinates | Can enumerate/extract image objects | No | extract_table works, limited for complex merged cells | Yes | See project repository declaration |
| PaddleOCR / PP-Structure | Assistive | Weaker | Strong, good for Chinese print text | PP-Structure handles layout and tables | Yes | Mostly Apache-2.0, models declared separately |
| MinerU | Strong | Fairly strong | Can handle | Fairly strong | Can run locally | License and commercial terms per repository |
Selection recommendations:
- Text-based chip datasheets: use PyMuPDF to separate text and images, and pdfplumber to fill in tables.
- Scans or image-based PDFs: PaddleOCR, RapidOCR, or Tesseract.
- Complex layouts, papers, multi-column tables: consider MinerU or PaddleOCR/PP-Structure.
- Privacy-sensitive restricted documents: prefer local models and keep a backup of the original PDF.
1. Separating Text and Images: Extract Images and Insert Anchors
Many failures aren’t caused by a tool being unable to convert at all, but by text and images being naively stacked together, which misplaces images. The correct approach is to first extract all candidate elements on a page—both text blocks and image rectangles—and then merge and output them in reading order. For a two-column datasheet, you cannot simply sort by the y-axis; instead, split the page into left-column, right-column, or spanning elements, then sort each separately.
pdfplumber provides capabilities such as page.images, extract_images(), and extract_table(), and can enumerate image objects and extract tables. However, coordinate sorting, image anchoring, caption matching, and semantic reconstruction usually still need to be implemented yourself. PyMuPDF, built on the MuPDF core, is well suited for quickly extracting text blocks, image xrefs, and rectangle coordinates.
It is recommended to use Python 3.9 or newer:
python -m pip install pymupdf
In newer versions of PyMuPDF, prefer:
import pymupdf
rather than the legacy import fitz style. The logic below generates text and image candidates in reading order and produces local files plus Markdown references for images.
import pymupdffrom pathlib import Pathdef pdf_to_md(pdf_path: str, out_dir: str = "assets"):out = Path(out_dir)out.mkdir(parents=True, exist_ok=True)doc = pymupdf.open(pdf_path)md = []cache = {}for pno, page in enumerate(doc, 1):items = []# Collect image candidates and compute their bounding boxes on the pagefor img in page.get_images(full=True):xref = img[0]for rect in page.get_image_rects(xref):items.append({"kind": "img","bbox": rect,"xref": xref})# Collect text block candidatesfor b in page.get_text("blocks"):rect = pymupdf.Rect(b[:4])text = b[4].strip()if text:items.append({"kind": "text","bbox": rect,"text": text})# Simple two-column split: decide left/right by the page midlinemid = page.rect.width / 2left, right = [], []for it in items:r = it["bbox"]# Headers, titles, and large images crossing the midline are not splitif r.x0 < mid < r.x1 and (r.height > 30 or r.y0 < 80):it["lane"] = 0else:it["lane"] = 0 if r.x1 <= mid else 1if it["lane"] == 0:left.append(it)else:right.append(it)left.sort(key=lambda x: (round(x["bbox"].y0, 1), x["bbox"].x0))right.sort(key=lambda x: (round(x["bbox"].y0, 1), x["bbox"].x0))ordered = left + rightfor it in ordered:if it["kind"] == "img":xref = it["xref"]# Optional: filter out full-page backgrounds or oversized decorative imagesr = it["bbox"]if r.get_area() > page.rect.get_area() * 0.85:continueif xref not in cache:info = doc.extract_image(xref)name = f"p{pno}_x{xref}.{info['ext']}"(out / name).write_bytes(info["image"])cache[xref] = namename = cache[xref]md.append(f"")else:md.append(it["text"])md.append(f"\n<!-- page {pno} -->\n")return "\n".join(md)
Anchoring isn’t just about dumping images into a folder. A more reliable approach is to generate a stable filename for each image, such as p{page}_x{xref}.{ext}, and then look for caption text nearby, such as “Figure 1-1” or “Figure 5-3”. If a caption is found, use it as the image’s alt text or title; if not, use the page number and a sequence placeholder. This avoids the semantic confusion caused by simply concatenating “figure number + coordinates.”
You should also export the same xref only once to avoid duplicating the same image across multiple pages. Oversized background images, header decorations, and transparent watermarks should be filtered or flagged separately, otherwise they will be mistaken for figures.
2. Layout Analysis: Restoring Two-Column Reading Order
Text coordinates in a PDF are absolute coordinates, not reading order. Chip datasheets commonly contain two columns, headers and footers, captions, notes, and margin annotations. If you sort directly by coordinates, the bottom of the left column may come before the top of the right column.
A practical processing flow is:
- Detect whether the page is columnar. If there is a wide blank gutter in the middle, or the left and right text blocks are clearly distributed, enter two-column mode.
- Classify text blocks and image blocks into header, footer, body, caption, table, and note.
- Sort the left column top-to-bottom, left-to-right, then sort the right column top-to-bottom, left-to-right.
- Handle spanning titles, spanning tables, and large top images separately so they aren’t wrongly forced into a single column.
- Filter out repeated headers, page numbers, copyright notices, company logo text, and other noise.
In Markdown, you can keep section headings and convert headers/footers into comments or delete them. For example:
<!-- page 12 -->## 6.3 Interrupt Controller...
3. OCR and Formulas: Render Before Recognizing Scanned Pages
For scans, image-based PDFs, or text embedded inside images, relying on text extraction alone yields blank output. In this case, first render the page to an image with PyMuPDF, then pass it to OCR. A recommended DPI range is 200–300: 200 DPI is faster, while 300 DPI is better for small text and complex tables but produces larger files and takes more time.
Optional local OCR frameworks:
| Framework | Installation | Model Download | Chinese/English Quality | License Notes |
|---|---|---|---|---|
| PaddleOCR | pip install paddlepaddle paddleocr |
Auto-downloaded on first run, or pull models with the official command | Balanced for Chinese print text and layout recognition | Mostly Apache-2.0; models and training data must be verified separately |
| RapidOCR | pip install rapidocr_onnxruntime |
Obtained from the package or on first run (ONNX models) | Lightweight, CPU-friendly, usable for everyday Chinese recognition | Per repository and model declarations |
| Tesseract | sudo apt install tesseract-ocr tesseract-ocr-chi-sim or brew install tesseract tesseract-lang, plus pip install pytesseract |
Installed via system language packs | General-purpose and multilingual; engineering docs need dictionaries and post-processing | Per repository and language pack declarations |
As for resource requirements, a CPU can generally run lightweight OCR, but complex layouts and PP-Structure are recommended with 16GB of memory; if you use a GPU, it is advisable to reserve more than 6GB of VRAM. For large volumes of datasheets, it is recommended to batch-render first and spot-check a sample before deciding whether to run OCR on everything.
For engineering documents, ordinary OCR tends to misrecognize pin names, register names, and part-number suffixes. You can add a custom dictionary—for example VCC, GND, I2C_SDA, CLK, RESET—and correct errors in the post-processing stage. For text inside timing diagrams and logic block diagrams, you can first extract connected regions in the image, exclude thick lines and borders, then OCR the candidate text regions separately, and finally append them as a plain-text list below the image’s Markdown reference.
4. Table Recognition: Rebuild GFM and Keep Attachments
Register tables are an important source of information in datasheets. OCR alone tends to misalign columns, so prefer structured table recognition. Newer versions of PyMuPDF support page.find_tables(), and pdfplumber supports page.extract_table(). If the recognition result is stable, convert it to GitHub Flavored Markdown; if merged cells or cross-page headers leave the structure incomplete, degrade it to key-value pairs and keep a screenshot of the original PDF or an HTML attachment.
import pdfplumberdef table_to_md(table):if not table or len(table) < 2:return ""header = table[0]rows = table[1:]# Inconsistent column counts usually mean merged cells, footnotes, or caption misclassificationif any(len(r) != len(header) for r in rows):lines = []for r in rows:cells = [str(c or "").replace("\n", " ") for c in r]if len(cells) == 1:lines.append(cells[0])else:kv = []for j, cell in enumerate(cells):key = header[j] if j < len(header) and header[j] else f"Col{j+1}"kv.append(f"{key}: {cell}")lines.append("- " + "; ".join(kv))return "\n".join(lines)clean_header = [str(c or "").replace("\n", " ").replace("|", "\\|") for c in header]lines = ["| " + " | ".join(clean_header) + " |","| " + " | ".join("---" for _ in header) + " |"]for r in rows:cells = [str(c or "").replace("\n", " ").replace("|", "\\|") for c in r]lines.append("| " + " | ".join(cells) + " |")return "\n".join(lines)
Table conversion needs additional rules:
- Cross-page tables: if the first row of the table on the second page matches the previous page’s header, you can reuse that header; otherwise, keep the original header note.
- Merged cells: if Rowspan/Colspan cannot be expressed accurately, degrade to “column name: value” key-value pairs to avoid column misalignment in Markdown tables.
- Caption or footnote misclassification: if a row has only a single column, has overly long text, and is located near an image area, it is usually not a data cell and should be converted to a paragraph or footnote.
- High-risk tables: register bit definitions, timing parameters, and pin definitions should keep a screenshot of the original PDF page, linked as an attachment in Markdown.
5. RAG Corpus Optimization: Chunking and Metadata Injection
Once the Markdown is generated, it still needs optimization for RAG retrieval. It is recommended to chunk by H1/H2/H3 headings and inject metadata before or after each chunk. For example:
<!--source: example_datasheet.pdfpage: 142chapter: 6.3 Interrupt Controller-->### 6.3.1 Interrupt Mask Register (IMASK)...
HTML comments are invisible in most Markdown renderers, but compatibility varies across renderers. If you need to force the content to display, you can switch to a blockquote or Frontmatter fields. Metadata fields should at minimum include the source file, page number, chapter, and figure/table number, making it easy to backfill context during retrieval.
Common bidirectional-link problems also need to be handled:
- Inconsistent anchor naming rules cause
[4.2.1]to miss. It is recommended to use the section number consistently as the anchor name. - Image filenames become disconnected from Figure numbers. It is recommended that filenames include the page number, figure number, and xref, for example
p12_fig5-3_x123.png. - Same-named chapters across documents collide. It is recommended to add a document prefix to links, for example
[[docA:6.3]].
Risks and Compliance Notes
- Converting and redistributing third-party datasheets, restricted technical manuals, and patent documents should be premised on the scope of authorization and copyright. Before ingestion, confirm whether internal retrieval is permitted and whether uploading to cloud services is permitted.
- Before feeding sensitive datasheets to cloud-based large models, prefer local models, or first perform redaction, summarization, or partial fragmentation; do not upload the full restricted document directly.
- PyMuPDF uses an AGPL / commercial dual license. If your project requires closed-source distribution, SaaS deployment, or commercial integration, verify the license obligations in advance and obtain a commercial license if necessary.
- Always back up the original PDF before conversion. Markdown conversion is a lossy process, and the original file is the basis for troubleshooting and manual review.
- Spot-check before ingestion: whether images are missing, whether captions correspond correctly, whether table column counts are consistent, whether headers/footers have leaked into the body, and whether section numbers are duplicated.
FAQ: Can Scanned PDFs Be Converted to Markdown?
Yes, but the result depends on clarity, layout complexity, and whether OCR is introduced. A completely blank scan with no text information can only rely on OCR or manual entry; ordinary print scans combined with local OCR usually yield usable Markdown.
How to choose tools? For text-based documents, prefer PyMuPDF; for complex tables, use pdfplumber or find_tables; for scans, use PaddleOCR, RapidOCR, or Tesseract; for complex layouts, consider MinerU or PP-Structure.
What if tables are garbled? First check whether there are merged cells or cross-page headers; if table recognition is unstable, keep a screenshot of the original PDF and convert key content to key-value pairs. How are images and captions preserved? Use image rectangle coordinates to determine anchors, use caption text as alt text, and make the filename include the page number, figure number, and xref.
Summary
Local PDF to Markdown is not about relying on a single “one-click silver bullet,” but is a systems engineering effort: use PyMuPDF to separate text and images and sort coordinates, use layout analysis to restore two-column reading order, use local OCR to handle scans and text within images, use table recognition to rebuild register tables, and then optimize the RAG corpus with metadata, chunking, and bidirectional links. As long as you combine these steps sensibly and retain spot-checking and compliance processes, technical documents in your local knowledge base become more searchable and better connected, and the context quality for AI-assisted reading and code generation improves significantly.
