| Module | pdf2md.py (with test_pdf2md.py) |
| Version | 1.1.0 |
| Date | 2026-11-25 |
| Authors | Another collaboration between Andrew.human and Claude.ai |
This manual is for people and for AIs. Every rule has a number and a name; the code, the tests and the summary output all use the same names.
pdf2md.py turns a PDF into Markdown and keeps as much of the look as Markdown can carry: headings, bold, italic, monospace, lists, links, tables and ruled lines.
Text only by default. Each picture's place is marked with a line like [figure p008_02] (R22). With --graphics the pictures themselves — the graphical transients — are made too, in a folder beside the .md, each saved as PNG or JPEG, whichever is smaller (R16). Markdown is plain text: lighter to store, easy to search, and far cheaper in tokens than a PDF, which is a container of positioned glyphs and drawing instructions rather than text in reading order.
What Markdown cannot carry is left out: fonts, colours, exact sizes, centring, page layout and columns. Those would need inline HTML, which the forum's Markdown parser is likely to escape and which would clutter the text for search indexing.
Every word in the result comes from the PDF itself. The optional local Qwen model is only allowed to suggest the reading order of blocks on pages with columns (rule R20) and can never add, drop or change text. After writing, the tool checks every word against the PDF (rule R21).
pymupdf or fitz), any version from 1.18 up.urllib.Features switch on by themselves according to what the machine has, and the start-up line says which are on:
| Box | PyMuPDF it can run | Table finder (R17) | Ruled lines (R18) | JPEG for graphical transients (R16) | Qwen (R20) |
|---|---|---|---|---|---|
| Live (stock glibc 2.12) | up to 1.18.19, the last build for glibc 2.12 | off — needs 1.23 | on | through Pillow, if installed; otherwise PNG only | off — Live cannot reach Clone |
| Clone (glibc 2.17 loader) | 1.23.x on Python 3.8 | on | on | through PyMuPDF itself | on, if llama-server is running |
So the full conversion is a Clone job; Live gives the same result minus tables and Qwen. Both were tested: on the 37-page test journal the two produce identical Markdown.
Copy pdf2md.py (and test_pdf2md.py, plus this manual) anywhere. No install step. Run it with the Python that has PyMuPDF, e.g. python3.8 pdf2md.py ....
To check a box before use, run the tests there (section 11).
python3.8 pdf2md.py INPUT [-o OUTPUT.md] [--graphics] [--embed] [--base-url URL]
[--no-comments] [--qwen [URL]] [--debug]
| Option | What it does |
|---|---|
INPUT |
The PDF. Checked by content, so SMF attachments with hashed names and no extension work. |
-o, --output |
Where to write the .md. Never overwritten: if taken, _2, _3 … is used (R3). |
--graphics |
Also make the graphical transients: <name>_images/pNNN_NN.png or .jpg, linked from the .md (R16). Without it the output is text only (R22). |
--embed |
Put the graphical transients inside the .md as encoded data: one self-contained file, no folder. Switches on --graphics. |
--base-url URL |
Put URL/ in front of every picture link, e.g. /pdf2md_images for a picture store on the forum. Switches on --graphics. |
--no-comments |
Leave out the hidden provenance note (R13) and page markers (R19). |
--qwen [URL] |
Ask a local llama-server Qwen for reading order on column pages (R20). Default URL http://127.0.0.1:8080. |
--debug |
Also show body size, heading sizes, every removed line, Qwen prompts and raw answers, and every word-check mismatch. |
-h, --help |
Help, with the version. |
Examples:
python3.8 pdf2md.py paper.pdf # paper.md, text only, [figure ...] markers
python3.8 pdf2md.py paper.pdf --graphics # paper.md + paper_images/
python3.8 pdf2md.py /var/www/html/attachments2/1234_3f9a1c0d77e2 -o /tmp/doc.md
python3.8 pdf2md.py paper.pdf --graphics --base-url /pdf2md_images \
-o /var/www/html/pdf2md_images/paper.md # straight into a picture store
python3.8 pdf2md.py paper.pdf --embed --no-comments # one self-contained file
python3.8 pdf2md.py paper.pdf --qwen # on Clone, with llama-server on 8080
python3.8 pdf2md.py paper.pdf --qwen http://127.0.0.1:8082 # the second copy (4b2)
Example start-up line and summary:
Text only (the default):
pdf2md v1.1.0 (2026-11-25) | PyMuPDF 1.23.26 | tables: on | ruled lines: on | graphics: off | qwen: off
pages: 37 (no text layer: none)
headings: 3 | lists: 5 | tables: 0 | ruled lines: 0
graphical transients: none made (text only) | figure markers placed: 37
running headers/footers/watermarks removed: 128 lines
column pages: none
word check: OK (12011 words in the PDF, all accounted for)
written: /home/user/mt.md
RC 0
With --graphics:
pdf2md v1.1.0 (2026-11-25) | PyMuPDF 1.23.26 | tables: on | ruled lines: on | graphics: on (PNG/JPEG via PyMuPDF) | qwen: off
pages: 37 (no text layer: none)
headings: 3 | lists: 5 | tables: 0 | ruled lines: 0
graphical transients: 37 written (PNG 25, JPEG 12) | text drawn inside them: 4 lines
running headers/footers/watermarks removed: 128 lines
column pages: none
word check: OK (12011 words in the PDF, all accounted for)
written: /home/user/mt.md
written: /home/user/mt_images/ (37 files)
RC 0
The input must contain %PDF- within its first 1024 bytes (the PDF standard allows junk before it). The file name and extension are ignored. Not a PDF, or unreadable → message, nothing written, return code 8.
Printed once, first: pdf2md v<version> (<date>) | PyMuPDF <version> | tables: on/off | ruled lines: on/off | graphics: off / on (PNG/JPEG via PyMuPDF or Pillow) / on (PNG only) | qwen: off / <url> reachable / <url> unreachable (plain mode). Usage errors and --help also show the version.
Output goes beside the input as <name>.md, or to the -o path. If that .md or its pictures folder already exists, the next free number is used for both: <name>_2.md with <name>_2_images/, then _3, and so on. Nothing is ever overwritten.
#, the next ##, the next ###; any smaller heading sizes also become ###.**…**) rather than being promoted to headings; a bold numbered line such as 1. Introduction stays a bold line, not a list.**x**, italic → *x*, bold and italic → ***x***, monospace → `x`. Taken from PyMuPDF's font flags, plus font-name hints (Bold, Italic/Oblique, Mono/Courier).``` block with its indentation kept (worked out from each line's position).Hameroff,¹, 10⁻³³). Small raised numbers that PyMuPDF filed as separate pieces are glued onto the end of the line they belong to.• ◦ ▪ ▫ ‣ · ● ○ ■ □ ► ▸ ➢ ✓ ✔) becomes - item. -, *, –, — count as bullets only when followed by a space and the line before ended a sentence (. : ! ?), or a list is already running.1. or 1) (up to 3 digits) becomes a numbered item, keeping the PDF's own number. It only counts when the line before ended a sentence, or it is the next number of a running list, so "… 2) megahertz, ⏎ 3) gigahertz" inside a sentence is not mistaken for a list.triplets-of- + triplets, a single letter like C- + termini, words ending in "ly"), and goes in all other cases. A hyphen before a capital letter always stays (Gottesman-Kitaev)./ is joined without a space. Soft hyphens are dropped.Removed when the document has at least 3 pages and:
Pictures repeated at the same spot (logos) are removed the same way. Every removed line is listed with --debug, and its words are expected to be missing by the word check (R21). Documents under 3 pages keep everything.
Web links (http, https, mailto) become [text](url). Pieces of one link on the same line are joined first, so doi: 10.… becomes one link. A span mostly covered by the link is linked whole; a partly covered span is split so only the words under the link are linked. Spaces and brackets in the address are encoded (%20, %28, %29). Links inside the document (contents pages) are ignored.
When the last paragraph on a page does not end a sentence (. ! ? : ; closing quote or bracket) and the first paragraph of the next page starts in lower case at the same size, they become one paragraph. The next page's marker (R19) then follows the joined paragraph.
Pages without text are listed in the summary and give return code 4; a page that holds only a picture is kept as that picture. If no page has text (a scanned PDF needing optical character recognition), nothing is written and the return code is 8.
A password-protected PDF gives a message, nothing written, return code 8. PDFs that open without a password (owner restrictions only) convert normally.
The first line of the .md is a hidden HTML comment: <!-- pdf2md v1.0.0 | source: <file name> | pages: N | converted: YYYY-MM-DD -->. Only the file name is recorded, never the folder path. Left out with --no-comments.
Printed at the end: pages (and pages without text), headings, lists, tables, ruled lines; the graphical transients written (and how many PNG and JPEG, and the text drawn inside them) or, in text-only runs, the figure markers placed; removed header/footer/watermark lines, column pages, Qwen results (when used), word check result, the files written, and the return code.
| Code | Meaning |
|---|---|
| 0 | Clean. |
| 4 | Written, with warnings: some pages had no text, or the word check found a mismatch. |
| 8 | Nothing written: not a PDF, unreadable, password-protected, no text at all, usage error, or a crash. |
--graphics)Only with --graphics (or --embed / --base-url, which switch it on). Without it see R22.
<name>_images/p003_01.png or .jpg. The same PDF gives the same names in text-only runs, so [figure p003_01] (R22) always refers to p003_01.*.; with --base-url URL as  (spaces encoded as %20).--debug and expected by the word check.--embed writes each picture into the .md as  (or image/jpeg) and creates no folder. Whether a viewer shows these depends on it accepting data: images; LMV currently does not.Only when PyMuPDF has its table finder (1.23 or later). A detected table becomes a Markdown table, first row as the header; | is escaped, empty cells stay empty, line breaks in cells become spaces. Its text is removed from the normal flow. To stop false tables (for example link underlines in a reference list), a table must have at least 2 rows and 2 columns, at least half its cells filled, fewer than half its rows with a single filled cell, no cell ending in a word broken by a hyphen, and real ruling: a vertical line inside it, or 2 or more lines across its full width. Without the finder, table text comes through as plain lines.
A drawn line no more than 2 pt high and at least 60 % of the page width, outside tables and outside the header/footer zones, becomes ---. Repeats with nothing between collapse to one.
Each page starts with a hidden <!-- page N --> (1-based), so any line can be traced back to its page. Left out with --no-comments. The markers stay hidden only if the Markdown viewer hides HTML comments; if LMV shows them as text, use --no-comments.
Without --graphics no pictures are made and no folder is written. Each picture that --graphics would make (after the R16 skips) is marked on its own line, where it sits in the reading order, as [figure pNNN_NN] — short, so it adds little to search indexes, but enough for a reader or an AI to know something was left out and which file --graphics would give. Text drawn on pictures stays as text in this mode (nothing is absorbed into a picture).
See section 7. In short: only on pages where the plain pass found columns, Qwen may reorder the numbered blocks; it never supplies text; a bad answer is thrown away.
After writing, the .md is read back and its Markdown is stripped (comments, pictures, link addresses, emphasis and code markers, bullets, heading marks, table pipes, fences, ---, backslash escapes, [figure …] markers; numbers of numbered lists are kept because they come from the PDF). Its words are compared with the PDF's words taken by a separate route (PyMuPDF's word list). Both sides are normalised (Unicode compatibility form, so ¹ = 1 and fi = fi; minus sign = hyphen; edge punctuation stripped). Words of removed header/footer/watermark lines and of text inside pictures are expected to be missing. Words split at a line-end hyphen or glued pieces (up to 3 parts) are matched up. Anything left over is a mismatch: the count and the first 10 words are shown (all with --debug) and the return code is 4.
The page is cut along its white gaps, recursively:
Running headers, footers and watermarks are removed before this, so a sideways margin strip cannot fake a column.
--qwen (default http://127.0.0.1:8080) or --qwen URL. At start the tool calls GET /health (5 s). Unreachable → qwen: <url> unreachable (plain mode) and nothing else changes.N: (x0,y0,x1,y1) size S | first 60 characters, pictures as [picture], tables as [table], ruled lines as [ruled line], plus the page size. It is asked for the human reading order as all the numbers, each once, comma-separated, nothing else; the prompt ends with /no_think. Request: POST /v1/chat/completions, temperature 0, 300 s time limit.<think>…</think> part is removed; the integers are read; the answer is accepted only if it is exactly a reordering of all the block numbers. Anything else is rejected, qwen: page N answer rejected is printed, and the plain order is kept. Failures (time-outs, errors) are counted; the return code is never affected.main
parse options (usage error -> RC 8)
probe Qwen if asked
print start-up line R2
convert
content check for %PDF- R1 -> RC 8
open; password? R12 -> RC 8
for each page: read lines/spans, picture pieces, links
attach links to spans R9
join touching picture pieces R16
no text anywhere? R11 -> RC 8
collect the document's words (for hyphen decisions) R7
find repeated margin lines / same-spot lines / logos R8
for each page:
drop running headers/footers/watermarks R8
drop tiny, background and repeated pictures R16
name pictures by position (pNNN_NN) R16 R22
--graphics: pictures absorb text drawn on them, grow to whole lines R16
tables (finder + false-table guards) R17
ruled lines R18
glue raised small numbers onto their line R5
group lines into blocks; join lone bullets R6
body size = size with most characters R4
for each page:
plain reading order (gutters, bands) section 6
column page and --qwen? ask Qwen, accept only a clean reordering R20
blocks -> rows -> paragraphs, list items, code R5 R6 R7
headings by size, short paragraphs only; merge multi-line titles R4
rejoin paragraphs split across blocks R7
join paragraphs across page breaks R10
pick a free output name R3
render Markdown: note, page markers, headings, styles, lists, code, tables, rules,
and per picture: [figure pNNN_NN] marker (default) R22
or graphical transient, PNG or JPEG whichever smaller,
as a file (+ --base-url) or embedded (--embed) R16
write .md
word check against the PDF's own word list R21
RC 0, or 4 if pages without text or word mismatch R11 R21 R15
print summary R14
print RC R15
<name>_images/pPPP_NN.png, linked relatively from the .md (%20 for spaces), or embedded with --embed.--no-comments. Embedded pictures need the viewer to accept data: images (LMV does not).[lmv] depends on MDParser (in CollabCore) accepting picture links such as /pdf2md_images/…; not yet checked. Until then, view them from the folder.test_pdf2md.py builds its own test PDFs with PyMuPDF, runs pdf2md.py on each as a separate program, and checks every rule R1–R22 (73 checks), including:
<think>, and a broken ordering — the first two must be used, the third rejected;--graphics files;Run it on the box, with the same Python as the converter, from the folder holding both files:
python3.8 test_pdf2md.py
It prints its version, one PASS/FAIL line per check, a per-rule table and a total, and exits 0 only if everything passed. Set PDF2MD_KEEP_TEST_FILES=1 to keep the generated files.
Results for v1.1.0: 73 of 73 on PyMuPDF 1.23.26, on 1.18.19, and on 1.18.19 with Pillow (Python 3.8). A 37-page journal article (sideways watermark, equations as picture tiles, reference list with link underlines) converts with the word check passing — 12,011 of 12,011 words. Its graphical transients take 0.7 MB with --graphics (12 JPEG, 25 PNG), against 3.2 MB in v1.0.0 and 2.2 MB for the PDF itself.
| Version | Date | Changes |
|---|---|---|
| 1.1.0 | 2026-11-25 | Text only by default with [figure pNNN_NN] markers (new R22); pictures now opt-in with --graphics and called graphical transients (R16). Each saved as PNG or JPEG, whichever is smaller, at about the PDF's own resolution (small pictures at 2× or more); JPEG via PyMuPDF 1.22+ or Pillow. Picture names fixed by position so markers and files match. New --base-url; --embed and --base-url switch on --graphics. Start-up line shows the graphics state; summary reports graphical transients or markers. Tests 64 → 73. |
| 1.0.0 | 2026-11-25 | First release. Rules R1–R21. Beyond the rules first agreed, built in from the first real test PDF: sideways and same-spot watermarks removed (R8); picture tiles joined and pictures grown to whole text lines (R16); false-table guards (R17); hyphen decisions from the document's own words (R7); raised small numbers glued on as superscripts (R5); paragraphs rejoined across blocks and hanging-indent reference lists (R7); Qwen reduced to reading order only, no labels (R20); picture skip size 8 pt instead of 16 pt so small equation pieces survive (R16). |