Tools,

Extract highlighted text from a PDF, tested

36 of 36

highlights read exactly, with one rule

Scan to text in one call

Keep words half inside each line box

A note stores one box per line. I read 36 notes in 5 made-up PDFs, four ways.

Way to read a note Exact, of 36 Extra words
The note's outer box, PyMuPDF 15 248
Each line's box, PyMuPDF 29 68
Words half inside a line box, PyMuPDF 36 0
The same rule, pypdf and pdfplumber 36 0

No way lost a word.

Flattened highlights: read the color

Flattening a PDF makes its notes part of the page. After PyMuPDF's bake(), PyMuPDF and pypdf found 0 notes in all 5 files. The text layer stayed.

The script then renders the page, finds the marker color, and keeps the words that are half under it: 36 of 36, 0 extra words. On the two-column page, multi-line highlights came out split, with the columns mixed.

On a scan, drop the color first

A made-up phone photo of a printed how-to page with phrases marked in orange, blue, yellow and green
One made-up phone photo, about 180 dpi.

A plain scan has no notes and no text layer. I drew marker on 34 phrases, then made 3 flatbed scans and 2 phone photos in code.

Way to read marker Exact, of 34 Extra words
Tesseract on the color page 12 16
Marker cut-outs, Tesseract 31 83
Marker cut-outs, our Actor's page code 29 91
Color dropped, then Tesseract 33 1

The first and last rows keep words on marker. On the color page, Tesseract skipped whole marked lines: 96 of 280 words.

Dropping the color: read the brightest channel, so marker turns white and print stays dark.

What went wrong
  • Cut-outs catch bits of the lines above and below, read as junk words.
  • In two columns, top to bottom order mixed the cut-outs of the 2 columns.
  • The one miss of the script: Tesseract read "up to" as "up fo".

The script: notes, color, then OCR

On each page it tries 3 cases in order: highlight notes, marker color over a text layer, then OCR. It also takes a photo.

pip install pypdf pdfplumber pypdfium2 opencv-python-headless numpy
python highlights.py notes.pdf
p1 note: March 31, 2027.
p1 note: thirty days from the date of the letter,
highlights.py, the whole script
"""Print the highlighted text of a PDF (or a photo), one highlight per line. The page's script.

Three cases, tried in this order on each page:
  note:   the page has highlight notes (annotations): the words of the text layer inside their boxes.
  marker: no notes, but a text layer: the words of the text layer under marker color (a flattened or printed highlight).
  ocr:    no text layer (a scan or a photo): Tesseract reads the page, and the words under marker color are kept.

pip install pypdf pdfplumber pypdfium2 opencv-python-headless numpy   (BSD, MIT, Apache/BSD, Apache, BSD;
  the OpenCV wheel also bundles FFmpeg, LGPL-2.1)
Tesseract on the PATH (brew install tesseract, apt install tesseract-ocr)
python highlights.py file.pdf
"""

import subprocess
import sys

import cv2
import numpy as np
import pdfplumber
import pypdfium2 as pdfium
from pypdf import PdfReader

SHARE = 0.5  # a word counts if this share of its box is inside a highlight


def note_boxes(page):
    """One list of boxes (x0, top, x1, bottom in points, top-left origin) per highlight note."""
    left, top = float(page.mediabox.left), float(page.mediabox.top)
    notes = []
    for ref in page.get("/Annots") or []:
        a = ref.get_object()
        if a.get("/Subtype") != "/Highlight":
            continue
        q = [float(v) for v in a.get("/QuadPoints", [])]
        boxes = []
        for i in range(0, len(q) - 7, 8):  # 4 corners per line; the corner order differs between apps
            xs, ys = q[i : i + 8 : 2], q[i + 1 : i + 8 : 2]
            boxes.append((min(xs) - left, top - max(ys), max(xs) - left, top - min(ys)))
        notes.append(boxes)
    return notes  # ponytail: rotated pages (/Rotate) not handled


def inside(word, boxes):
    x0, t, x1, b = word
    area = max((x1 - x0) * (b - t), 1e-9)
    return any(
        max(0, min(x1, X1) - max(x0, X0)) * max(0, min(b, B) - max(t, T)) / area >= SHARE for X0, T, X1, B in boxes
    )


