Purrx

Measure text with real font metrics

Work out how wide text will be in PowerPoint before the file is opened, by adding up real character widths from the font: the foundation of text fitting.

10 min+25 XPHands-on

Everything in the next four lessons, wrapping lines, shrinking text, sizing boxes to their content, depends on one question: how wide is this text? A browser can answer by drawing it. We can't: our code runs on a server and PowerPoint only draws the text when someone opens the file. So we measure it ourselves.

  • i222 / 1000
  • l222 / 1000
  • a556 / 1000
  • M833 / 1000
  • W944 / 1000

At 20pt: width = sum of widths ÷ 1000 × 20. "Wi" = (944 + 222) ÷ 1000 × 20 = 23.3 pt

In Arial, a W is more than four times as wide as an i. Counting characters can't tell you how wide text is; adding up each character's width can.

Font metrics

A font file stores measurements for every character: its . The one we need is the width, stored in thousandths of the font size. In Arial, W is 944 and i is 222.

This lesson adds src/fonts.js with Arial's widths for every character from space to ~, regular and bold, plus a few common extras like and curly quotes. Anything else gets an average width.

The arithmetic

  • charWidth(char, bold): look the character up. The tables start at the space character (code 32), so the position in the table is char.codePointAt(0) - 32.
  • measureText(text, fontSize, bold): add up the widths and convert: total ÷ 1000 × fontSize.
Under the hood — Why Arial, and what if the user has a different font?

Arial (or a metric-compatible copy like Arimo) is available almost everywhere PowerPoint files are opened, so layout computed with its widths matches what people see. The production PPTX Lab measures several fonts this way, generated from the font files themselves.

If a machine substitutes a different font, lines can wrap slightly differently. That's one reason the engine will leave a little safety room when fitting text, and why it only uses widely available fonts.

Key takeaways

  • Characters have different widths, so counting them can't tell you how wide text is.
  • Font files store each character's width in thousandths of the font size.
  • Width in points = sum of character widths ÷ 1000 × font size.

Sign in to run the exercise

Reading is free. Writing code here needs an account so we have somewhere to keep your Gemini key and the +25 XP you are about to earn.