Skip to main content

9  Extracting Data from PDFs

TipLearning Objectives
  • Explain what a PDF stores (characters, rectangles, and images placed on a page) and why its text and tables must be reconstructed
  • Tell born-digital, scanned, and mixed pages apart before you extract anything
  • Download PDFs from a records portal politely, keeping a record of where each came from
  • Extract text with pypdf, and words, lines, and tables with pdfplumber, and say what each one reconstructs
  • Recover text from a page image with OCR
  • Check an extraction with counts, sums, cross-checks, and a sample coded by hand, and use those checks to judge an AI document parser
TipCompanion Notebook

Run this chapter’s code as you read: open the companion notebook (see Appendix A for all of them).

9.1 The Web’s Filing Cabinets

PDFs are everywhere in institutional record-keeping: city council minutes, legislative bill texts, financial reports, court filings, academic papers, and environmental impact assessments. They are the format of choice for “official” documents because they look the same on every screen and every printer. The records inside them are what Salganik (2018) calls readymade data: made by institutions for their own purposes, and reusable, with effort, to answer questions their makers never asked.

The City of Boulder keeps thousands of them in its online records portal: signed City Council minutes back to 2000, budgets, ordinances, and the Finance Department’s revenue reports. The revenue report for December 2024 shows both the promise and the problem. Its first pages hold tables of tax revenue whose numbers you can select and copy. Its last page holds a table of sales tax by month for six years that you can’t select at all, because it is a picture of a table. Beside it, the city printed a note: “Please contact sales tax staff … for a screen readable version.”

When you read a PDF, you see paragraphs, tables, headers, and page numbers. A computer reading the same file sees instructions for drawing the page: put these characters at these coordinates, fill this rectangle, paint this image. Getting data out of a PDF is reconstruction, not reading. Software has to infer the words, lines, and tables you see from where things sit on the page, and for a picture of a table, it has to recognize the characters themselves.

So treat the PDF as your last resort, in the same spirit as chapter 8’s order of preference for web pages (Chapter 8):

  1. Look for the data in a form made for machines: an open-data portal, an API, or a spreadsheet.
  2. Ask for it. Colorado’s open-records law says that a record kept in a sortable format, such as a spreadsheet, must be provided in that format (C.R.S. 24-72-203(3.5)).
  3. Parse the PDF.

This chapter is about the third step, which for older records is often the only one available. It starts with the concepts and tools: what a PDF stores, how to tell which kind of PDF you have, how to get the files, what pypdf, pdfplumber, and OCR each reconstruct, and how to check that an extraction is right. Two case studies from Boulder then use all of them: council minutes for text, and revenue reports for tables. The chapter ends with AI document parsers, and with how to judge one. What it costs the public when records come only as PDFs is the subject of “Social History and Public Interest”, at the end of this chapter.

9.1.1 This Chapter’s Files

The chapter’s code reads copies of the city’s PDFs that the book keeps on GitHub, so that a class of readers doesn’t send hundreds of requests to the city’s server at once. “Getting the Files,” below, shows where the copies came from and how to download from the portal yourself. Each file downloads once, the first time you ask for it:

import requests
from pathlib import Path

# The book's copies of this chapter's files; data/ch-09/manifest.csv says where each one came from
BOOK_DATA = "https://raw.githubusercontent.com/cuinfoscience/Web-Data-Science-Book/main/data/ch-09/"
# Say who is asking, as chapter 2 recommends; put your own email address here
HEADERS = {"User-Agent": "WebDataScience/1.0 (your-email@colorado.edu)"}
# The folder, next to your notebook, where the files are saved
PDF_DIR = Path("pdfs")

def get_saved_copy(name):
    """Return the path of one of the book's saved files, downloading it the first time.

    Parameters
    ----------
    name : str
        A file name in the book's data/ch-09 folder, such as "revenue-report-2024-12.pdf"

    Returns
    -------
    pathlib.Path
        Where the file is on your computer
    """
    path = PDF_DIR / name
    if not path.exists():                  # download only the first time
        PDF_DIR.mkdir(exist_ok=True)       # make the folder if it isn't there yet
        response = requests.get(BOOK_DATA + name, headers=HEADERS, timeout=60)
        response.raise_for_status()        # stop with an error if the download failed
        path.write_bytes(response.content) # a PDF is bytes, not text, so save the bytes as they came
    return path

# The December 2024 revenue report, which the next sections read
report_2024 = get_saved_copy("revenue-report-2024-12.pdf")
print(report_2024, f"{report_2024.stat().st_size:,} bytes")  # the file's size, with commas
# pdfs/revenue-report-2024-12.pdf 723,920 bytes

The files land in a pdfs folder next to your notebook. On Windows, the path prints with a backslash.

9.1.2 Installing pypdf, pdfplumber, and pytesseract

The chapter reads PDFs with pypdf and pdfplumber, starting in the next section, and reads pictures of text with pytesseract, in “When There Is No Text Layer: OCR”. pytesseract is a Python library that runs a separate program, Tesseract, which does the reading. Chapter 1’s webdata environment has all of them. Anaconda as it comes has none, and a webdata made before October 2026 lacks some. In either case, an import stops with ModuleNotFoundError. Run this cell once:

# Install four packages from conda-forge into the Python that runs this notebook
%conda install -y -c conda-forge pypdf pdfplumber pytesseract tesseract

It installs four packages, into whichever environment runs this notebook:

  • pypdf and pdfplumber, the two libraries for reading PDFs. pdfplumber brings the libraries it is built on, among them pdfminer.six.
  • pytesseract, the library you import to run OCR from Python;
  • tesseract, the OCR program itself. pytesseract doesn’t bring it, so name it. conda-forge has it for Windows, macOS, and Linux.

The cell takes a minute or two. It worked if one of its last lines is Executing transaction: done, or, if everything was there already, All requested packages already installed. Then restart the kernel (Kernel → Restart Kernel…), and run the cell under “This Chapter’s Files” again, since a restart forgets get_saved_copy().

From a terminal, the same install is conda install -c conda-forge pypdf pdfplumber pytesseract tesseract, typed where the environment you use is active: after conda activate webdata, or where the prompt shows (base).

To check, import the libraries and print their versions, and Tesseract’s:

import pypdf
import pdfplumber
import pytesseract

# Each library records its own version number
print("pypdf", pypdf.__version__, "| pdfplumber", pdfplumber.__version__, "| pytesseract", pytesseract.__version__)

# pytesseract asks the Tesseract program for its version; TesseractNotFoundError means the program is missing
print("Tesseract", pytesseract.get_tesseract_version())
# pypdf 6.20.1 | pdfplumber 0.11.10 | pytesseract 0.3.13
# Tesseract 5.5.3

Newer versions are fine. The chapter’s outputs come from these.

9.2 What’s Inside a PDF

A PDF page is a list of drawing instructions, which the format calls a content stream. Three kinds of things get drawn:

  • Characters. Each instruction picks a font and a size and places characters at a position. The font maps each character’s shape to the Unicode character it stands for. When that map is missing or wrong, extraction returns gibberish from a page that looks fine.
  • Lines and rectangles: rules, borders, shading, and the grid of a table.
  • Images: logos, photographs, charts, and, in a scanned document, the whole page.

What most PDFs don’t store is any of the structure you see: words, lines of text, paragraphs, columns, tables, or the order in which to read them. The gap between two words may be a space character, or just a wider gap between two characters. Everything else is inferred from position.

You can see this with pdfplumber, which lists every object on a page with its coordinates. Positions are in points, 1/72 of an inch, measured from the page’s left edge (x0) and its top (top):

import pdfplumber

# "with" opens the file and closes it again at the end of the block
with pdfplumber.open(report_2024) as pdf:
    page = pdf.pages[1]  # the second page, where the report's tables start
    print(len(pdf.pages), "pages; this one is", page.width, "by", page.height, "points")
    # page.chars is a list with one dictionary per character; print seven of them
    for char in page.chars[1:8]:
        # The character, its distance from the left edge and from the top, its font, and its size
        print(repr(char["text"]), round(char["x0"], 1), round(char["top"], 1), char["fontname"], round(char["size"], 1))
    # How many of each kind of object the page draws
    print(len(page.chars), "characters,", len(page.lines), "lines,", len(page.rects), "rectangles,", len(page.images), "images")
# 15 pages; this one is 612.0 by 792.0 points
# 'C' 54.0 30.4 CALYKT+Arial-BoldMT 11.0
# 'i' 61.9 30.4 CALYKT+Arial-BoldMT 11.0
# 't' 65.0 30.4 CALYKT+Arial-BoldMT 11.0
# 'y' 68.8 30.4 CALYKT+Arial-BoldMT 11.0
# ' ' 74.9 30.4 CALYKT+Arial-BoldMT 11.0
# 'o' 78.0 30.4 CALYKT+Arial-BoldMT 11.0
# 'f' 84.6 30.4 CALYKT+Arial-BoldMT 11.0
# 2222 characters, 0 lines, 549 rectangles, 0 images

The first seven characters spell “City of”, one character at a time. Each carries its own position, font, and size, and “City” is a word only because its four characters sit close together. The table’s rules aren’t lines at all: they are hundreds of thin, filled rectangles (Figure 9.1). Any tool that finds a table on this page has to rebuild its grid from those rectangles, and its cells from the characters.

Metadata. A PDF also stores facts about itself: a title, an author, the program that made it, and dates. pypdf reads them:

from pypdf import PdfReader

reader = PdfReader(report_2024)  # open the report with pypdf
meta = reader.metadata           # the facts the file stores about itself
print(meta.title, "|", meta.subject, "|", meta.creator, "|", meta.creation_date)
# REVENUE REPORT | March 2018 | Acrobat PDFMaker 25 for Word | 2025-05-01 13:20:25-06:00

The title and the creator look right. The subject, March 2018, in a report on December 2024, came from the Word template the report started from: five of the city’s seven year-end reports carry it. Metadata says what the software wrote, not what is true, so don’t date a document by it. The creator is worth reading, though, because it tells you how the file was made, which is what the next section is about.

Tagged PDFs. Some PDFs carry a second layer for assistive technology: a structure tree that marks headings, paragraphs, tables, and figures, sets the reading order, and holds alternative text, which a screen reader speaks in place of an image. PDF/UA (ISO 14289-1) is the standard for doing this well. Six of the seven year-end reports are tagged; December 2023’s isn’t, so check each file, not one. In the December 2024 report, the picture of the monthly table has alternative text, and it reads the note again: “This table presents historical taxes by type. Please contact sales tax staff … for a screen readable version.” In December 2021, the three pictures of tables say what Word writes when nobody writes anything: “Table. Description automatically generated.” Tagging can make a PDF accessible, but only when someone fills it in.

# A tagged PDF's catalog, the object at the root of the file, points to a structure tree
print("tagged:", "/StructTreeRoot" in reader.trailer["/Root"])
# tagged: True

9.2.1 What’s in the File

Because Adobe published the format’s specification, anyone can write software that makes PDFs, which is why this chapter’s files come from so many makers: Word’s PDFMaker, Acrobat Distiller, a Canon scanner, and, for the minutes of 2000, the records portal itself. (Where the format came from is part of “Social History and Public Interest”, at the end of this chapter.) All of them write the same parts.

The file is a set of numbered objects: dictionaries, arrays, numbers, and strings, plus streams of compressed bytes, such as fonts, images, and each page’s drawing instructions. A cross-reference table records where each object starts, so a viewer can jump to page 15 without reading pages 1 to 14; since PDF 1.5 (2003) the table can itself be a compressed stream, as it is in this report. A viewer starts at the end of the file, whose last lines say where that table is (pypdf’s guide to the format walks through the parts). Each page object points to the fonts, images, and content stream it uses. Here are the December 2024 report’s first bytes, and the instructions that draw its running title on page 2:

raw = report_2024.read_bytes()                   # the whole file, as bytes
print(raw[:8])                                   # the header: the format and its version
print(raw[raw.find(b"<<"):raw.find(b">>") + 2])  # the first object: how the file is arranged

# Page 2's drawing instructions, uncompressed and turned into text
stream = reader.pages[1].get_contents().get_data().decode("latin-1")
print(len(stream), "characters of drawing instructions on page 2")
start = stream.find("/TT0 1 Tf")                 # the report's running title, "City of Boulder"
print(stream[start:stream.find("]TJ", start) + 3])  # from there to the end of the first TJ instruction

# The page's fonts, by the short names its instructions use
fonts = reader.pages[1]["/Resources"]["/Font"]
print("/TT0 is", fonts["/TT0"]["/BaseFont"])
# b'%PDF-1.6'
# b'<</Linearized 1/L 723920/O 3296/E 219046/N 15/T 723260/H [ 526 432]>>'
# 62267 characters of drawing instructions on page 2
# /TT0 1 Tf
# 11.04 0 0 11.04 54 767.28 Tm
# ( )Tj
# -0.002 Tc 0.007 Tw 0 -1.141 TD
# [(C)2.6 (i)-6.6 (t)-6 (y o)11.2 (f)-6 ( B)2.6 (ou)11.2 (l)-6.6 (der)]TJ
# /TT0 is /CALYKT+Arial-BoldMT

The header names the format and its version. The first object says the file is linearized, which Acrobat calls “Fast Web View”: 723,920 bytes long, with 15 pages, arranged so that the first page’s objects come first and a browser can show page 1 while the rest downloads. In the content stream, Tf picks the font /TT0, Arial Bold. The six letters before the plus sign in its name mark a subset: the file holds only the characters the report uses. Tm sets the size, 11.04 points, and a position 54 points from the left edge and 767.28 up from the bottom, since PDF counts up from the bottom where pdfplumber’s top counts down. After a space, TD moves down a line, and TJ draws the strings in its brackets. “City of Boulder” is stored as nine pieces, C, i, t, y o, and so on, with the numbers between them nudging each piece into place. Nothing marks the three words as words, or the line as a title.

9.3 What Kind of PDF Is It?

Chapter 8 began with three checks for whether a page needs a browser (Chapter 8). A PDF needs the same kind of triage before you extract anything, because the right tool depends on how each page was made. There are three kinds:

  • Born-digital pages come from software, such as Word or a print-to-PDF driver, which writes the characters into the file. The text is there to extract, though its structure must still be rebuilt.
  • Scanned pages are pictures of paper. The file holds an image and no characters, so text extraction returns nothing. You need optical character recognition (OCR), which reads characters from the image.
  • Scanned with a text layer: someone, often the scanner itself, already ran OCR and hid the text it recognized behind the image. The page looks like a scan, and extraction returns text, but that text is only as good as the OCR that made it.

Files mix them. Boulder’s revenue reports are born-digital, but their charts, and in some years their tables, are pictures.

Check 1: try to select the text. Open the PDF in a viewer and drag across a line. If the text highlights word by word, the page has characters. If nothing highlights, or the whole page highlights as one block, it’s an image.

Check 2: count characters and images on every page. This is check 1 done in code, for every page at once:

def page_profile(path):
    """Count the characters of extracted text, and the images, on each page of a PDF.

    Returns two lists, characters and images, with one number per page.
    """
    reader = PdfReader(path)
    characters = []
    images = []
    for page in reader.pages:
        characters.append(len(page.extract_text()))  # how much text the page gives
        images.append(len(page.images))              # how many pictures it holds
    return characters, images

for name in ["revenue-report-2024-12.pdf", "revenue-report-2018.pdf", "council-minutes-2018-12-04.pdf"]:
    characters, images = page_profile(get_saved_copy(name))
    print(name)
    print("  characters:", characters)
    print("  images:    ", images)
# revenue-report-2024-12.pdf
#   characters: [1332, 2279, 2781, 648, 738, 393, 491, 1356, 1390, 676, 3429, 1519, 3797, 4624, 265]
#   images:     [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
# revenue-report-2018.pdf
#   characters: [1491, 1919, 143, 474, 42, 191, 374, 269, 907, 1273, 3048, 1334, 3031, 3964, 5569]
#   images:     [1, 0, 2, 1, 1, 1, 3, 3, 2, 1, 0, 0, 0, 0, 0]
# council-minutes-2018-12-04.pdf
#   characters: [1718, 1869, 1729, 2381, 2776, 1706, 1665, 1673, 320]
#   images:     [1, 1, 1, 1, 1, 1, 1, 1, 1]

Read each file’s two lists together:

  • The December 2024 report has text on every page. Its first page has one image (the city’s logo), and its last page has one image and only 265 characters: the picture of the monthly table, and the note beside it.
  • The 2018 annual report has pages with one to three images and little text: those are its charts. Its last page has 5,569 characters, because in 2018 the same monthly table was text.
  • The minutes from December 4, 2018 have one image and about 1,700 characters on every page. One image filling the page, with plenty of text, is the third kind: a scan with a text layer.
TipLook past the document average

Keep the per-page character counts from page_profile() when you summarize a document as characters per page. A long text page can raise the average enough to hide a page whose table is an image. Inspect pages with little text in a PDF viewer: a signature page may have little to extract, while a table with only its caption extracted needs OCR for its numbers. There is no character threshold that tells these apart. Compare the text with what you see on the page before deciding whether to run OCR.

Figure 9.2 shows the two reports’ last pages. They look alike on screen. Try to select the numbers, though, and only the 2018 table’s highlight; the counts above say why.

Check 3: find out where the text came from. The minutes’ metadata names the machine that made them, and their text shows how well its OCR worked:

minutes = PdfReader(get_saved_copy("council-minutes-2018-12-04.pdf"))
# Which program or machine made the file, and when
print(minutes.metadata.creator, "|", minutes.metadata.creation_date)
# The first three lines of page 1's text layer
for line in minutes.pages[0].extract_text().splitlines()[:3]:
    print(line.strip())
# Canon  | 2019-01-22 10:08:22-07:00
# CITY OF BOULDER
# CITY COTJNCIL MEETING
# Municipal Building, 1777 Broadway

The minutes were scanned on a Canon scanner seven weeks after the meeting, and the scanner’s OCR read “COUNCIL” as “COTJNCIL”. Most of the page fared better. The motions, though, are printed in small capital letters, and on page 7 the scanner turned “Council Member Weaver moved to adopt Ordinance 8302” into “CouNcrr, Mnunrn WnlvnR MovED To ADopr OnorNaNcr 8302”, and “The motion passed 8:1 at 9:08 p.m.” into “TnB nrorroN plssno 8:1 ar 9:08 p.m.” The text layer exists, but in the parts that record the votes, only the numbers survive. Later in the chapter, OCR reads these pages again.

The checks route each page to a tool:

What the checks show What the page is What to do
Text you can select; characters on the page Born-digital Extract the text with pypdf, and the layout and tables with pdfplumber
One image on the page, and no characters Scanned Run OCR
One image, and characters too Scanned with a text layer Test the text; if it’s poor, run OCR again
Text pages, with some image pages Mixed Route each page by itself

9.4 Getting the Files

The saved copies came from the city’s records portal, documents.bouldercolorado.gov, which runs Laserfiche WebLink, software that many local governments use for their records. Open the Revenue Reports folder in a browser and you’ll see four year folders and three annual reports. View Source shows almost none of it: the page is a shell that says “Loading…”, and JavaScript fills in the list. Chapter 8’s way of finding a hidden API (Chapter 8, “Check 3: Watch the Network Tab”) shows where the list comes from: a request named GetFolderListing2, which sends the folder’s number and gets back JSON.

ImportantCertificates and public records

HTTPS checks a certificate, which proves that a server is who it claims to be. Public data isn’t exempt: some government servers are set up in ways that browsers forgive and Python doesn’t, and Boulder’s is one of them. Its first answer to Python is likely an SSLError that mentions CERTIFICATE_VERIFY_FAILED. The cells below pass verify=bundle, a file of certificates that the book provides, and the request goes through. Never use verify=False, which turns the check off. “Appendix: Technical Notes”, at the end of the chapter, explains what is missing and how the bundle was made.

These two cells are the chapter’s only requests to the city’s server. Run them at home, not all at once in class: on October 6, 2026, the server stopped answering after 13 to 17 requests in a row, whether they came 30 or 60 seconds apart, and answered again after a five-minute pause. The first cell asks for the Revenue Reports folder’s list, as the folder page does:

import time

# The certificates to check the city's server against (see the note above)
bundle = get_saved_copy("boulder-ca-bundle.pem")
PORTAL = "https://documents.bouldercolorado.gov/WebLink/"

# The JSON the folder page itself sends: 194345 is the Revenue Reports folder
body = {"repoName": "LF8PROD2", "folderId": 194345, "getNewListing": True,
        "start": 0, "end": 100, "sortColumn": "", "sortAscending": True}
# POST, not GET: the request carries the JSON above, as the page's own request does
response = requests.post(PORTAL + "FolderListingService.aspx/GetFolderListing2",
                         json=body, headers=HEADERS, timeout=60, verify=bundle)
response.raise_for_status()
folder = response.json()["data"]  # the answer is JSON; the listing is under "data"
print(folder["path"], "|", folder["totalEntries"], "entries")
for entry in folder["results"]:
    # Type 0 is a folder; for a document, the second item in "data" is its page count
    if entry["type"] == 0:
        kind = "folder"
    else:
        kind = f"{entry['data'][1]} pages"
    print(entry["entryId"], entry["name"], f"({kind})")
# \Central Records\Finance\Reports\Revenue Reports | 7 entries
# 194346 2021 (folder)
# 194359 2022 (folder)
# 194372 2023 (folder)
# 194385 2024 (folder)
# 194398 Revenue Report 2018 (15 pages)
# 194399 Revenue Report 2019 (14 pages)
# 194400 Revenue Report 2020 (16 pages)

Each document’s entryId is the number the portal’s download address needs. The second cell downloads the December 2024 report, which sits in the 2024 folder:

time.sleep(30)  # wait between requests to the city's server
docid = 194397  # Revenue Report 2024.12
# The portal's download address for one document
url = PORTAL + f"ElectronicFile.aspx?docid={docid}&dbid=0&repo=LF8PROD2"
response = requests.get(url, headers=HEADERS, timeout=120, verify=bundle)
response.raise_for_status()
# What came back: its type, its size in bytes, and its first five bytes
print(response.headers["Content-Type"], len(response.content), response.content[:5])
# application/pdf 723920 b'%PDF-'

Check what came back before you parse it. A status of 200 isn’t enough: for a record that holds scanned pages rather than a PDF file, the same address answers 200 with an empty body. A PDF starts with the five bytes %PDF-, so test them along with the content type. The size, 723,920 bytes, matches the book’s saved copy; “Appendix: Technical Notes” shows how to check that two copies are the same file, byte for byte.

This code fits Laserfiche WebLink portals, and this one in particular: the folder number, the repository name LF8PROD2, and the request body all come from Boulder’s site. What carries over to other portals is the method: watch what the page requests, test one request, check what comes back, and keep a record of every file you take.

9.5 Text with pypdf

pypdf reads a PDF’s objects and runs each page’s drawing instructions from first to last, writing out characters in the order they are drawn. It is written in Python alone, so it installs anywhere, and it is the first tool to try on a page with a text layer. The minutes of December 5, 2024 were written in Word and saved as PDF, and every page has characters:

