Install grounding skill

Turning a PDF Measurement Report into a Reviewable Summary

Read every table in a PDF report and append a final page that answers the reviewer's first questions: how many readings, the range, the mean, and what's wrong with the data.

December 2, 20267 min readIntermediateLegalProcessingGrounding

A measurement report is only useful if someone can review it quickly. With PyMuPDF, about 100 lines of Python read every table in a PDF report and append a final page that answers the reviewer's first questions: how many readings, the range, the mean, and what's wrong with the data.

The problem is familiar to anyone in quality assurance. A supplier sends a report with 120 readings spread across five pages. The reviewer has a spec to check, and somewhere in those tables are a blank cell and a reading in the wrong unit. Scanning by eye is slow, and it's exactly how those problems get missed.

This notebook builds a sample report, reads its tables, and appends the summary page.

Setup

You need PyMuPDF with find_tables() and insert_htmlbox(). This notebook was tested with PyMuPDF 2.2.

%pip install -q pymupdf
Output
[notice] A new release of pip is available: 26.0.1 -> 26.3
[notice] To update, run: pip install --upgrade pip
Note: you may need to restart the kernel to use updated packages.
import pymupdf
print(pymupdf.__version__)
Output
2.2

The scenario

A machine shop anodises aluminium brackets for an aerospace customer, whose spec requires a coating thickness of 25 µm ± 5 µm (20.0 to 30.0 µm). The inspector measures 30 parts at four locations each with an eddy-current gauge, giving 120 readings.

The report is a 6-page PDF: a cover page, then ruled tables on pages 2 to 6 with four columns: Part ID, Location, Thickness and Unit.

The next cell creates that report as sample_report.pdf. It plants the kinds of problems real reports contain: two skipped readings, and two taken with the gauge set to imperial. A reading of 0.98 mil is about 24.9 µm, so the part is fine, but the number would wreck an average if it slipped in unnoticed. Skip this cell if you have your own report.

import random

import pymupdf

random.seed(7)

PARTS = [f"BRK-{n:04d}" for n in range(401, 431)]       # 30 parts
LOCATIONS = ["Flange A", "Flange B", "Flange C", "Web"]  # 4 readings each
ROWS_PER_PAGE = 24

# Build 120 readings: (part, location, value, unit)
rows = []
for part in PARTS:
    for loc in LOCATIONS:
        value = round(min(max(random.gauss(25.2, 2.0), 20.4), 29.6), 1)
        rows.append([part, loc, f"{value:.1f}", "µm"])

# Deliberate problems and extremes for the reviewer to find
rows[7][2:] = ["31.4", "µm"]      # maximum
rows[33][2:] = ["", ""]           # missing value
rows[38][2:] = ["0.98", "mil"]    # unexpected unit
rows[41][2:] = ["1.03", "mil"]    # unexpected unit
rows[66][2:] = ["19.8", "µm"]     # minimum
rows[101][2:] = ["n/a", ""]       # missing value written as "n/a"

doc = pymupdf.open()

# Cover page
page = doc.new_page()
page.insert_htmlbox(
    pymupdf.Rect(60, 80, 535, 400),
    """
    <h1 style="font-family:sans-serif">Coating Thickness Inspection Report</h1>
    <p style="font-family:sans-serif">Part: Anodised bracket, drawing BRK-200 rev C<br>
    Batch: 2026-11-B<br>
    Specification: 25 µm ± 5 µm (20.0 to 30.0 µm)<br>
    Instrument: eddy-current coating thickness gauge<br>
    Readings: 30 parts × 4 locations</p>
    """,
)

# Measurement tables
headers = ["Part ID", "Location", "Thickness", "Unit"]
col_x = [60, 180, 320, 430, 535]
row_h = 22

