DEV Community

Dudko Development
Dudko Development

Posted on Originally published at pdf2md.dudko.dev

Footnotes in PDF to Markdown: where the notes land, and how to move them

Page 11 of a court opinion ends mid-sentence: "Other MCED-test developers testified that they". The footnote for that page comes next, then page 12 picks up with "anticipated competing with Grail on price". Run that PDF through a PDF-to-Markdown converter and you get the sentence, then a paragraph about antitrust commentators, then the rest of the sentence. Chunk it for retrieval and there's a fair chance the claim and its ending sit in different chunks, with a footnote wedged between them.

This keeps coming up. On docling there's an open request to serialize footnotes as real Markdown footnotes, so an LLM stops reading them as a numbered list. A pull request for [^n] output (docling-core #569) is still open as of Nov 23, 2026. On marker, the report that superscripts "are just fused with the word they follow" was closed as not planned on Nov 4, 2026. pymupdf4llm fixed a case where a raised superscript reordered its own line in 1.28.2. And a 2025 benchmark of five parsers put it flatly: "None of them is able to treat footnotes/footer as footnotes/footer." (harningle, June 2025)

pdf2md doesn't handle footnotes either. It has no footnote option. What follows is how its output actually looks on a real document, next to markitdown's, and a short script on top of pdf2md's npm package that moves the notes out of the way.

Why this is hard

A PDF has no footnote object (tagged PDFs aside). A footnote is small text near the bottom of the page, and its marker is a small digit set a few points above the line. Both are guesses about geometry. The marker is the tricky part. A digit raised by a few points can look closer to the line above than to its own, and an extractor that sorts text by height will move it. That's exactly where pdf2md lost its two markers below.

The test

The main document is a public one: Illumina, Inc. v. FTC, No. 23-60167 (5th Cir. Dec. 15, 2023), the PDF from govinfo.gov. It's 34 pages with 18 numbered footnotes, and on 10 pages the body runs into the next page mid-sentence with notes in between. Court opinions are a good test because the notes carry real content (citations, caveats) and readers do search them.

The second is a two-page fixture made with reportlab (the generator is at the end): four numbered notes, one of them two lines long, and one sentence running over the page break. Its note numbers are 6 pt and raised a little, which is common in reports.

The counts come from a pdfplumber script that reads the PDF itself. A marker is a run of digits at least 20% smaller than the rest of its line. A footnote is a line in the lower half of the page that starts with such a number. Then it looks for each one in the Markdown.

Tools: @dudko.dev/pdf-to-md-cli 0.3.6 with default options, and markitdown 0.1.9 (pip install 'markitdown[pdf]').

Results

Court opinion, 18 footnotes:

pdf2md 0.3.6 markitdown 0.1.9
marker as a separate number (Clayton Act. 2 The) 15 0
marker as a superscript (du Pont¹³) 1 0
marker glued to the text (Clayton Act.2 The) 0 18
marker in the wrong place 2 0
note text present, with its number 18 18
notes inside a sentence that crosses a page 10 of 10 10 of 10

Fixture, 4 footnotes:

pdf2md 0.3.6 markitdown 0.1.9
markers 4 as ¹²³⁴ 4 glued (pier1)
note numbers kept 2 of 4 4 of 4
note text present 4 of 4 4 of 4
notes inside the sentence that crosses the page yes yes

What that means in practice:

Neither tool moves the notes. On every page where a sentence runs over, both put the footnote text in the middle of it. That's the RAG problem, and it's the same for both.

markitdown keeps every number and glues it on. test.1 While, du Pont13, and on the fixture pier1, stations2. A keyword index sees Pont13 as one token. It does give each note its own line, which makes the notes easy to find afterwards.

pdf2md keeps the marker apart from the word, mostly as a spaced number, so Act stays Act. It got two of 18 wrong. One moved two words early (the supposed 17 [anticompetitive] harm). The other was the first line of a page, and its raised 14 came out at the start of that line, ahead of the sentence it belongs to. pdf2md also puts all of a page's notes into one paragraph, with the _____ rule from the PDF glued to the front: _____ 12 405 U.S. at 571. 13 United States v. E. I. du Pont….