# installed under "Installing pypdf, pdfplumber, and pytesseract", above
from pypdf import PdfReader

minutes_2024 = PdfReader(get_saved_copy("council-minutes-2024-12-05.pdf"))
text = minutes_2024.pages[0].extract_text()  # page 1's text, as one string
# Print the first 13 lines, without the spaces at their ends
for line in text.splitlines()[:13]:
    print(line.rstrip())
# P age 1
# CI
# TY COUNCIL MEETING
# Council Chambers
# Thursday, December 5, 2024
# MINUTES
# 1. C
# all to Order and Roll Call:
# M
# ayor Brockett called the meeting to order at 6:00 p.m.
# C
# ouncil Members present: Benjamin, Brockett, Folkerts, Marquis, Schuchard,
# Speer, Wallach, Winer

Every word is there, and several are broken. “CITY” is split across two lines; “Call,” “Mayor,” and “Council” each leave their first letter on the line above; and the page number, which pypdf prints first because the page draws it first, reads “P age 1”. The page shows none of this. Its drawing instructions show where the breaks come from:

# The drawing instructions around the "M" of "Mayor"
stream = minutes_2024.pages[0].get_contents().get_data().decode("latin-1")
instructions = stream.splitlines()       # one instruction per line
start = instructions.index("(M)Tj")      # the line that draws the "M"
# Print the line before it and the three after it
print("\n".join(instructions[start - 1:start + 4]))
# 0 Tc 0 Tw 12 0 0 12 99.12 448.08 Tm
# (M)Tj
# 12 0 0 12 63.12 461.76 Tm
# 3.88 -1.14 Td
# [(a)4 (yor)-7 ( )]TJ

These are the operators from “What’s in the File”, above. The first Tm sets a 12-point size and puts the “M” 99.12 points from the left edge and 448.08 up from the bottom. The next Tm jumps to the start of a line higher up the page, and the Td after it moves 3.88 across and 1.14 down, in multiples of the 12-point size. That lands at 109.68 and 448.08, just right of the “M”. pypdf starts a new line of text whenever the position moves to another line, so the detour breaks the word, although “ayor” ends up beside the “M” on the page. Word drew the first letter of many paragraphs this way.

pypdf’s second mode, extraction_mode="layout", places each piece of text by its position, as on the page:

layout = minutes_2024.pages[0].extract_text(extraction_mode="layout")
for line in layout.splitlines()[:18]:
    if line.strip():                   # skip the blank lines that layout mode adds
        print(" ".join(line.split()))  # the runs of spaces that place each word, shrunk to one
# CITY COUNCIL MEETING
# Council Chambers
# Thursday, December 5, 2024
# MINUTES
# 1. Call to Order and Roll Call:
# Mayor Brockett called the meeting to order at 6:00 p.m.
# Council Members present : Benjamin, Brockett, Folkerts, Marquis, Schuchard,
# Speer, Wallach, Winer
# Virtually present: Adams
# Motion Made By/Seconded Vote
# Motion to AMEND the agenda to: Wallach / Benjamin Carried 9:0

Layout mode keeps “Mayor” whole, and it puts the vote on the motion’s line, where the page prints it; its one slip on this page is the space in “present :”. Older versions split words too. Word spaces letters with tiny nudges, the numbers between the strings inside TJ: “Carried” is drawn as [(C)3 (ar)-11 (r)-11 (i)-6 (ed)-4 …]TJ, where −11 moves the next letter right by 11 thousandths of the font size. Before version 6.20, pypdf’s layout mode read the larger nudges as spaces, and printed “C ham bers,” “Br ockett,” and “Car r ied” here; if your output splits words like that, check pypdf.__version__. Plain mode breaks lines, and layout mode can break words. Pick the mode whose errors your next step can survive, and read its output before you rely on it.

9.5.1 Cleanup Strategies

You can repair some of the damage with regular expressions, as long as you match what the extraction produced rather than what the page shows. A pattern for “Page 1” would miss pypdf’s “P age 1”:

import re

def clean_page_text(raw_text):
    """Clean text that pypdf extracted from a page of the council minutes.

    Parameters
    ----------
    raw_text : str
        Raw text from PdfReader.pages[n].extract_text()

    Returns
    -------
    str
        Cleaned text with normalized spacing, line breaks preserved
    """
    # Drop the page number, which pypdf reads from these minutes as "P age 1"
    text = re.sub(r'^P ?age \d+[ \t]*$', '', raw_text, flags=re.MULTILINE)

    # Rejoin a first letter that Word drew apart from the rest of its word: "M" and "ayor" become "Mayor"
    text = re.sub(r'\b([A-Z]{1,2})\n(?=[A-Za-z])', r'\1', text)

    # Collapse runs of spaces and tabs, but NOT newlines. Line structure is real information in extracted PDF text (headings sit on their own lines), so we keep it
    text = re.sub(r'[ \t]+', ' ', text)

    # Strip each line and drop lines left empty by the removals above
    kept = []
    for line in text.split('\n'):
        line = line.strip()
        if line:
            kept.append(line)
    return '\n'.join(kept)  # put the lines back together, one per line

cleaned = clean_page_text(text)  # text: page 1 of the December 5 minutes, from the cell above
for line in cleaned.splitlines()[:8]:
    print(line)
# CITY COUNCIL MEETING
# Council Chambers
# Thursday, December 5, 2024
# MINUTES
# 1. Call to Order and Roll Call:
# Mayor Brockett called the meeting to order at 6:00 p.m.
# Council Members present: Benjamin, Brockett, Folkerts, Marquis, Schuchard,
# Speer, Wallach, Winer

The most important choice in this function is what not to collapse. A tempting one-liner is re.sub(r'\s+', ' ', raw_text), which normalizes all whitespace in a single pass — but \s matches newlines too, and flattening the page into one long line destroys structure you will need later. Section headings, for example, are recognizable precisely because they sit alone on their own lines; erase the newlines and no heading detector can find them. Collapsing only spaces and tabs ([ \t]+) tidies the text while keeping its shape.

The second rule is a guess about this source: a line that ends in one or two capital letters, followed by a line that starts with a letter, is one word cut in two. On these minutes the guess holds. Across the eight pages it rejoins 39 words, and each was a real break. On the minutes of December 7, 2023, one of its 30 joins is wrong. A motion “to ACCEPT consent agenda items A-F” sits beside the table cell that names who made and seconded it, pypdf puts the two on consecutive lines, and the rule joins “A-F” to “Wallach” as “A-FWallach”. The same page breaks “Call-Up” into “Ca” and “ll-Up”, which the rule doesn’t catch at all. Both of December 2022’s minutes break words after lowercase letters (“Counci” and “l Members present”), which the rule never joins: in the minutes of December 15, 2022, “Council” appears 29 times after clean_page_text(), and 35 times in the text pdfplumber gives (see “Words, Lines, and Tables with pdfplumber”, below), which doesn’t break these words. Check a repair written for one file on the next, and print what it changed; sometimes another tool beats a better pattern.

9.5.2 Regular Expressions for PDF Text

Regular expressions are your main tool for imposing structure on the text that comes out of a PDF. Where structured data formats give you fields and columns, PDF text gives you lines of characters, and a pattern carves out the pieces you need. Here are five, run on all eight pages of the December 5 minutes:

# Join the text of all eight pages, then clean it once
page_texts = []
for page in minutes_2024.pages:
    page_texts.append(page.extract_text())
full_text = clean_page_text("\n".join(page_texts))

# re.findall() returns every match of a pattern, as a list

# 1. Dates written out, as the minutes write most of them ("December 5, 2024")
MONTH = r'(?:January|February|March|April|May|June|July|August|September|October|November|December)'
print(re.findall(MONTH + r' \d{1,2}, \d{4}', full_text))

# 2. Dates with slashes, which the minutes also use ("12/19/24")
print(re.findall(r'\d{1,2}/\d{1,2}/\d{2,4}', full_text))

# 3. Clock times ("6:00 p.m."): print the first, the last, and how many
times = re.findall(r'\d{1,2}:\d{2} [ap]\.m\.', full_text)
print(times[0], "to", times[-1], f"({len(times)} times in all)")

# 4. Vote tallies in the motion tables ("Carried 9:0"); each group in parentheses becomes one part of a match
print(re.findall(r'(Carried|Failed) (\d+):(\d+)', full_text))

# 5. Dollar amounts ("$20,000,000")
print(re.findall(r'\$[\d,]+(?:\.\d{2})?', full_text))
# ['December 5, 2024', 'November 5, 2024', 'November 5, 2024']
# ['12/05/24', '12/19/24']
# 6:00 p.m. to 10:43 p.m. (12 times in all)
# [('Carried', '9', '0'), ('Carried', '9', '0')]
# ['$20,000,000']

Each pattern assumes something about the document. The minutes write most dates out in words, so a slash pattern alone would find two of the five. The tally pattern finds the two votes recorded in motion tables and misses the votes recorded in sentences, such as “by a vote of 9:0”. The dollar pattern assumes a leading $; budget documents that put negative values in parentheses need more. Test a pattern on several pages and several documents from the same source before you build on it, and count what it misses as well as what it finds.

TipMissing Manual Reference

For a thorough introduction to regular expressions — the pattern-matching tool you will use extensively for text cleanup — see Missing Manual Chapter 18: Regular Expressions.

9.6 Words, Lines, and Tables with pdfplumber

pdfplumber, which is built on the pdfminer.six library, starts from where each character ends up rather than the order in which it was drawn. It groups characters into words when the gap between them is under 3 points (its x_tolerance), and words into lines when their tops line up (y_tolerance). On the same page of the December 5 minutes:

with pdfplumber.open(get_saved_copy("council-minutes-2024-12-05.pdf")) as pdf:
    # pdfplumber's text of page 1, line by line: the first 11 lines
    for line in pdf.pages[0].extract_text().splitlines()[:11]:
        print(line)
# CITY COUNCIL MEETING
# Council Chambers
# Thursday, December 5, 2024
# MINUTES
# 1. Call to Order and Roll Call:
# Mayor Brockett called the meeting to order at 6:00 p.m.
# Council Members present: Benjamin, Brockett, Folkerts, Marquis, Schuchard,
# Speer, Wallach, Winer
# Virtually present: Adams
# Motion Made By/Seconded Vote
# Motion to AMEND the agenda to: Wallach / Benjamin Carried 9:0

“Mayor” is whole, because its “M” and “a” end up side by side, whatever route the drawing took between them. The vote sits on the motion’s line, where the page prints it. The page number is no longer first: pdfplumber reads lines from the top of the page down, and “Page 1” is at the bottom.

Neither library is right in general. pdfplumber merges text that sits side by side into one line, as it merged the motion and its vote here; on a page set in two columns of prose, it would interleave the columns. pypdf keeps the order in which the program that made the PDF wrote the text, which is often the reading order. For the minutes, pdfplumber’s text needs fewer repairs. The case study on the minutes uses pypdf anyway, with the repairs from “Cleanup Strategies”, and checks the result against pdfplumber’s.

9.6.1 Finding Tables

A table in a PDF is characters that line up, usually with rules or shaded boxes around them, and pdfplumber’s table finder rebuilds the grid. By default it uses the lines strategy: it collects the page’s rules and the sides of its rectangles, joins those that nearly touch, and makes a cell wherever horizontal and vertical rules close a box. The text strategy infers columns from words that line up instead. Start with the summary page of the December 2024 report:

report = pdfplumber.open(report_2024)  # closed at the end of this section, once the table is out
summary_page = report.pages[1]
tables = summary_page.find_tables()    # every table the finder sees on the page
for table in tables:
    # table.bbox holds the table's four edges; round each to a whole point
    edges = []
    for edge in table.bbox:
        edges.append(round(edge))
    print(edges, len(table.rows), "rows")
# [54, 188, 588, 375] 12 rows
# [60, 203, 232, 231] 2 rows
# [54, 449, 577, 632] 13 rows
# [459, 470, 505, 495] 2 rows

Each bbox is a table’s left, top, right, and bottom edge, in points. The page has two tables, and pdfplumber finds four: the second and fourth are fragments, small boxes inside the shaded headers of the real ones. Look closer at the first:

default_rows = tables[0].extract()  # the first table's cells, as a list of rows
print(default_rows[-1][:6])         # the first six cells of its last row
# search() finds a phrase on the page and returns where it sits; [0] is the first match
total_row = summary_page.search("Total Sales and Use Tax")[0]
# bbox[3] is the table's bottom edge; compare it with the totals row's top and bottom
print("the table ends at", round(tables[0].bbox[3]), "and the totals row runs from", round(total_row["top"]), "to", round(total_row["bottom"]))
# ['Use Tax Audit Revenue', None, '1,498,943', None, '643,062', '-855,881']
# the table ends at 375 and the totals row runs from 380 to 391

The last row it found is “Use Tax Audit Revenue”. The table’s most important row, the total, lies below the table’s edge, and nothing raised an error. Figure 9.3 shows why: the totals row has a double rule under it but no vertical rules beside its figures, so no cells form there, and the table ends above it.

The fix is to tell pdfplumber where the columns are. The table it found already has them: the left and right edges of its cells. Pass those as explicit_vertical_lines, keep the page’s own horizontal rules, and crop the page just below the totals row, so that the footnote under the table stays out:

first = tables[0]
# Each cell is (left, top, right, bottom); collect every left and right edge, once each
edges = set()
for cell in first.cells:
    edges.add(round(cell[0], 2))  # the cell's left edge
    edges.add(round(cell[2], 2))  # and its right edge
edges = sorted(edges)             # from left to right
# Columns where we say they are; rows from the page's own horizontal rules
settings = {"vertical_strategy": "explicit", "explicit_vertical_lines": edges, "horizontal_strategy": "lines"}
area = summary_page.crop((first.bbox[0], first.bbox[1], first.bbox[2], 395))  # 395 points: below the totals row, above the footnote
fixed_rows = area.extract_table(settings)
print(len(default_rows), "rows before,", len(fixed_rows), "after")
print(fixed_rows[-1][:6])
# 12 rows before, 13 after
# ['', 'Total Sales and Use Tax', '', '$175,517,129', '$173,908,431', '-$1,608,698']

The header still comes out in pieces. It is three rows deep, with merged cells that come back as None, and the new column lines cut “December YTD” into “D” and “ecember YTD”. Name the columns yourself, and keep only the rows that have figures:

import pandas as pd

def summary_frame(rows, columns, label="source"):
    """Turn the rows of a table of labeled figures into a DataFrame.

    Parameters
    ----------
    rows : list of lists
        The table, as pdfplumber's extract() or extract_table() returns it
    columns : dict
        Each column's name and its position in a row, such as {"source": 1, "ytd_2023": 3};
        every column but the label holds figures
    label : str
        The name, in columns, of the column that holds each row's label

    Returns
    -------
    pandas.DataFrame
        One row for each row with a label and a first figure; header rows and section titles are left out
    """
    # The figure columns: every column but the label, in the order columns lists them
    figure_columns = []
    for name in columns:
        if name != label:
            figure_columns.append(name)
    first_figure = figure_columns[0]

    records = []
    for row in rows:
        # Keep a row only if it has a label and a first figure; that leaves out headers and section titles
        if not row[columns[label]] or not row[columns[first_figure]]:
            continue
        record = {}
        for name, position in columns.items():
            record[name] = row[position]  # the cell in that column
        records.append(record)
    frame = pd.DataFrame(records)
    frame[label] = frame[label].str.replace("\n", " ")  # a label that wraps becomes one line
    for name in figure_columns:
        # Remove dollar signs, commas, and percent signs, then read what is left as a number
        frame[name] = pd.to_numeric(frame[name].str.replace(r"[$,%]", "", regex=True))
    return frame

# Where each column sits in fixed_rows: the label is the second cell, 2023 the fourth, and so on.
# For another table, name its own columns and positions; the label column defaults to "source"
summary_df = summary_frame(fixed_rows, {"source": 1, "ytd_2023": 3, "ytd_2024": 4, "change": 5, "pct_change": 7})
report.close()  # done with the December 2024 report's pages
print(summary_df[["source", "ytd_2024"]].to_string(index=False))
#                                                   source  ytd_2024
#                                                Sales Tax 139069840
#                                  Rec MJ Additional 3.5%*   1184018
#                                         Business Use Tax   9855472
#                                     Construction Use Tax  14930902
#                                    Motor Vehicle Use Tax   5965968
# Total Sales & Use Tax based on current economic activity 171006199
#                                  Sales Tax Audit Revenue   2259170
#                                    Use Tax Audit Revenue    643062
#                                  Total Sales and Use Tax 173908431

A table without rules needs the other strategy. Exhibit 3 in the 2018 report, the monthly table that later became a picture, has no rules at all:

with pdfplumber.open(get_saved_copy("revenue-report-2018.pdf")) as pdf:
    exhibit_3_2018 = pdf.pages[14]  # page 15, Exhibit 3
    # The default, lines strategy finds nothing on a page with no rules
    print(len(exhibit_3_2018.find_tables()), "tables with the lines strategy")
    # The text strategy finds columns and rows from where the words line up
    text_rows = exhibit_3_2018.extract_table({"vertical_strategy": "text", "horizontal_strategy": "text"})
print(text_rows[4][3:8], text_rows[4][16:])  # part of the header row: its first and last few cells
print(text_rows[7][3:8])                     # a data row: the year and its first four months
# 0 tables with the lines strategy
# ['YEAR', 'JAN', 'FEB', 'MAR', 'APR'] ['YTD T', 'axable Sales S', 'ales R', 'ate']
# ['2012', '5,363,498', '5,129,096', '6,752,856', '5,588,402']

The text strategy finds columns where words line up, and the data rows come out clean. The header doesn’t: where its words don’t line up with the figures below, the column boundaries cut through them, giving “YTD T” and “axable Sales S”. Again, name the columns by hand.

The table settings. find_tables(), extract_table(), and extract_tables() all take the same dictionary of settings, and any setting you leave out keeps its default. The ones you are most likely to change, with their defaults in pdfplumber 0.11:

  • vertical_strategy and horizontal_strategy (both "lines") say where column and row boundaries come from:
    • "lines": the page’s rules and the sides of its rectangles;
    • "lines_strict": rules only, ignoring rectangles, such as shaded backgrounds;
    • "text": words that line up;
    • "explicit": positions you give.
  • explicit_vertical_lines and explicit_horizontal_lines (none): the positions, in points, for the "explicit" strategy, as the fix above used for the columns. They can also add boundaries to the ones another strategy finds.
  • snap_tolerance (3 points): parallel rules closer than this are moved to one position, so that a border drawn twice, slightly apart, counts once. snap_x_tolerance and snap_y_tolerance set it for one direction.
  • join_tolerance (3 points): pieces of a rule whose ends are this close are joined into one, so that a border drawn in segments counts as a single line.
  • edge_min_length (3 points): rules shorter than this are dropped before the grid is built, which leaves out underlines and tick marks.
  • intersection_tolerance (3 points): how close a horizontal and a vertical rule must come to count as crossing, and so to make the corner of a cell.
  • min_words_vertical (3) and min_words_horizontal (1): for the "text" strategy, how many words must line up to make a column boundary or a row boundary. Raise min_words_vertical when a short run of aligned words makes a column that isn’t there.
  • text_x_tolerance and text_y_tolerance (3 points each): for the "text" strategy, how far apart letters can be and still count as one word, and how far up or down and still count as one line.

To see what a set of settings finds, draw it: page.to_image().debug_tablefinder(settings) outlines the cells and marks the crossings, as in Figure 9.3. pdfplumber’s documentation lists every setting, with more on each: Table-extraction settings.

9.7 When There Is No Text Layer: OCR

Optical character recognition (OCR) turns a picture of text into characters. An OCR engine finds the parts of a page that hold text, splits them into lines and words, and recognizes each character from its shape, using a model of the language to settle close calls. It works best on sharp, straight, high-contrast images of at least 300 dots per inch. Tesseract, an engine that Hewlett-Packard built between 1985 and 1994, partly in Greeley, Colorado, and that Google developed from 2006, is the standard open-source choice. pytesseract runs Tesseract from Python; both were installed under “Installing pypdf, pdfplumber, and pytesseract”, at the start of the chapter.

A scanned page. Page 7 of the December 4, 2018 minutes is the page where the scanner’s own OCR garbled the motions (“What Kind of PDF Is It?”). The page is one image, which pypdf hands you as a Pillow image, and Tesseract reads that:

import pytesseract

page_7 = minutes.pages[6]  # minutes: the December 4, 2018 minutes, opened in "What Kind of PDF Is It?"
scan = page_7.images[0].image  # the page's one image, as a Pillow image
print(scan.size, "pixels")     # its width and height
tesseract_text = pytesseract.image_to_string(scan)  # Tesseract reads the image and returns its text
# Print only the lines of the motion and the vote
for line in tesseract_text.splitlines():
    if "MOVED" in line or "PASSED" in line:
        print(line)
# (2556, 3291) pixels
# COUNCIL MEMBER WEAVER MOVED TO ADOPT ORDINANCE 8302
# MORZEL SECONDED THE MOTION. THE MOTION PASSED 8:1 AT 9:08 P.M.

Where the scanner’s text layer reads “CouNcrr, Mnunrn WnlvnR MovED To ADopr OnorNaNcr 8302”, Tesseract reads every word of both lines, from the same image. The image is 2,556 pixels across a page 8.5 inches wide, so it has the 300 dots per inch that OCR needs.

A picture of a table. The December 2024 report’s Exhibit 3 is one image on page 15. Tesseract’s page segmentation mode tells it what layout to expect, and mode 6 says the image is one uniform block of text, which suits a table whose rows run straight across:

# Page 15's one image, converted to grayscale ("L"), which suits OCR
exhibit_3 = PdfReader(report_2024).pages[14].images[0].image.convert("L")
ocr_text = pytesseract.image_to_string(exhibit_3, config="--psm 6")  # mode 6: one block of text
ocr_lines = ocr_text.splitlines()
print(exhibit_3.size, "pixels,", len(ocr_lines), "lines of text")
for line in ocr_lines[4:7]:
    print(" ".join(line.split()[:6]))  # the year and its first five months
# (2545, 1331) pixels, 43 lines of text
# 2020 7,761,028 7,370,943 10,025,017 6,090,136 7,059,371
# 2021 8,059,343 7,608.759 10,351,245 8,666,637 9,229,065
# 2022 9,592,143 9,009,882 11,376,046 —11.242.614 10,608,781

Tesseract reads most figures right, and gets the punctuation of a few wrong: periods for commas in “7,608.759” and “11.242.614”, and a stray dash before the second. The figures are whole dollars, so commas and periods can both be dropped. A stray mark that breaks a row’s pattern is harder, so set those rows aside and report them:

NUMBER = r"[—–-]?\d[\d.,]*"  # a figure as OCR may read it, with a stray dash, or periods for commas
# A row: an optional category name, a year, then 13 figures (twelve months and the year's total)
ROW = re.compile(r"^(?P<label>[A-Za-z ]*?)\s*(?P<year>20\d\d)\s+(?P<figures>(?:" + NUMBER + r"\s+){13})")