for start in range(0, len(rows), ROWS_PER_PAGE):
    page = doc.new_page()
    page.insert_text((60, 60), "Measurements", fontsize=14, fontname="hebo")
    chunk = [headers] + rows[start:start + ROWS_PER_PAGE]
    top = 80
    for i, row in enumerate(chunk):
        y0 = top + i * row_h
        font = "hebo" if i == 0 else "helv"
        for j, cell in enumerate(row):
            page.insert_text((col_x[j] + 6, y0 + 15), cell, fontsize=10, fontname=font)
    # Ruling lines so find_tables() sees a proper grid
    bottom = top + len(chunk) * row_h
    for i in range(len(chunk) + 1):
        y = top + i * row_h
        page.draw_line((col_x[0], y), (col_x[-1], y), width=0.5)
    for x in col_x:
        page.draw_line((x, top), (x, bottom), width=0.5)

doc.save("sample_report.pdf")
print(f"Wrote sample_report.pdf with {doc.page_count} pages and {len(rows)} readings")
Output
Wrote sample_report.pdf with 6 pages and 120 readings

Here's page 3 of the sample report, with one missing reading and two in mils:

from IPython.display import Image

Image(pymupdf.open("sample_report.pdf")[2].get_pixmap(dpi=80).tobytes("png"))
Output
Cell output

How it works

The script does four things, each a few lines of PyMuPDF.

  1. Find the tables. page.find_tables() detects ruled tables on each page, and table.extract() returns their cells as lists of strings, header first.
  2. Keep only measurement tables. A table counts if its header row has the value column ("Thickness") and the unit column ("Unit"). Every row keeps its page number, so the summary can point back to it.
  3. Sort each reading. A cell that won't parse as a number is missing. A number in another unit is flagged. Everything else goes into the statistics.
  4. Append a page. doc.new_page() matches the report's page size, and page.insert_htmlbox() lays out the summary from a few lines of HTML and CSS.

One detail worth knowing: norm() maps the Greek mu (U+03BC) to the micro sign (U+00B5). They look identical, but a plain string comparison treats them as different units.

import html
import statistics


def norm(text):
    """Tidy a cell: collapse whitespace and treat the Greek mu as the micro sign."""
    return " ".join((text or "").split()).replace("μ", "µ")


def read_measurements(doc, value_col, unit_col):
    """Yield one dict per table row that has a value column, across all pages."""
    for page in doc:
        for table in page.find_tables().tables:
            rows = table.extract()
            if not rows:
                continue
            header = [norm(c) for c in rows[0]]
            if value_col not in header or unit_col not in header:
                continue  # not a measurement table
            vi, ui = header.index(value_col), header.index(unit_col)
            for cells in rows[1:]:
                cells = [norm(c) for c in cells]
                yield {
                    "page": page.number + 1,  # 1-based for humans
                    "label": " ".join(c for i, c in enumerate(cells) if i not in (vi, ui) and c),
                    "raw": cells[vi],
                    "unit": cells[ui],
                }


def classify(readings, unit):
    """Split readings into usable values, missing values and wrong units."""
    good, missing, wrong_unit = [], [], []
    for r in readings:
        try:
            r["value"] = float(r["raw"])
        except ValueError:
            missing.append(r)  # blank, dash, "n/a", etc.
            continue
        (good if r["unit"] == unit else wrong_unit).append(r)
    return good, missing, wrong_unit


def summary_html(good, missing, wrong_unit, unit, value_col):
    esc = html.escape
    lo = min(good, key=lambda r: r["value"])
    hi = max(good, key=lambda r: r["value"])
    mean = statistics.fmean(r["value"] for r in good)

    def where(r):
        return f"page {r['page']}, {esc(r['label'])}"

    def item_list(items, show_value):
        if not items:
            return "<p>None.</p>"
        lis = "".join(
            f"<li>Page {r['page']}: {esc(r['label'])}"
            + (f", {esc(r['raw'])} {esc(r['unit'])}" if show_value else "")
            + "</li>"
            for r in items
        )
        return f"<ul>{lis}</ul>"

    return f"""
    <h2>Measurement Summary: {esc(value_col)} ({esc(unit)})</h2>
    <table>
      <tr><td>Readings in {esc(unit)}</td><td>{len(good)}</td></tr>
      <tr><td>Minimum</td><td>{lo['value']:g} {esc(unit)} ({where(lo)})</td></tr>
      <tr><td>Maximum</td><td>{hi['value']:g} {esc(unit)} ({where(hi)})</td></tr>
      <tr><td>Mean</td><td>{mean:.1f} {esc(unit)}</td></tr>
    </table>
    <h3>Missing values ({len(missing)})</h3>
    {item_list(missing, show_value=False)}
    <h3>Unexpected units ({len(wrong_unit)}): excluded from statistics</h3>
    {item_list(wrong_unit, show_value=True)}
    """