pdf2md lost two note numbers on the fixture. On the real document all 18 numbers survived. On the fixture, note 3's number disappeared and its text ran on after note 2, and note 4 came out as a bare line of text on page 2. The note text is all there, but without the number nothing ties it to its marker. My guess is that the 6 pt raised number is set high enough to be grouped with the line above it, but that's a guess. If your documents set note numbers small and high, check a few pages before you trust the numbers.

A fix: move the notes, join the sentence

The script below converts with includePageMarkers: true, so it can work one page at a time. On each page it finds the note block (a _____ rule, or a line that opens with the next expected note number), splits it on the numbers in order (notes run 1, 2, 3 through the document, which helps a lot), and turns each into a [^N]: definition at the end of the document. In the body it swaps the marker for [^N]. Then, if a page ends without closing punctuation and the next page starts in lower case, it joins the two.

It also drops running heads at the top of each page (on this opinion, Case: 23-60167 Document: 336-1 Page: 11 …), because they sit between the two halves of the sentence too.

// footnotes.mjs
// Move each page's footnotes out of the text flow and into Markdown footnotes:
// body markers become [^N], the notes become [^N]: definitions at the end, and a
// sentence that ran over the page break is joined up again.
// Written against the public API of @dudko.dev/pdf-to-md-core.
import { readFile } from 'node:fs/promises';
import { convert } from '@dudko.dev/pdf-to-md-core';

const SUP = '⁰¹²³⁴⁵⁶⁷⁸⁹';
const sup = (n) => String(n).replace(/\d/g, (d) => SUP[d]);
const shape = (line) => line.replace(/\d+/g, '#').trim();
const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