def ocr_dollars(figure):
    """'8.832.480' -> 8832480. The table's dollar figures are whole and positive, so every other character can go."""
    return int(re.sub(r"\D", "", figure))  # \D: anything that isn't a digit

ocr_rows = []   # the rows that parsed
set_aside = []  # lines with a year that didn't parse
category = None # the tax the current rows belong to
for line in ocr_lines:
    match = ROW.match(line)
    if not match:
        if re.search(r"\b20\d\d\b", line):
            set_aside.append(line)  # a line with a year that didn't parse: keep it to look at
        continue                    # go on to the next line
    if match["label"].strip():
        category = match["label"].strip()  # each category's name starts its first row
    figures = []
    for figure in match["figures"].split():
        figures.append(ocr_dollars(figure))
    # The first twelve figures are the months, and the thirteenth is the year's total
    ocr_rows.append({"category": category, "year": int(match["year"]), "months": figures[:12], "total": figures[12]})

print(len(ocr_rows), "rows parsed;", len(set_aside), "set aside")
for line in set_aside:
    print(" ".join(line.split()[:6]))  # the start of each line set aside
# 28 rows parsed; 2 set aside
# ” 2022 489,417 405,726 646,263 552.449
# 2022 12,289,385 11,703,828 14,650,181 — 13,712,583

The table has four taxes and their total, each with a row for every year from 2019 to 2024: 30 rows. 28 parsed, and the two set aside each have a stray mark, ” or —, that breaks the pattern. A parsed row can still be wrong, though, since a misread digit leaves a well-formed number. The table checks itself, because each row’s twelve months add up to its total:

# For each row, how far the twelve months' sum is from the printed total, in dollars either way
largest_gap = 0
for row in ocr_rows:
    gap = abs(sum(row["months"]) - row["total"])
    if gap > largest_gap:
        largest_gap = gap
print("largest gap between the months and the total:", largest_gap, "dollars")
# largest gap between the months and the total: 2 dollars

Every parsed row adds up within $2, the rounding you’d expect. A digit misread anywhere but the last place would miss by $10 or more.

Confidence. Tesseract scores each word from 0 to 100, and the scores look like an alarm for misreads. They ring at the wrong times:

# image_to_data() returns one row per word, with its position and its confidence ("conf")
words = pytesseract.image_to_data(exhibit_3, config="--psm 6", output_type=pytesseract.Output.DATAFRAME)
words = words[words["conf"] >= 0]  # -1 marks a block or a line, not a word
print(len(words), "words;", (words["conf"] < 80).sum(), "scored below 80")
# The confidence of two figures that Tesseract read with periods for commas
for figure in ["8.832.480", "7,608.759"]:
    print(figure, words.loc[words["text"] == figure, "conf"].round().astype(int).tolist())
# 722 words; 163 scored below 80
# 8.832.480 [3]
# 7,608.759 [83]

A score of 3 flags “8.832.480”, whose only fault is its periods. “7,608.759” has the same fault and scores 83. Figure 9.4 boxes the words on the table’s first six rows: 13 score below 80, and Tesseract read 11 of those correctly. A low score says Tesseract wasn’t sure of the shapes, not that the number is wrong, and the sums above are the stronger check.

A whole file. pytesseract returns text, and leaves the PDF as it was. To add a text layer to a whole scanned PDF, so that a viewer can select its text and pypdf can extract it, use OCRmyPDF. It needs more installing than the libraries above, so it is in “Appendix: Technical Notes”, at the end of the chapter.

9.8 Checking an Extraction

Extraction fails without errors. pdfplumber dropped the summary table’s totals row and raised nothing. The tally pattern found two votes and said nothing about the others. Tesseract read periods for commas, and its confidence scores flagged one such figure and passed another. Each of these was caught by a check, and checks are cheap: most take a line or two of code. Here they are, cheapest first, each with its example from this chapter:

  1. Look at the page beside the output. The debug image showed where the table ended (Figure 9.3), and the scan of page 7 of the 2018 minutes showed that Tesseract read the motion right.
  2. Count. You know how many rows the page shows. The summary table has nine rows of figures, Exhibit 3 has 30, and the council has nine seats.
  3. Types and ranges. Every figure should parse as a number, and a value far outside the others gets a look. Exhibit 3 says that business use tax’s taxable sales changed by 615.01% in 2019. The image says the same as the OCR, so the question goes to the city, not to Tesseract.
  4. Sums. Parts should add up to their totals, within a tolerance for rounding. The summary table’s five sources add up to $171,006,200, and the subtotal printed beneath them is $171,006,199.
  5. Two tools agree. pypdf’s text and pdfplumber’s table, read from the same page, should give the same figures.
  6. Two documents agree. OCR’s 2024 total from Exhibit 3 should equal the summary page’s, which is text. Reports that overlap should agree too: the December 2023 and December 2024 reports both print 2023’s figures, and all 12 match.
  7. A sample coded by hand. For text, such as the names in an attendance list, read a sample of pages yourself and measure the extraction against it.
  8. A record of what you did. Keep the manifest of files and hashes, the versions of the libraries, and the date of each run, so that someone else can audit your work and redo it.

Write the checks as a function that returns a list of problems, so a pipeline can run them on every file and report what failed, instead of stopping at the first error or carrying on in silence:

def check_summary(table, tolerance=5):
    """Check the revenue summary table's figures against each other.

    Parameters
    ----------
    table : pandas.DataFrame
        The table, from summary_frame()
    tolerance : int
        How many dollars a sum may miss by; the report rounds each figure to the dollar

    Returns
    -------
    list of str
        One line for each failed check; an empty list means every check passed
    """
    problems = []

    # Count: the page shows nine rows of figures
    if len(table) != 9:
        problems.append(f"expected 9 rows of figures, found {len(table)}")

    # Look up rows by their labels from here on
    figures = table.set_index("source")
    subtotal = "Total Sales & Use Tax based on current economic activity"
    total = "Total Sales and Use Tax"
    for label in [subtotal, total]:
        if label not in figures.index:
            problems.append(f"no row labeled {label!r}")
    if problems:
        return problems  # the sums below need every row

    # Sums, for each year: the parts should add up to the subtotal, and the subtotal and audits to the total
    for year in ["ytd_2023", "ytd_2024"]:
        sources = figures[year].iloc[:5].sum()  # the five sources above the subtotal
        if abs(sources - figures.loc[subtotal, year]) > tolerance:
            problems.append(f"{year}: the sources add up to {sources:,}, not {figures.loc[subtotal, year]:,}")
        audits = figures.loc["Sales Tax Audit Revenue", year] + figures.loc["Use Tax Audit Revenue", year]
        if abs(figures.loc[subtotal, year] + audits - figures.loc[total, year]) > tolerance:
            problems.append(f"{year}: the subtotal and audit revenue don't add up to the total")
    return problems

# The table as the default settings read it, which missed the totals row; its columns sit in other places
default_df = summary_frame(default_rows, {"source": 0, "ytd_2023": 2, "ytd_2024": 4, "change": 5, "pct_change": 6})
print("fixed table:  ", check_summary(summary_df))
print("default table:", check_summary(default_df))
# fixed table:   []
# default table: ['expected 9 rows of figures, found 8', "no row labeled 'Total Sales and Use Tax'"]

The case study on the revenue reports runs checks like these on all seven years in the saved copies. Two of the other checks take a few lines each. Here is the same table read through pypdf, compared with pdfplumber’s, and OCR’s total compared with the text:

# pypdf puts each row of figures on one line; one pattern reads the label and the two years
# Page 2's text, up to the heading of the next table
page_2 = PdfReader(report_2024).pages[1].extract_text().split("Other Tax Revenues")[0]
FIGURE_ROW = re.compile(r"^(.+?) +\$?([\d,]+) +\$?([\d,]+) +-?\$?-?[\d,]+ +-?[\d.]+%", re.MULTILINE)
# Each match gives a label and two figures; keep the 2024 figure, by label
pypdf_2024 = {}
for label, ytd_2023, ytd_2024 in FIGURE_ROW.findall(page_2):
    pypdf_2024[label.strip()] = int(ytd_2024.replace(",", ""))

# The same figures from pdfplumber's table, by label
pdfplumber_2024 = {}
for label, ytd_2024 in zip(summary_df["source"], summary_df["ytd_2024"]):
    pdfplumber_2024[label] = ytd_2024

# Labels that only one tool found (the "-" between two sets keeps what is in the first and not the second)
print("only pypdf has:", sorted(pypdf_2024.keys() - pdfplumber_2024.keys()))
print("only pdfplumber has:", sorted(pdfplumber_2024.keys() - pypdf_2024.keys()))
# Labels both tools found, whose figures disagree
differ = []
for label in pypdf_2024:
    if label in pdfplumber_2024 and pypdf_2024[label] != pdfplumber_2024[label]:
        differ.append(label)
print("figures that differ:", differ)

# OCR's 2024 total, from the picture of Exhibit 3, against the summary page's text
for row in ocr_rows:
    if row["category"] == "TOTAL" and row["year"] == 2024:
        ocr_total = row["total"]
print("OCR total matches the text:", ocr_total == pdfplumber_2024["Total Sales and Use Tax"])
# only pypdf has: ['current economic activity']
# only pdfplumber has: ['Total Sales & Use Tax based on current economic activity']
# figures that differ: []
# OCR total matches the text: True

The two tools agree on every figure they share. Their one disagreement is a label: the subtotal’s name wraps onto a second line, and pypdf’s one-line pattern kept only “current economic activity”. OCR’s total from the picture equals the text’s to the dollar.

Measure a text extraction against a sample. For fields such as names, the check is a sample you code by hand, and two numbers describe how an extraction did against it. Precision is the share of what the extraction found that is right; recall is the share of what is there that it found. Here is a first attempt at attendance, the names after “present:”, on page 1 of the December 5 minutes:

# Coded by hand from the page: eight members in the room, and one online
present_by_hand = {"Adams", "Benjamin", "Brockett", "Folkerts", "Marquis", "Schuchard", "Speer", "Wallach", "Winer"}

# A first attempt: the names after "present:", up to the end of the line
page_1 = minutes_2024.pages[0].extract_text()
match = re.search(r"present:\s*(.*)$", page_1, re.IGNORECASE | re.MULTILINE)
# Split the names at the commas, and keep each one that isn't empty
present_found = set()
for name in match.group(1).split(","):
    if name.strip():
        present_found.add(name.strip())

correct = present_found & present_by_hand  # "&": the names in both sets
print("precision:", round(len(correct) / len(present_found), 2))
print("recall:", round(len(correct) / len(present_by_hand), 2))
print("missed:", sorted(present_by_hand - present_found))
# precision: 1.0
# recall: 0.56
# missed: ['Adams', 'Speer', 'Wallach', 'Winer']

Every name the pattern found is right, so its precision is perfect, and it found five of the nine members. The other four are on the next line, where the list wraps, and on the “Virtually present” line below it. Precision alone would have hidden the problem. The case study on the minutes builds a parser that handles both, and checks it the same way.

Checking is not auditing. A table whose sums hold shows that you copied the city’s figures faithfully, not that the figures are right; that takes a financial audit. The report itself calls its figures “unaudited” (page 2).

Write down what failed. Keep a short record of each check, what it caught, and what you set aside or fixed by hand, and publish it with the data. Gebru et al. (2021) propose datasheets for datasets, which answer questions like these in a standard form: how the data was collected, what is missing from it, and what errors are known.

9.9 Case Study: Boulder City Council Minutes