Read and classify the readings

INPUT = "sample_report.pdf"
OUTPUT = "sample_report_summarised.pdf"
UNIT = norm("µm")
VALUE_COL, UNIT_COL = "Thickness", "Unit"

doc = pymupdf.open(INPUT)
readings = list(read_measurements(doc, VALUE_COL, UNIT_COL))
good, missing, wrong_unit = classify(readings, UNIT)

print(f"{len(readings)} rows read: {len(good)} in {UNIT}, "
      f"{len(missing)} missing, {len(wrong_unit)} in other units")
for r in missing + wrong_unit:
    print(f"  page {r['page']}: {r['label']} -> {r['raw']!r} {r['unit']}")
Output
120 rows read: 116 in µm, 2 missing, 2 in other units
  page 3: BRK-0409 Flange B -> '' 
  page 6: BRK-0426 Flange B -> 'n/a' 
  page 3: BRK-0410 Flange C -> '0.98' mil
  page 3: BRK-0411 Flange B -> '1.03' mil

Append the summary page

width, height = doc[-1].rect.width, doc[-1].rect.height
page = doc.new_page(width=width, height=height)
box = page.rect + (50, 50, -50, -50)
css = ("* {font-family: sans-serif; font-size: 10pt;} h2 {font-size: 15pt;} h3 {font-size: 12pt;}"
       " table {border-collapse: collapse; width: 100%;} td {border: 1px solid #999; padding: 3pt 6pt;}")
_, scale = page.insert_htmlbox(box, summary_html(good, missing, wrong_unit, UNIT, VALUE_COL), css=css)
if scale < 1:
    print(f"Note: summary was scaled to {scale:.0%} to fit on one page.")

doc.save(OUTPUT, garbage=3, deflate=True)
print(f"Summary added as page {page.number + 1} of {OUTPUT}")
Output
Summary added as page 7 of sample_report_summarised.pdf
Image(page.get_pixmap(dpi=100, clip=pymupdf.Rect(30, 30, 565, 300)).tobytes("png"))
Output
Cell output

The mean sits comfortably in spec, but both extremes fall just outside 20 to 30 µm. That's the first thing the reviewer needs to know, and the page reference takes them straight to the row.

Three design decisions

Flag units, don't convert them. Converting 0.98 mil to 24.9 µm is easy, but a unit mismatch can mean a mis-configured gauge, which may affect other readings too. The script excludes those readings from the statistics and lists them, so a person decides.

Show where the extremes are. A bare minimum of 19.8 µm tells the reviewer something is out of spec. Adding "page 4, BRK-0417 Flange C" tells them which part to quarantine.

Append, don't create a separate file. The customer archives one PDF per batch. Keeping the summary inside the report means the evidence and the conclusion always travel together.

Beyond coating thickness

The same pattern fits any report where readings sit in tables across pages: tensile strength in MPa on material test certificates, concrete cover in mm on site inspection records, gas concentrations in ppm on environmental monitoring logs, or calibration results. Change VALUE_COL and UNIT, and the code works unchanged.

Some variations:

  • Tables without ruling lines: try page.find_tables(strategy="text").
  • Value and unit in one cell ("24.6 µm"): split the cell with a regular expression before classifying.
  • Unit only in the header ("Thickness (µm)"): read it once and apply it to every row.
  • Spec limits: list readings outside 20 to 30 µm with their pages, the same way as missing values.
  • Decimal commas (24,6): replace the comma before calling float().
  • Scanned reports have no text layer: add one with an OCR tool such as OCRmyPDF first.

Discuss This Article with the Community

Have a question, a different approach, or something you built after reading this? Share it on the forum or join the Discord, we'd love to hear from you.

PyMuPDF Logo

© 2026 Artifex Software Inc. All rights reserved.