export async function toMarkdownWithFootnotes(pdf, { log = () => {} } = {}) {
  const { markdown = '' } = await convert(pdf, { includePageMarkers: true });
  const pages = markdown.split(/^<!-- Page \d+ -->$/m).slice(1).map((p) => p.split('\n'));

  // running heads such as "Case: 23-60167 ... Page: 11": a line near the top of
  // most pages whose shape (digits masked) repeats. They sit between the two
  // halves of a split sentence, so they have to go before the halves can meet.
  const tops = new Map();
  for (const p of pages)
    for (const l of p.filter((x) => x.trim()).slice(0, 3)) tops.set(shape(l), (tops.get(shape(l)) ?? 0) + 1);
  const isHead = (l) => (tops.get(shape(l)) ?? 0) >= Math.max(3, pages.length / 2);

  let next = 1; // footnote numbers run 1, 2, 3 ... through the document
  const defs = [];
  const bodies = pages.map((lines, i) => {
    const text = lines.filter((l, k) => !(k < 6 && isHead(l))).join('\n');
    // where the notes start: a "_____" rule (pdf2md may glue it to the end of the
    // last body line), or else a line opening with the next note number
    let at = text.search(/_{5,}/);
    if (at < 0) at = text.search(new RegExp(`\\n${next}[ \\t]+\\S`));
    if (at < 0) return text.trim();
    let block = text.slice(at).replace(/^\s*_{5,}\s*/, '').replace(/\s+/g, ' ').trim();
    let body = text.slice(0, at).trim();
    // a note continued from the previous page arrives without a number
    const cont = new RegExp(`^${next}\\s`).test(block) ? '' : block.split(new RegExp(`(?<=[.)”"’\\]*])\\s+(?=${next}\\s+[A-Z*“"\\[_])`))[0];
    if (cont && defs.length) { defs[defs.length - 1] += ' ' + cont; block = block.slice(cont.length).trim(); }
    if (!new RegExp(`^${next}\\s`).test(block)) return [body, block].filter(Boolean).join('\n\n');
    // split the block on the expected numbers, in order
    const notes = [];
    while (true) {
      const n = next;
      const m = block.match(new RegExp(`^${n}\\s+`));
      if (!m) break;
      block = block.slice(m[0].length);
      const after = new RegExp(`(?<=[.)”"’\\]*])\\s+${n + 1}\\s+(?=[A-Z*“"\\[_])`).exec(block);
      notes.push([n, (after ? block.slice(0, after.index) : block).trim()]);
      block = after ? block.slice(after.index).trim() : '';
      next = n + 1;
    }
    for (const [n, note] of notes) {
      // the marker: superscript digits, or a bare number standing after punctuation
      const s = new RegExp(`${esc(sup(n))}(?![${SUP}])`);
      const bare = new RegExp(`([.,;:)”"’\\]*])\\s+${n}(?=\\s|$)`);
      if (s.test(body)) body = body.replace(s, `[^${n}]`);
      else if (bare.test(body)) body = body.replace(bare, `$1[^${n}]`);
      else log(`page ${i + 1}: marker ${n} not found, note kept as a definition`);
      defs.push(`[^${n}]: ${note}`);
    }
    if (block) body += '\n\n' + block; // anything after the last number we could match
    return body;
  });

  // join a sentence that runs over the page break
  let out = '';
  for (const b of bodies.filter(Boolean)) {
    if (!out) out = b;
    else if (/[\p{L},-]$/u.test(out) && /^[\p{Ll}(“"]/u.test(b)) out += (out.endsWith('-') ? '' : ' ') + b;
    else out += '\n\n' + b;
  }
  return out + (defs.length ? '\n\n' + defs.join('\n\n') + '\n' : '\n');
}

if (import.meta.url === `file://${process.argv[1]}`) {
  const pdf = new Uint8Array(await readFile(process.argv[2]));
  const md = await toMarkdownWithFootnotes(pdf, { log: (m) => console.error(m) });
  process.stdout.write(md);
}
Enter fullscreen mode Exit fullscreen mode
npm i @dudko.dev/pdf-to-md-core
node footnotes.mjs opinion.pdf > opinion.md
Enter fullscreen mode Exit fullscreen mode

Measured the same way as above:

court opinion fixture
markers turned into [^N] at the right place 16 of 18 2 of 4
footnotes as [^N]: definitions 18 of 18 2 of 4
sentences across a page joined, no note inside 10 of 10 1 of 1
body words lost 0 (only the running heads went) 0

The output reads like this: …Section 7 of the Clayton Act.[^2] The merger was…, and at the end [^2]: For clarity, we use "FTC" when discussing…. A Markdown renderer that supports footnotes shows them as footnotes, and a chunker no longer gets a note in the middle of a sentence.

Where it falls short:

  • It can't fix a marker pdf2md moved. The two misplaced markers stay where they were (arbitration 14 when it came time). Their notes still get a definition, just with nothing pointing at it. The script prints a line for each one, so you know where to look.
  • It can't recover a lost number. On the fixture, note 3's text stays attached to note 2's definition, and note 4 stays in the body as a plain line. The script counts on the numbers, and when they're gone, so is the split.
  • A bare number after punctuation is taken as the marker. That's how most of them come out of pdf2md, and on this document every one landed in the right place. A sentence like "…under Rule 4. 4 copies were filed" on a page that carries note 4 would fool it.
  • Symbols aren't handled. * and † came out as pier * on a symbol-marked version of the fixture. The script only looks for numbers.
  • Page markers have to be there. They were on both of these, one per page. In an earlier test a page of ruled tables produced fewer markers than pages, so compare the count with the page count first.

When you don't need it

Endnotes are already at the end of the document, out of the body's way. Leave them alone.

Scanned PDFs have no text layer, so there's nothing to move until OCR has run. pdf2md does no OCR, and here's how to tell which pages need it.

If you just want the notes out of the chunks, not kept, it's easier: the same note-block detection, and drop the block instead of moving it.

What I'd do

For a legal or academic corpus going into RAG, run a pass like this one, whichever converter you use. The split sentences are what hurt retrieval, and no converter here fixes them on its own. If you use pdf2md, check the note numbers on a few pages first, because on small, high-set numbers it lost half of them in the fixture. If you use markitdown, the numbers survive, and a similar pass has to unglue them from the words first.

These measurements are of the npm CLI. pdf2md also runs in the browser at pdf2md.dudko.dev/app, where nothing is uploaded, and over an HTTP API. I didn't run this document through the API. The packages are free for noncommercial use under PolyForm Noncommercial 1.0.0, with a 32-day trial for evaluating at work.

The fixture generator

pip install reportlab, then python make_fixtures.py fx writes both test PDFs into fx/.

"""Footnote test PDFs. Needs reportlab (tested 5.1.0). Usage: python make_fixtures.py OUTDIR
Every text is invented for the test."""
import sys, os
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter

OUT = sys.argv[1]
os.makedirs(OUT, exist_ok=True)
W, H = letter
L, R = 72, W - 72

def body(c, y, parts, size=11):
    """parts: list of str or ('sup', '1'). Draws one line; superscripts are 7pt, raised 4pt."""
    x = L
    for p in parts:
        if isinstance(p, tuple):
            c.setFont('Helvetica', 7); c.drawString(x, y + 4, p[1]); x += c.stringWidth(p[1], 'Helvetica', 7)
        else:
            c.setFont('Helvetica', size); c.drawString(x, y, p); x += c.stringWidth(p, 'Helvetica', size)
    return y - 15

def notes(c, items, rule=True):
    """Footnotes at the page bottom, 8pt, under a short rule. items: list of (num, [lines])."""
    n_lines = sum(len(t) for _, t in items)
    y = 72 + n_lines * 10
    if rule:
        c.setLineWidth(0.5); c.line(L, y + 8, L + 144, y + 8)
    for num, lines in items:
        for i, t in enumerate(lines):
            c.setFont('Helvetica', 8)
            if i == 0:
                c.setFont('Helvetica', 6); c.drawString(L, y + 3, num)
                c.setFont('Helvetica', 8); c.drawString(L + 6, y, t)
            else:
                c.drawString(L + 6, y, t)
            y -= 10

def make_basic(path):
    # Page 1: three markers, three notes (one two lines long). The last body sentence runs on to page 2.
    c = canvas.Canvas(path, pagesize=letter)
    c.setFont('Helvetica-Bold', 16); c.drawString(L, H - 72, 'Harbor Sediment Survey')
    y = H - 110
    y = body(c, y, ['Samples were taken at twelve stations along the east pier', ('sup', '1'), '.'])
    y = body(c, y, ['Copper levels exceeded the screening value at four stations', ('sup', '2'), ','])
    y = body(c, y, ['and the survey team repeated those four in the following week.'])
    y -= 8
    y = body(c, y, ['Grain size was measured by laser diffraction', ('sup', '3'), ' on every sample, and the'])
    y = body(c, y, ['results are reported as the median diameter of the fine fraction, which'])
    notes(c, [('1', ['Station positions are listed in Annex B.']),
              ('2', ['The screening value used is the one in the 2019 regional guidance,',
                     'not the stricter draft that was still under consultation.']),
              ('3', ['Instrument calibrated against a reference sand before each batch.'])])
    c.showPage()
    # Page 2: the sentence continues; one more note.
    y = H - 72
    y = body(c, y, ['is the value the dredging permit refers to.'])
    y -= 8
    y = body(c, y, ['Organic carbon was below two percent at every station', ('sup', '4'), '.'])
    notes(c, [('4', ['Loss on ignition at 450 degrees, four hours.'])])
    c.showPage(); c.save()

def make_symbols(path):
    # Same layout with * and dagger markers instead of numbers.
    c = canvas.Canvas(path, pagesize=letter)
    c.setFont('Helvetica-Bold', 16); c.drawString(L, H - 72, 'Harbor Sediment Survey')
    y = H - 110
    y = body(c, y, ['Samples were taken at twelve stations along the east pier', ('sup', '*'), '.'])
    y = body(c, y, ['Copper levels exceeded the screening value at four stations', ('sup', '†'), '.'])
    notes(c, [('*', ['Station positions are listed in Annex B.']),
              ('†', ['The screening value used is the one in the 2019 regional guidance.'])])
    c.showPage(); c.save()

make_basic(os.path.join(OUT, 'footnotes_numbered.pdf'))
make_symbols(os.path.join(OUT, 'footnotes_symbols.pdf'))
print('ok')
Enter fullscreen mode Exit fullscreen mode

Originally published at https://pdf2md.dudko.dev/blog/pdf-footnotes-markdown.

Top comments (1)

Collapse
 
ahmetozel profile image
Ahmet Özel •

That Illumina v. FTC example illustrates a retrieval failure that almost nobody notices until they inspect raw parsed chunks: when a footnote lands right between the two halves of a sentence spanning a page break, naive chunking cuts the legal claim apart and embeds an unrelated citation in the middle.

Detecting raised superscript markers by relative font size and vertical offset via pdfplumber is a practical workaround for untagged PDFs. One edge case to watch in legal and financial filings is exponent notation or chemical formulas, which share the exact same raised small-digit geometry as footnote markers.