The City Council’s signed minutes record who was at each meeting. This case study measures attendance in the eleven December meetings in the book’s saved copies, from 2018 to 2024: how many members answered the roll call. It uses pypdf. Every page of these minutes has a text layer: those from 2020 on were saved from Word, and those from 2018 and 2019 are scans with the scanner’s own text layer. The repairs from “Cleanup Strategies” handle most of what pypdf breaks, and checks catch the rest.

9.9.1 Reading the Minutes

Read every page of every meeting once, clean it, and keep the pages by meeting date:

MINUTES = [
    "council-minutes-2018-12-04.pdf", "council-minutes-2019-12-03.pdf",
    "council-minutes-2020-12-01.pdf", "council-minutes-2020-12-15.pdf",
    "council-minutes-2021-12-14.pdf", "council-minutes-2022-12-01.pdf",
    "council-minutes-2022-12-15.pdf", "council-minutes-2023-12-07.pdf",
    "council-minutes-2023-12-21.pdf", "council-minutes-2024-12-05.pdf",
    "council-minutes-2024-12-19.pdf",
]

minutes_pages = {}  # each meeting's date, and the cleaned text of each of its pages
page_count = 0
for name in MINUTES:
    meeting = name.removeprefix("council-minutes-").removesuffix(".pdf")  # the meeting's date
    reader = PdfReader(get_saved_copy(name))
    pages = []
    for page in reader.pages:
        pages.append(clean_page_text(page.extract_text()))  # extract, then repair, each page
    minutes_pages[meeting] = pages
    page_count += len(pages)

print(len(minutes_pages), "meetings,", page_count, "pages")
# 11 meetings, 81 pages

9.9.2 Attendance at Roll Call

The roll call opens page 1 of every meeting, and the clerks have recorded it two ways. Here is the first meeting in the set, and the last:

for meeting in ["2018-12-04", "2024-12-05"]:
    lines = minutes_pages[meeting][0].splitlines()  # page 1, line by line
    # Find the line where the meeting is called to order; enumerate() numbers the lines from 0
    for i, line in enumerate(lines):
        if "called the meeting to order" in line:
            start = i
            break  # stop at the first one
    print("\n".join(lines[start:start + 4]))  # that line and the three after it
    print()
# Mayor Jones called the meeting to order at 6:04 p.m.
# Council Members Brockett, Carlisle, Morzel, Nagle, Weaver, Yates and Young
# were present. Council Member Grano arrived at 6:24 p.m.
# Council Member Morzel moved to amend the agenda by removing Item 6,4'-
#
# Mayor Brockett called the meeting to order at 6:00 p.m.
# Council Members present: Benjamin, Brockett, Folkerts, Marquis, Schuchard,
# Speer, Wallach, Winer
# Virtually present: Adams

Through 2020, a sentence names the members who “were present”, and the mayor, who called the meeting to order, isn’t in it. From 2021, a label introduces a list that can wrap onto the next line, and members who joined online get a second label, worded three ways across these meetings: “Virtually present:”, “Present virtually:”, and “Council Members present virtually:”. pypdf adds damage of its own. In the 2021 minutes, “Speer” comes out as “S peer”, and in the second meeting of December 2022, “Council” is cut into “Counci” and “l Members”. The function below handles each case, and says which case each step is for:

def split_names(names):
    """Split a list of surnames such as "Speer, Wallach, and Winer" into a set."""
    names = re.sub(r"\b([A-Z]) ([a-z]+)", r"\1\2", names)  # pypdf's "S peer" is "Speer"
    surnames = set()
    # Split at each comma and at each word "and"
    for name in re.split(r",|\band\b", names):
        if name.strip():
            surnames.add(name.strip())
    return surnames

def roll_call(page_1):
    """Find the members present at a meeting's roll call.

    Parameters
    ----------
    page_1 : str
        The cleaned text of page 1 of a meeting's minutes

    Returns
    -------
    set of str
        The surnames of the members present, in the room or online
    """
    present = set()

    # The mayor calls the meeting to order; through 2020, the list of members leaves the mayor out
    mayor = re.search(r"Mayor (\w+) called the meeting to order", page_1)
    if mayor:
        present.add(mayor.group(1))

    # 2018-2020: "Council Members Brockett, Carlisle, ... and Young were present"
    sentence = re.search(r"Council Members ([A-Z][^:]*?)\s+were\s+present", page_1)
    if sentence:
        present |= split_names(sentence.group(1))  # "|=" adds the names to the set

    # 2021-2024: "Council Members present: ...", "Virtually present: ...", "Present virtually: ..."
    lines = page_1.splitlines()
    for i, line in enumerate(lines):
        label = re.match(r"(?:.*Members present(?: virtually)?|Virtually present|Present virtually):\s*(.*)", line, re.IGNORECASE)
        if label:
            names = label.group(1)  # the names after the label, on this line
            for following in lines[i + 1:]:
                if not names.endswith(","):
                    break  # a list that goes on to the next line ends this one with a comma
                names += " " + following
            present |= split_names(names)
    return present

# One row per meeting: its date, and how many members its roll call found
rows = []
for meeting, pages in minutes_pages.items():
    rows.append({"meeting": meeting, "present": len(roll_call(pages[0]))})
attendance = pd.DataFrame(rows)
print(attendance.to_string(index=False))
#    meeting  present
# 2018-12-04        8
# 2019-12-03        9
# 2020-12-01        8
# 2020-12-15        8
# 2021-12-14        8
# 2022-12-01        9
# 2022-12-15        9
# 2023-12-07        9
# 2023-12-21        9
# 2024-12-05        9
# 2024-12-19        9

The counts need the check from “Checking an Extraction”: a sample coded by hand. Here the sample is every meeting. Reading the eleven roll calls gives these counts, and the extraction matches all of them:

# Counted by hand from page 1 of each meeting: members at the roll call, in the room or online, with the mayor
by_hand = {"2018-12-04": 8, "2019-12-03": 9, "2020-12-01": 8, "2020-12-15": 8, "2021-12-14": 8,
           "2022-12-01": 9, "2022-12-15": 9, "2023-12-07": 9, "2023-12-21": 9, "2024-12-05": 9, "2024-12-19": 9}
# Compare each meeting's count with the hand count, and keep the meetings where they differ
mismatches = {}
for row in attendance.itertuples():  # one row of the DataFrame at a time
    if row.present != by_hand[row.meeting]:
        mismatches[row.meeting] = (row.present, by_hand[row.meeting])
print("meetings that differ:", mismatches)
# meetings that differ: {}

Know what the number means before you use it. It counts the members who answered the roll call, so a member who arrived later counts as absent: two did, in December 2018 and December 2021. The council has nine seats, and four meetings had eight members at the roll call. The names are written as each clerk wrote them, and one member is “Swetlik” in 2019 and “Swetlick” in 2020. To follow a member across years, you would map the spellings to one person yourself.

9.10 Case Study: Boulder Revenue Reports

The Finance Department’s year-end revenue report opens with a summary table of sales and use tax, the city’s largest source of revenue, for the year and the year before. Seven reports, from 2018 to December 2024, cover eight years. This case study uses pdfplumber to build one time series from them, total sales and use tax by year from 2017 to 2024, and asks how it changed through the pandemic.

9.10.1 Finding the Summary Page

The summary table is on page 2 of every report but one. The 2020 report opens with a letter, dated March 1, 2021, whose subject is “December 2020 Revenue Report Restatement of Earlier Period Revenues”, so its summary is on page 3. Find the page by what it says, not by its number. Every summary page begins its text with the same sentence:

REPORTS = ["revenue-report-2018.pdf", "revenue-report-2019.pdf", "revenue-report-2020.pdf",
           "revenue-report-2021-12.pdf", "revenue-report-2022-12.pdf",
           "revenue-report-2023-12.pdf", "revenue-report-2024-12.pdf"]

def find_summary_page(pdf):
    """Return the page of a revenue report that holds the sales and use tax summary, or None."""
    for page in pdf.pages[:4]:  # the summary is in the first four pages
        # pdfplumber before 0.6 (2021) gave None for a page with no text; or "" keeps this line safe on those versions
        if "This report provides" in (page.extract_text() or ""):
            return page
    return None  # no page had the sentence

for name in REPORTS:
    with pdfplumber.open(get_saved_copy(name)) as pdf:
        print(name, "page", find_summary_page(pdf).page_number)  # page_number counts from 1
# revenue-report-2018.pdf page 2
# revenue-report-2019.pdf page 2
# revenue-report-2020.pdf page 3
# revenue-report-2021-12.pdf page 2
# revenue-report-2022-12.pdf page 2
# revenue-report-2023-12.pdf page 2
# revenue-report-2024-12.pdf page 2

9.10.2 Reading the Totals Row by Position

“Finding Tables” showed that pdfplumber’s table finder leaves out the totals row on the December 2024 page, because the row has no vertical rules beside it. The other reports’ tables have different rules, and each would need its own settings. One row is all this question needs, though, and pdfplumber can find a row without finding the table: search() returns where a phrase sits on the page, and a crop of the page from the left edge to the right, as tall as that line, holds the row’s words. The column headings work the same way: the two years sit side by side above the figures.

def row_words(page, label):
    """Return the words to the right of label, on the line where label is.

    Parameters
    ----------
    page : pdfplumber.page.Page
        The page to read
    label : str
        A regular expression for the row's label, such as "Total Sales and Use Tax"

    Returns
    -------
    list of str
        The row's other words, from left to right
    """
    found = page.search(label)[0]  # the first match: its text, and its position in points
    # A strip of the page, across its whole width, from just above the label to just below it
    line = page.crop((0, found["top"] - 1, page.width, found["bottom"] + 1))
    words = []
    for word in line.extract_words():
        if word["x0"] > found["x1"]:  # the word starts right of where the label ends
            words.append(word["text"])
    return words

def to_number(text):
    """Turn a figure such as "$134,538,892", "(1,145,528)", or "-$1,608,698" into an int."""
    negative = text.startswith(("(", "-"))   # accountants write a negative number in parentheses
    value = int(re.sub(r"[^\d]", "", text))  # keep only the digits
    if negative:
        return -value
    return value

with pdfplumber.open(get_saved_copy("revenue-report-2018.pdf")) as pdf:
    page = find_summary_page(pdf)
    # Two years side by side, such as "2017 2018"; "groups" holds what each pair of parentheses matched
    print(page.search(r"(20\d\d) +(20\d\d)")[0]["groups"])
    print(row_words(page, "Total Sales and Use Tax"))
# ('2017', '2018')
# ['$134,538,892', '$140,648,710', '$6,109,818', '4.54%']

The row reads left to right: the earlier year’s total, this year’s, the change in dollars, and the change in percent. The report’s own change column is a check that costs nothing: this year’s total minus last year’s should equal it.

totals = []
for name in REPORTS:
    with pdfplumber.open(get_saved_copy(name)) as pdf:
        page = find_summary_page(pdf)
        # The two years in the table's heading: the year before, and this year
        years = page.search(r"(20\d\d) +(20\d\d)")[0]["groups"]
        earlier_year = int(years[0])
        this_year = int(years[1])
        # The totals row's first three figures: the year before, this year, and the change
        figures = row_words(page, "Total Sales and Use Tax")
        earlier = to_number(figures[0])
        this = to_number(figures[1])
        change = to_number(figures[2])
    # The check: this year minus the year before should equal the printed change
    if this - earlier != change:
        print(f"{name}: {this:,} - {earlier:,} is not {change:,}")
    # Keep both years' totals, with the report they came from
    totals.append({"report": name, "year": earlier_year, "total": earlier})
    totals.append({"report": name, "year": this_year, "total": this})