def marker_mask(rgb):
    """Marker ink: bright and colored. Paper is not colored, print is not bright. Closing fills the letters."""
    hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV)
    m = ((hsv[..., 1] > 60) & (hsv[..., 2] > 110)).astype(np.uint8)
    k = max(3, rgb.shape[1] // 170)
    m = cv2.morphologyEx(m, cv2.MORPH_CLOSE, np.ones((k // 2 | 1, k | 1), np.uint8))
    m = cv2.morphologyEx(m, cv2.MORPH_OPEN, np.ones((k // 2 | 1, k // 2 | 1), np.uint8))
    return m.astype(bool)


def under_marker(mask, box, scale=1.0):
    x0, t, x1, b = (int(round(v * scale)) for v in box)
    cut = mask[max(t, 0) : b, max(x0, 0) : x1]
    return cut.size > 0 and cut.mean() >= SHARE


def ocr_words(rgb, drop=True):
    """Tesseract words (x0, top, x1, bottom, text) in its reading order. drop: read the brightest channel, so marker
    color turns white. On the color page Tesseract skipped whole highlighted lines."""
    img = rgb.max(axis=2) if drop else cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)
    png = cv2.imencode(".png", img)[1].tobytes()
    tsv = subprocess.run(["tesseract", "-", "-", "--psm", "3", "tsv"], input=png, capture_output=True, check=True)
    rows = [r.split("\t") for r in tsv.stdout.decode().splitlines()[1:]]
    return [
        (int(r[6]), int(r[7]), int(r[6]) + int(r[8]), int(r[7]) + int(r[9]), r[11])
        for r in rows
        if len(r) == 12 and r[11].strip()
    ]


def runs(words, keep):
    """Join kept words that follow each other into one highlight."""
    out, cur = [], []
    for w in words:
        if keep(w):
            cur.append(w[4])
        elif cur:
            out.append(" ".join(cur))
            cur = []
    return out + ([" ".join(cur)] if cur else [])


def highlights(path):
    """Yield (page number, case, text) for each highlight."""
    if not path.lower().endswith(".pdf"):  # a photo or a scan saved as an image
        rgb = cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2RGB)
        mask = marker_mask(rgb)
        for text in runs(ocr_words(rgb), lambda w: under_marker(mask, w[:4])):
            yield 1, "ocr", text
        return
    reader, raster = PdfReader(path), pdfium.PdfDocument(path)
    with pdfplumber.open(path) as pdf:
        for n, (pg, pl) in enumerate(zip(reader.pages, pdf.pages)):
            words = [(w["x0"], w["top"], w["x1"], w["bottom"], w["text"]) for w in pl.extract_words()]
            notes = note_boxes(pg)
            if notes and words:
                for boxes in notes:
                    yield n + 1, "note", " ".join(w[4] for w in words if inside(w[:4], boxes))
                continue
            scale = (150 if words else 300) / 72  # pixels per point
            rgb = np.asarray(raster[n].render(scale=scale).to_pil().convert("RGB"))
            mask = marker_mask(rgb)
            if words:
                for text in runs(words, lambda w: under_marker(mask, w[:4], scale)):
                    yield n + 1, "marker", text
            else:
                for text in runs(ocr_words(rgb), lambda w: under_marker(mask, w[:4])):
                    yield n + 1, "ocr", text


if __name__ == "__main__":
    for page, case, text in highlights(sys.argv[1]):
        print(f"p{page} {case}: {text}")
Already on PyMuPDF? The same rule
import sys

import pymupdf

page = pymupdf.open(sys.argv[1])[0]
words = page.get_text("words")
for a in page.annots(types=[pymupdf.PDF_ANNOT_HIGHLIGHT]):
    v = a.vertices
    lines = [pymupdf.Quad(v[i : i + 4]).rect for i in range(0, len(v), 4)]
    print(" ".join(w[4] for w in words if any(abs(pymupdf.Rect(w[:4]) & r) >= abs(pymupdf.Rect(w[:4])) / 2 for r in lines)))

It gave the same 36 lines as the script. PyMuPDF is AGPL-3.0 or a paid license, so check that before you ship it.

Need the whole page? Our Actor

Our Apify Actor, PDF to Markdown OCR, reads scanned PDFs and images and returns the text. It returns no word boxes, so it cannot pick the marked words on a full page.

On the 41 cut-outs it found 277 of 280 marked words.

The API call, on a 10-page scan
curl -s -X POST "https://api.apify.com/v2/acts/brasspage~pdf-ocr-to-markdown/run-sync-get-dataset-items" \
  -H "Authorization: Bearer $APIFY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"documentUrls": ["https://api.apify.com/v2/key-value-stores/sTnmNrGoSsi7tLQvs/records/langchain-scan-10-pages.pdf"]}'

What I tested, and what I did not

How I tested
  • 5 one-page documents from headless Chromium 153: a memo, a two-column textbook page, a tight agreement, a how-to with a list and a report abstract.
  • 36 notes on the typed PDFs and 34 marked phrases on the scans, 11 of each over 2 or more lines. Marker in 5 colors.
  • Exact: for notes, the note's words are the phrase's words in order. For color and scans, the phrase's words come out in a row. Case and punctuation do not count. Extra words: words out that match no marked word.
  • Scans: a slight turn, blur, noise and JPEG. Photos: 60% size, uneven light and a warm cast.
  • Flattened copies: PyMuPDF bake(), then the script at 150 dpi.
  • PyMuPDF 2.2, pypdf 7.2.0, pdfplumber 0.11.11, pypdfium2 5.15.2, OpenCV 5.1.0, Tesseract 5.5.4 with 1 thread, Python 3.13.
  • Cut-outs: one box for each marker blob, padded, read with --psm 6. Close lines merged 45 strokes into 41 boxes (10 into 7 on the tight agreement).
  • Our Actor: its page code from our repo, second reader on (the default), on this Mac. Not an Apify run.
Sources
  • PyMuPDF Annot docs. PyMuPDF is AGPL-3.0 or a paid license
  • pypdf (BSD-3-Clause) and pdfplumber (MIT)
  • Tesseract (Apache-2.0)
  • Scripts and results stay in our private repo, in research/bench/extract-highlighted-text-pdf-2026-11-27/.
  • We make the Apify Actor, not these libraries.

Questions people ask

How do I extract highlighted text from a PDF for free?

Keep the words that are at least half inside each highlight's line boxes, with a free Python script. It got 36 of 36 highlight notes right in my 5 test PDFs. I did not test online tools.

Can I extract highlighted text from an image or a scan?

Yes, by color. Drop the marker color, run OCR, and keep the words that sit on marker. That read 33 of 34 marked phrases on 3 made-up scans and 2 made-up phone photos.

PyMuPDF or pdfplumber for PDF highlights?

Both got 36 of 36 with the same rule: a word counts when half of it is inside a line box. PyMuPDF is AGPL-3.0 or a paid license. The script uses pypdf (BSD), pdfplumber (MIT), and pypdfium2, OpenCV and numpy (Apache or BSD).