Make Certificates from a Roster Without Clipping Long Names
Measure each name on a roster against the space on a certificate template, reduce the font size until it fits, and flag names that still won't fit at the minimum size or use characters the font can't draw.
A certificate template has a fixed space for the name. Most names fit at the design size, but a roster always has a few long ones, and a long name drawn at the design size runs past the edge of that space or off the page. Checking every certificate by eye doesn't scale.
This notebook does it with PyMuPDF:
- Read the roster and the name area of the certificate template.
- Measure each name in the certificate font and reduce the font size until it fits the space.
- Flag names that still won't fit at the minimum size, and names with characters the font can't draw.
- Make one certificate per fitted name, and write a report of every name with its font size or the reason it was flagged.
- Check the saved certificates: every name is there, unchanged, and inside the name area.
Tested with PyMuPDF 2.2.
%pip install -q pymupdfSample template and roster
The template is a landscape A4 certificate with a blank space for the name. NAME_BOX is that space, in PDF points from the top-left corner of the page. The thin line under it is where the name sits. To use your own template, set template_path and measure NAME_BOX from it, for example by opening it in a viewer that shows coordinates, or by drawing a test rectangle on a copy until it lines up.
The roster is a CSV file with one name per row. It includes some long names, a name with Polish characters, and a name in Chinese characters.
import csv
import pymupdf
NAME_BOX = pymupdf.Rect(121, 230, 721, 300) # the space for the name, in points
NAVY = (0.10, 0.17, 0.35)
def centred(page, y, text, font, size, color=NAVY):
"""Write text centred across the page with its baseline at y."""
x = (page.rect.width - font.text_length(text, size)) / 2
tw = pymupdf.TextWriter(page.rect)
tw.append((x, y), text, font=font, fontsize=size)
tw.write_text(page, color=color)
def make_template(path):
doc = pymupdf.open()
page = doc.new_page(width=842, height=595) # A4 landscape
page.draw_rect(page.rect + (24, 24, -24, -24), color=NAVY, width=3)
page.draw_rect(page.rect + (32, 32, -32, -32), color=NAVY, width=0.75)
bold, roman, italic = pymupdf.Font("tibo"), pymupdf.Font("tiro"), pymupdf.Font("tiit")
centred(page, 140, "Certificate of Completion", bold, 40)
centred(page, 200, "This certifies that", italic, 18)
page.draw_line((NAME_BOX.x0, NAME_BOX.y1 + 4), (NAME_BOX.x1, NAME_BOX.y1 + 4), color=(0.6, 0.6, 0.6), width=0.75)
centred(page, 350, "has completed the course", italic, 18)
centred(page, 390, "Advanced PDF Processing", bold, 24)
for x, label in ((150, "Date"), (512, "Course Director")):
page.draw_line((x, 480), (x + 180, 480), color=NAVY, width=0.75)
tw = pymupdf.TextWriter(page.rect)
tw.append((x + (180 - roman.text_length(label, 12)) / 2, 498), label, font=roman, fontsize=12)
tw.write_text(page, color=NAVY)
doc.save(path, garbage=3, deflate=True)
ROSTER = [
"Ana Li",
"Tomás O'Connell",
"María José García-Hernández",
"Łukasz Brzęczyszczykiewicz",
"Dr. Oluwaseun Adebayo-Okonkwo",
"Siobhán Ní Mhaonaigh", # two spaces: cleaned up below
"Alexandra Konstantina Papadopoulou-Richardson",
"Maximiliana Theodora Evangelina Constantinopoulou-Fairweather-Ashworth",
"陈伟",
]
make_template("certificate_template.pdf")
with open("roster.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["name"])
writer.writerows([n] for n in ROSTER)
template_path = "certificate_template.pdf"
roster_path = "roster.csv"
with open(roster_path, newline="", encoding="utf-8-sig") as f:
names = [" ".join(row["name"].split()) for row in csv.DictReader(f)] # trim and collapse spaces
names = [n for n in names if n]
print(f"{len(names)} names in {roster_path}")9 names in roster.csv
Step 1: Measure each name and choose a font size
Font.text_length() gives the width of a string at a given font size, using the font's own glyph widths. The width grows in proportion to the size, so measuring once at 1 pt gives the largest size that fits: the available width divided by the width at 1 pt.
Each name gets the design size, MAX_SIZE, if it fits. Otherwise it gets the largest size that fits, rounded down to the nearest half point so the rounding can never push it over. PADDING keeps a little space at each end so a name never touches the edge of the area.
A name is flagged instead of fitted when:
- too long: even at
MIN_SIZEit is wider than the space. Below a certain size a name stops looking like the main line of the certificate, so it's better to flag it than to shrink it further. - missing glyphs: the font has no glyph for some of its characters, which would print as blanks or boxes.
Font.has_glyph()checks each character.
import math
FONT = pymupdf.Font("tibo") # Times Bold, the certificate's name font
MAX_SIZE = 40 # design size for the name
MIN_SIZE = 20 # smallest size we accept
PADDING = 12 # space kept clear at each end, in points
AVAILABLE = NAME_BOX.width - 2 * PADDING
def fit_name(name, font=FONT, available=AVAILABLE, max_size=MAX_SIZE, min_size=MIN_SIZE):
"""Choose a font size for the name. Returns a dict with the size, or with the reason it was flagged."""
missing = list(dict.fromkeys(c for c in name if not font.has_glyph(ord(c))))
if missing:
return {"name": name, "status": "missing glyphs", "size": None,
"detail": "font has no glyph for " + " ".join(missing)}
width_1pt = font.text_length(name, 1)
size = min(max_size, math.floor(available / width_1pt * 2) / 2)
if size < min_size:
need = font.text_length(name, min_size)
return {"name": name, "status": "too long", "size": None,
"detail": f"{need:.0f} pt wide at {min_size} pt, space is {available:.0f} pt"}
assert font.text_length(name, size) <= available
status = "fits" if size == max_size else "reduced"
return {"name": name, "status": status, "size": size,
"detail": f"{font.text_length(name, size):.0f} of {available:.0f} pt"}
results = [fit_name(n) for n in names]
for r in results:
size = f'{r["size"]:>4} pt' if r["size"] else " -- "
print(f'{r["status"]:<15} {size} {r["name"][:45]:<45} {r["detail"]}')fits 40 pt Ana Li 119 of 576 pt fits 40 pt Tomás O'Connell 301 of 576 pt fits 40 pt María José García-Hernández 520 of 576 pt fits 40 pt Łukasz Brzęczyszczykiewicz 485 of 576 pt reduced 38.0 pt Dr. Oluwaseun Adebayo-Okonkwo 569 of 576 pt fits 40 pt Siobhán Ní Mhaonaigh 396 of 576 pt reduced 26.5 pt Alexandra Konstantina Papadopoulou-Richardson 576 of 576 pt too long -- Maximiliana Theodora Evangelina Constantinopo 669 pt wide at 20 pt, space is 576 pt missing glyphs -- 陈伟 font has no glyph for 陈 伟
The short names keep the design size of 40 pt. The longer names are reduced, down to 26.5 pt for the longest one that still fits. The 70-character name would need about 670 pt even at 20 pt, more than the 576 pt available, so it is flagged. The Chinese name is flagged because Times Bold has no Chinese characters.
Step 2: Make the certificates
Each fitted name is written onto a copy of the template, centred in the name area with its baseline on the line, so names of every size sit in the same place. All certificates go into one PDF, one page per person, with a bookmark for each name so a particular certificate is easy to find.
Flagged names get no certificate. Making one anyway would mean a clipped name, a name smaller than the design allows, or blank boxes, which is what this notebook is meant to prevent.
BASELINE = NAME_BOX.y1 - 4 # names sit just above the line
def write_name(page, name, size, font=FONT, box=NAME_BOX):
x = box.x0 + (box.width - font.text_length(name, size)) / 2
tw = pymupdf.TextWriter(page.rect)
tw.append((x, BASELINE), name, font=font, fontsize=size)
tw.write_text(page, color=NAVY)
template = pymupdf.open(template_path)
out = pymupdf.open()
toc = []
for r in results:
if r["size"] is None:
continue
out.insert_pdf(template)
write_name(out[-1], r["name"], r["size"])
r["page"] = out.page_count
toc.append([1, r["name"], out.page_count])
out.set_toc(toc)
out.set_metadata({"title": "Certificates of Completion"})
out.save("certificates.pdf", garbage=3, deflate=True)
print(f"certificates.pdf: {out.page_count} certificates")certificates.pdf: 7 certificates
Here is the certificate for the longest name that fits, at its reduced size:
from IPython.display import Image
longest = max((r for r in results if r["size"]), key=lambda r: len(r["name"]))
out[longest["page"] - 1].get_pixmap(dpi=60).save("certificate_preview.png")
Image("certificate_preview.png")Step 3: Write the report
The report lists every name on the roster, in roster order, with what happened to it: the font size and certificate page, or why it was flagged. Send the flagged names back to whoever owns the roster. Usually the fix is a shorter form of the name agreed with the person, or a template with a wider name area or a font that covers their script.
with open("certificates_report.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "status", "size", "page", "detail"])
writer.writeheader()
writer.writerows({"page": None, **r} for r in results)
flagged = [r for r in results if r["size"] is None]
print(f"{len(results) - len(flagged)} certificates made, {len(flagged)} names need attention:")
for r in flagged:
print(f' {r["name"]}: {r["status"]} ({r["detail"]})')7 certificates made, 2 names need attention: Maximiliana Theodora Evangelina Constantinopoulou-Fairweather-Ashworth: too long (669 pt wide at 20 pt, space is 576 pt) 陈伟: missing glyphs (font has no glyph for 陈 伟)
Step 4: Check the saved certificates
Re-open certificates.pdf and read each name back from the page itself. On every certificate, the text drawn in the name area must be exactly the roster name, at the size chosen, and its left and right edges must be inside NAME_BOX. The check reads what is on the page, so it would also catch a name that went wrong after the size was chosen.
def name_on_page(page, box=NAME_BOX):
"""The text spans whose baseline is in the name area, as (text, size, bbox)."""
spans = []
for block in page.get_text("dict")["blocks"]:
for line in block.get("lines", []):
for span in line["spans"]:
if box.y0 <= span["origin"][1] <= box.y1:
spans.append((span["text"], span["size"], pymupdf.Rect(span["bbox"])))
return spans
check = pymupdf.open("certificates.pdf")
fitted = [r for r in results if r["size"]]
assert check.page_count == len(fitted), "one page per fitted name"
for r in fitted:
spans = name_on_page(check[r["page"] - 1])
text = "".join(s[0] for s in spans)
left, right = min(s[2].x0 for s in spans), max(s[2].x1 for s in spans)
assert text == r["name"], f'page {r["page"]}: found {text!r}'
assert all(abs(s[1] - r["size"]) < 0.01 for s in spans), f'page {r["page"]}: wrong size'
assert NAME_BOX.x0 <= left and right <= NAME_BOX.x1, f'page {r["page"]}: name outside the name area'
print(f'page {r["page"]} {r["size"]:>4} pt {left - NAME_BOX.x0:5.1f} pt clear left, {NAME_BOX.x1 - right:5.1f} pt clear right {r["name"]}')
print("\nall certificates passed")page 1 40 pt 240.5 pt clear left, 240.5 pt clear right Ana Li page 2 40 pt 149.4 pt clear left, 149.4 pt clear right Tomás O'Connell page 3 40 pt 40.0 pt clear left, 40.0 pt clear right María José García-Hernández page 4 40 pt 57.3 pt clear left, 57.3 pt clear right Łukasz Brzęczyszczykiewicz page 5 38.0 pt 15.5 pt clear left, 15.5 pt clear right Dr. Oluwaseun Adebayo-Okonkwo page 6 40 pt 102.2 pt clear left, 102.2 pt clear right Siobhán Ní Mhaonaigh page 7 26.5 pt 12.1 pt clear left, 12.1 pt clear right Alexandra Konstantina Papadopoulou-Richardson all certificates passed
Limits to know
- Width only. The size is chosen from the name's width. A single-line name area is short enough that height is no problem at sizes up to
MAX_SIZE, but check it if you raiseMAX_SIZEor use a tall display font. - One line. A name that is too long is flagged rather than split over two lines. Breaking a name in the right place, between given names and family names, depends on the name and the culture, so it's a decision for a person, not the script.
- Base-14 fonts cover Latin, Greek and Cyrillic, not every script. For names in other scripts, load a font that covers them with
pymupdf.Font(fontfile=...). The samefit_name()then measures and checks it. Names that mix scripts may need a font for each, or a font that covers both. - No kerning.
Font.text_length()adds up glyph widths without kerning, so the measured width is at most slightly wider than the drawn text. That errs on the safe side.
Next steps
Font.text_length(),Font.has_glyph()andTextWriterin the PyMuPDF documentation- To send each person their own file, save each page of
certificates.pdfas a separate PDF withDocument.insert_pdf()and a new document per page.
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.