totals = pd.DataFrame(totals)
print(len(totals), "figures from", totals["report"].nunique(), "reports; every change column checks")
# 14 figures from 7 reports; every change column checks

9.10.3 Two Printings of the Same Year

Six of the eight years are printed twice: as “this year” in one report, and as “the year before” in the next. They should agree:

# For each year: how many reports print it, and the smallest and largest figure they give
printings = totals.groupby("year")["total"].agg(["count", "min", "max"])
twice = printings[printings["count"] == 2]  # the years printed in two reports
# Add a column for how far apart the two printings are, and print the table
print(twice.assign(difference=twice["max"] - twice["min"]).to_string())
#       count        min        max  difference
# year
# 2018      2  140609751  140648710       38959
# 2019      2  141954650  141954650           0
# 2020      2  135195413  135195413           0
# 2021      2  152302653  152302653           0
# 2022      2  169112615  169112615           0
# 2023      2  175517129  175517129           0

Five years agree to the dollar. 2018 doesn’t: the 2018 report gives $140,648,710, and the 2019 report gives 2018 as $140,609,751, $38,959 less. The 2019 report doesn’t say why. A later printing of a figure is usually a correction, so the series below uses each year’s latest printing, and a note with the data should say so. The 2020 letter is a reminder that reports do get restated: it explains that January to November 2020 had wrongly included penalties and interest, which the December report leaves out.

9.10.4 The Time Series

latest = totals.groupby("year").last()  # REPORTS runs oldest to newest, so last() is each year's latest printing
# pct_change() compares each year with the one before; times 100 makes it a percent
latest["change_pct"] = (latest["total"].pct_change() * 100).round(2)
print(latest[["total", "change_pct"]].to_string())
#           total  change_pct
# year
# 2017  134538892         NaN
# 2018  140609751        4.51
# 2019  141954650        0.96
# 2020  135195413       -4.76
# 2021  152302653       12.65
# 2022  169112615       11.04
# 2023  175517129        3.79
# 2024  173908431       -0.92

Figure 9.5 shows the series. Sales and use tax fell 4.76% in 2020, rose by more than 10% in both 2021 and 2022, and was nearly flat by 2024, when it fell 0.92%. These are dollars of each year, not adjusted for inflation; prices rose faster than revenue in 2024, so in real terms the fall was larger. The checks above are what let you put the eight years side by side: every figure was read by position, every change column agreed, and the one year printed two ways is accounted for.

These functions fit these seven reports. The label “Total Sales and Use Tax”, the sentence that opens the summary page, and the order of the row’s figures are the city’s choices, and the city has changed its reports before: the program that made them, the wording of the table’s header, and, in the last page’s monthly table, text that became a picture. When the next report changes, the checks are what will tell you. A label that isn’t found raises an error, and a row read wrong fails its change column or disagrees with the next year’s printing.

9.11 Document Understanding

Everything so far rebuilds a page step by step, and you choose each step: which library reads the text layer, where a table’s columns are, which rows to set aside. Document understanding is the research field that tries to read a document as a whole. Its tasks include layout analysis, which finds the headings, paragraphs, tables, and figures on a page and the order to read them in; table structure recognition, which finds a table’s rows, columns, and merged cells; OCR; and key information extraction, which pulls named fields, such as a date or a total, out of forms and invoices. The Awesome Document Understanding list collects the field’s papers, datasets, and tools.

Its tools usually write Markdown or HTML, because those formats keep a document’s structure, its headings, lists, and tables, as text that a script or a language model (Chapter 13) can read.

NoteOptional: nothing in this section is required

The tools in this section are not in webdata, and nothing else in the chapter or its exercises uses them. Some need a large download or a GPU, and some send your document to a company’s server. The code below is shown, not run in the companion notebook. To try two of them, make a separate environment, so that their dependencies stay out of webdata:

conda create -n docparse -c conda-forge python=3.12 pandoc
conda activate docparse
pip install docling "markitdown[pdf]"

9.11.1 Three Kinds of Tools

  • Converters that read the text layer. MarkItDown, from Microsoft, turns PDFs, Word, PowerPoint, Excel, and HTML files into Markdown. For a PDF it reads the text layer, much as pypdf does, so it is fast and needs no model, but a scanned page gives it nothing to read. pymupdf4llm is similar; note its AGPL license, which has conditions for software you distribute.
  • Pipelines of models. A layout model finds the parts of each page, a table model finds each table’s cells, and an OCR engine reads any part that is a picture. Docling, which IBM Research started and the LF AI & Data Foundation now hosts, runs on a laptop’s processor. Marker, from Datalab, and MinerU, from OpenDataLab, work the same way, with a GPU for their best modes.
  • Vision-language models. A model reads an image of the page and writes the whole page out as Markdown or HTML, tables included. Most need an NVIDIA GPU: olmOCR from Ai2, DeepSeek-OCR, Chandra from Datalab, dots.mocr, and PaddleOCR-VL. LightOnOCR-2, at one billion parameters, is small enough to run, slowly, without one. Hosted services, such as Mistral OCR and Datalab’s own API, run the model for you, for a fee per page, after you upload the document.

Pandoc belongs beside these tools but does a different job. It converts between markup formats, such as Markdown, HTML, Word, LaTeX, and EPUB, and Quarto uses it to build this book. Pandoc can write a PDF but can’t read one, so it comes after a parser: pandoc -s summary.md -o summary.html turns a parser’s Markdown into a web page, and -o summary.docx into a Word file.

Tool Made by Kind Runs on a laptop without a GPU License (code / model)
MarkItDown Microsoft Text-layer converter Yes MIT
Docling IBM Research; LF AI & Data Pipeline Yes MIT / varies by model
Marker Datalab Pipeline with a vision model Partly (--mode fast) Apache-2.0 / modified OpenRAIL-M
MinerU OpenDataLab Pipeline, with a vision model in its higher tiers Its basic tier Its own license
olmOCR Ai2 Vision-language model, 7B No (NVIDIA GPU) Apache-2.0 / Apache-2.0
DeepSeek-OCR DeepSeek Vision-language model, about 3B No (NVIDIA GPU) MIT / MIT
Chandra Datalab Vision-language model, about 5B No, in practice Apache-2.0 / modified OpenRAIL-M
Mistral OCR Mistral AI Hosted service Runs on Mistral’s servers Proprietary
Pandoc John MacFarlane and contributors Format converter; reads no PDFs Yes GPL-2.0

The table reflects each project’s own pages in October 2026. The field moves quickly: check a tool’s current version and license before you rely on it. The models’ licenses matter as well as the code’s. Datalab’s models, for instance, are free to use only below a revenue threshold.

9.11.2 Two of Them on the Revenue Report

Here is how MarkItDown 0.1.8 and Docling 2.139.0 handled the December 2024 report, run for this chapter on October 14, 2026, on a four-core Linux machine without a GPU. In the docparse environment, each takes a few lines:

from markitdown import MarkItDown
from docling.document_converter import DocumentConverter

# MarkItDown: the whole report, as one Markdown string
markitdown_text = MarkItDown().convert("pdfs/revenue-report-2024-12.pdf").markdown

# Docling: page 2, the summary page; its models download the first time it runs
result = DocumentConverter().convert("pdfs/revenue-report-2024-12.pdf", page_range=(2, 2))
docling_text = result.document.export_to_markdown()

MarkItDown gave the summary table as lines of text, one row per line, much like pypdf’s: “Total Sales and Use Tax $175,517,129 $173,908,431 -$1,608,698 -0.92% -0.92%”. Reading the figures would still take the patterns from “Checking an Extraction”. On Exhibit 1 it mixed the two: a few rows came out as Markdown tables, some of them tables of a single row, the rest as lines of text, with empty tables in between. Exhibit 3, the picture of a table, gave only the note beside it, because MarkItDown doesn’t run OCR unless you connect it to a language model or to Microsoft’s cloud service.

Docling took about 20 seconds for the summary page and wrote a Markdown table with all nine rows of figures, the totals row included, which pdfplumber’s default settings missed. It named each column from the header above, such as “December YTD - 2024”. On the picture of Exhibit 3 it ran its default OCR engine, RapidOCR, whose models it downloaded first, and took about a minute. It read “7,608,759”, where Tesseract wrote “7,608.759”. But the chapter’s checks found what else went wrong:

  • Sums. Of the table’s 30 rows of figures, 21 came out whole, and every one of those adds up to its total.
  • Count. The other nine didn’t come out whole. Two years’ rows were merged into one, with two figures in each cell; one row lost most of its figures; others had empty cells.
  • Labels. Two rows that pass the sums carry the wrong label: Docling put “Change from prior year (YTD)” beside Construction Use Tax’s 2019 figures, and the TOTAL label on an empty row below the total’s 2019 figures. Sums can’t catch a wrong label, so check the labels as well.

Nothing raised an error. The table looked complete, and only the checks showed which rows to trust.

9.11.3 Judging a Parser

A parser’s benchmark score, such as olmOCR-Bench or OmniDocBench, says how it did on other people’s documents, usually as its own makers report it. On your documents, run the checks from “Checking an Extraction”: count the rows, add up the parts, compare two tools, and code a sample by hand. Then weigh what else the tool costs:

  • Privacy. A hosted service receives your document. So does a local tool when you switch on its cloud options, such as MarkItDown’s language-model and Microsoft Azure features, Marker’s --use_llm, or MinerU’s remote mode. Don’t upload records that hold personal information without permission.
  • Plausible errors. A vision-language model writes text that looks right. Where Tesseract garbles a digit, a model can write a different, well-formed number, or fill in a cell it couldn’t read. Sums and second printings catch these; reading the output does not.
  • Reproducibility. Record the tool’s version and the model’s, as the chapter does for pypdf and pdfplumber. A model that changes can change your data.
  • Time and cost. Docling took a minute for one picture of a table on a laptop’s processor. A thousand pages takes hours without a GPU, or a fee per page from a hosted service.

For the two case studies, the chapter’s own code was the better choice: pypdf and pdfplumber read the text layer exactly, and each step can be checked. Reach for a parser when documents have no text layer, come in many layouts, or are too many to write patterns for, and run the checks on what it produces.

9.13 Additional Exercises

These are open-ended extensions — no scaffold, no fixed path. Use them for further practice or deeper exploration.

  1. Extraction quality comparison. Compare the text extraction quality of PyPDF on three different types of PDFs: a text-based report, a document with complex tables, and a slide deck exported to PDF. What works well and what fails?

  2. Tables, not text. Find a government PDF that contains a budget or financial table — a city budget summary, a department expenditure report, or a school district financial statement. First extract the page with pypdf and observe what happens to the table’s structure. Then extract the same table with pdfplumber’s extract_table() and build a proper DataFrame with numeric columns. Briefly describe what spatial information pdfplumber uses that plain text extraction throws away, and when that extra dependency is worth it.

  3. Topic tracking. Download a year’s worth of city council meeting minutes (roughly 12–24 PDFs). Choose a topic term relevant to local politics — “housing,” “police,” “flood,” “budget” — and count how often it appears in each meeting’s extracted text. Plot the frequency over time and identify the meetings where the topic spiked. For a measure more robust than raw counts, apply the bag-of-words preprocessing from Chapter 7 (tokenization, stopword removal) before counting, and normalize by each document’s length. What events or agenda items explain the spikes?

  4. Tool comparison. Install pdfplumber alongside pypdf. Extract text from the same PDF using both tools. Compare the quality of text extraction — line breaks, whitespace handling, table detection. Which tool handles your specific PDF better, and why?

  5. A third printing. Exhibit 3 of the December 2024 report prints each year’s total for 2019 to 2024, beside the two summary pages that print each year. Read its TOTAL rows with the OCR pipeline from “When There Is No Text Layer: OCR”, and compare each year with the series from “Two Printings of the Same Year”. Which year disagrees, by how much, and does the picture’s own row add up? Which figure would you publish, and what would you write in the data’s notes?

  6. Graduate extension (INFO 5617). Sample at least ten municipal-meeting PDFs from each of two different cities and quantify extraction quality across the two corpora: characters extracted per page, the share of pages yielding little or no text, and whether any documents are scanned images that would require OCR. Then write a data-quality memo organized around the datasheet categories of Gebru et al. (2021) — motivation, composition, collection process, preprocessing, and recommended uses — documenting what a downstream researcher would need to know before trusting analyses built on these extractions.

9.14 Social History and Public Interest

PDF grew out of a printer language. In 1984 Adobe released PostScript, a programming language for describing pages: a laser printer ran a PostScript program, and the program drew the page (Computer History Museum, 2022). In the summer of 1990, John Warnock, one of Adobe’s founders, wrote a six-page paper called “The Camelot Project.” If every computer could display and print the same page description, he argued, people could send each other documents that looked the same everywhere. Adobe released Acrobat and version 1.0 of the Portable Document Format on June 15, 1993 (Adobe, 2018). PDF kept PostScript’s way of drawing a page, with fonts, coordinates, lines, and images, and dropped the programming: a PDF page is a fixed list of instructions rather than a program to run. With version 2.0, in September 1994, Adobe began giving Acrobat Reader away (Adobe’s announcement, as forwarded to an MIT mailing list), and it published the specification at no charge, so anyone could write software that reads or writes PDFs (Library of Congress).

Later versions added what the first lacked. Linearization, which Acrobat calls “Fast Web View,” came with PDF 1.2 in 1996; a structure tree came with PDF 1.3 in 2000; and tagged PDF, the rules for using that tree to record headings, reading order, and alternative text, came with PDF 1.4 in 2001 (Adobe keeps the PDF Reference for each version). Tags are optional, so software that makes PDFs can leave them out. PDF became an ISO standard in 2008, as ISO 32000-1, and PDF 2.0 followed as ISO 32000-2 in 2017 (Library of Congress). Two narrower standards build on it: PDF/A for archives (ISO 19005-1, from 2005), which requires every font to be embedded and forbids encryption, so a file still opens decades later (Library of Congress); and PDF/UA for accessibility (ISO 14289-1, from 2012), which requires that all of a document’s real content be tagged (Library of Congress).

The same design explains why institutions publish PDFs and why analysts struggle with them. A PDF looks the same on every screen and printer, carries its own fonts, can be signed, and can be kept for decades, which suits a record that must not change. But it describes a printed page: it doesn’t reflow on a phone, it keeps its structure only when someone tags it, and it hands a script positions instead of words. Adobe’s answer, in 2020, was Liquid Mode, a reading mode for phones that uses machine learning to infer a PDF’s structure (Adobe, 2020). The UK’s Government Digital Service drew a different conclusion in 2018: its guidance for GOV.UK publishers is HTML by default, because information in a PDF is harder to find, use, and maintain, and unless made with care is often bad for accessibility (Williams, 2018).

When governments publish minutes, budgets, and filings only as PDFs, they create what Chapter 3 calls “soft enclosure”: records that are public in name and hard to analyze in practice. A picture of a table, like the last page of Boulder’s December 2024 revenue report, is the extreme case, because neither a screen reader nor a script can read its numbers. The Sunlight Foundation, an open-government group whose work began in 2006 (Sunlight Foundation) and which closed in September 2020 (its board chair’s note), argued against PDF-only publishing for years. Machine readability is one of its ten principles for open government data, which warns that information shared as PDF “is very difficult for machines to parse” and asks that such data also be published in formats machines can read (Sunlight Foundation, 2010).

Others built tools for the PDFs that agencies publish anyway. DocumentCloud, envisioned by editors at ProPublica and The New York Times and founded in 2009 with a grant from the Knight Foundation, gives journalists one place to upload, search, annotate, and publish primary source documents; in 2011 it moved to Investigative Reporters and Editors (IRE) (Hickman, 2011). Newsrooms have used it for collaborations as large as the Panama Papers (Knight Foundation, 2019), and because the platform is shared, one newsroom’s processed documents can serve others investigating the same institutions. MuckRock works at the other end, the request: it helps journalists and members of the public file and track public records requests, and publishes what agencies release. By 2018 it was processing thousands of requests a month and had released more than a million pages of government records (MuckRock, 2018). The two merged that year (Pilhofer and Morisy, 2018), and MuckRock now also hosts the Data Liberation Project, which obtains, reformats, cleans, documents, and publishes government datasets of public interest. Their work embodies the ownership value from Chapter 3: public records belong to the public, and technical barriers to access are themselves a form of enclosure that undermines democratic accountability.

Boulder’s council minutes show the same tension at the level of a city. The attendance this chapter rebuilt from the minutes could be published as a table that anyone can sort, and the same is true of votes and the number of people who spoke in public comment; published as PDFs, they take a pipeline like this chapter’s to count. The format is a policy decision with consequences for transparency and accountability. Building the skills to extract data from PDFs serves the oversight value: it lets people outside an institution analyze its records for themselves, which is the work these organizations have championed for decades.

9.15 Common Issues to Debug

  • Garbled text from scanned PDFs: PyPDF extracts text only from PDFs that have a text layer. Truly scanned documents require OCR tools like Tesseract.
  • Table data extracted as a text stream: PyPDF is not a table extraction tool. For tabular data in PDFs, consider pdfplumber or camelot.
  • Regular expressions that work on one document but fail on another: PDF formatting varies even within documents from the same source. Test your patterns on multiple files.
  • Encoding issues: Some PDFs use non-standard character encodings. Use .encode('utf-8', errors='replace') if needed.

9.16 Key Takeaways

PDFs are designed for visual fidelity, not data extraction. pypdf gives you a page’s text in the order it was drawn; pdfplumber gives you where each word sits, which is what a table needs; and regular expressions impose structure on what either extracts. Expect messiness — PDF extraction is reconstruction, not reading — and check every extraction: against a sample coded by hand, against a second tool, against the document’s own totals, and against a second printing of the same figure. The broader lesson connects to Chapter 3: when institutions publish data only in PDF form, they create a practical barrier to the analysis that nominally public records are meant to enable.

9.17 Further Reading

9.18 Appendix: Technical Notes

These notes cover three things the chapter mentions and sets aside: why the city’s server needs a certificate bundle, how to check that two copies of a file are the same, and how to add a text layer to a whole scanned PDF.

9.18.1 The City’s Server and Its Certificate

Your first request to Boulder’s portal from Python will probably fail with SSLError: … CERTIFICATE_VERIFY_FAILED … unable to get local issuer certificate. A server proves who it is with a chain of certificates: its own, signed by an intermediate certificate, which is signed by a root certificate that your computer already trusts. Boulder’s server sends its own certificate but not the intermediate one. Browsers find the missing certificate by themselves; Python doesn’t.

verify=False would make the error go away by turning off the check that you’re talking to the real server, so don’t use it. The book’s bundle, boulder-ca-bundle.pem, holds the standard root certificates plus that one intermediate, and verify=bundle tells requests to check the server against it. If the city repairs its server, the bundle still works. data/ch-09/make_ca_bundle.py in the book’s repository shows how the bundle was made.

9.18.2 Checking That Two Copies Are the Same File

A hash is a fingerprint of a file’s bytes: change one byte and the hash changes. data/ch-09/manifest.csv records each saved copy’s hash, along with its address on the portal and when it was downloaded. Comparing a file’s hash with the manifest’s says whether you have the same file, byte for byte. If you have run the chapter’s cells in order, you have 18 of the manifest’s 20 files:

import hashlib

manifest = pd.read_csv(get_saved_copy("manifest.csv"))  # one row per saved file
checked = 0
differ = []
for row in manifest.itertuples():
    path = PDF_DIR / row.file
    if not path.exists():
        continue  # check only the files you have downloaded
    digest = hashlib.sha256(path.read_bytes()).hexdigest()  # the file's SHA-256 hash, as text
    checked += 1
    if digest != row.sha256:
        differ.append(row.file)
print(checked, "files checked; hashes that differ:", differ)
# 18 files checked; hashes that differ: []

To check a fresh download from the portal, compute hashlib.sha256(response.content).hexdigest() and compare it with the file’s row. The two scanned minutes from 2000 are the exception: the portal builds a new PDF from their page images for every download, so no two downloads have the same hash.

9.18.3 OCR for a Whole File: OCRmyPDF

pytesseract returns text and leaves the PDF as it was. OCRmyPDF does the whole file: it renders each page, runs Tesseract, and lays the recognized text over the image as an invisible layer, where a viewer can select it and pypdf can extract it.

It is harder to install than the libraries in this chapter, because it is a program that runs other programs, Tesseract among them, and chapter 1’s webdata leaves it out. In webdata, conda install -c conda-forge ocrmypdf may be all it takes. If that fails, or OCRmyPDF reports a missing program, follow its installation guide, which gives the steps for each system: Homebrew (brew install ocrmypdf) or MacPorts (sudo port install ocrmypdf) on a Mac, the package manager on Linux, and several steps on Windows.

The minutes of December 19, 2000, which the portal made from scanned pages, have text on only three of their nine pages. mode="redo" replaces any earlier OCR layer and fills in the pages without one:

import ocrmypdf

scan_2000 = get_saved_copy("council-minutes-2000-12-19.pdf")
ocr_copy = PDF_DIR / "council-minutes-2000-12-19-ocr.pdf"  # where to save the new copy
# OCR every page in English, and write a copy with a text layer
ocrmypdf.ocr(scan_2000, ocr_copy, language="eng", mode="redo", progress_bar=False)

# Characters of text on each page, before and after
before = []
for page in PdfReader(scan_2000).pages:
    before.append(len(page.extract_text()))
after = []
for page in PdfReader(ocr_copy).pages:
    after.append(len(page.extract_text()))
print("characters per page before:", before)
print("characters per page after: ", after)
# characters per page before: [2207, 0, 0, 0, 1693, 1575, 0, 0, 0]
# characters per page after:  [2270, 1698, 1663, 1465, 1709, 1597, 1751, 2283, 1164]

It takes a few seconds. To find out whether it read the pages right, compare its text with the image, by hand, for the lines you need:

first_page = PdfReader(ocr_copy).pages[0].extract_text()
# The roll call: from "Deputy Mayor Mock called" to the end of the sentence that ends "absent."
start = first_page.find("Deputy Mayor Mock called")
end = first_page.find("absent.", start) + len("absent.")
for line in first_page[start:end].splitlines():
    print(line.strip())
# Deputy Mayor Mock called the regular December 19, 2000 meeting of the Boulder City
# Council to order at 6:00 p.m. in the Council Chambers.
# Those present were: Deputy Mayor Mock and Councilmembers Corson, Eldridge,
# Lopez, Morzel, Poinsatte and Riggle. Havlick and Toor was absent.

Against the scan, these lines are right word for word, down to the minutes’ own “Havlick and Toor was absent.” Errors remain elsewhere on the page: the first agenda item’s number, “1.”, comes out as “I.” A check by hand covers only the lines you check, so check the ones your analysis will use.

Gebru, Timnit, Jamie Morgenstern, Brenda Vecchione, et al. 2021. “Datasheets for Datasets.” Communications of the ACM 64 (12): 86–92. https://doi.org/10.1145/3458723.
Salganik, Matthew J. 2018. Bit by Bit: Social Research in the Digital Age. Princeton University Press. https://www.bitbybitbook.com/.