DEV Community

Nahuel Giudizi
Nahuel Giudizi

Posted on

react-pdf was squeezing my letters: how I patched its line breaker and justifier

I build Folium, a free resume builder. The live preview and the PDF you download come from the same renderer, @react-pdf/renderer (4.9, with @react-pdf/textkit 7.0.1), so whatever the layout engine does, people see it twice.

A user told me their resume "didn't look well arranged". They were right, and the cause was not in my templates. It was in how textkit breaks and justifies lines. This post is what I measured, the three changes I made, and how I keep them from silently disappearing on the next npm install.

What was wrong

I rendered 30 templates with 5 kinds of content each (sample data, a realistic resume, the same one justified, and both again with a bigger font) and measured every line with PyMuPDF. Three problems showed up:

  1. Letters squeezed in left-aligned text. About 1 line in 8 had its letters compressed, by up to 2%. Not justified text: plain left-aligned paragraphs.
  2. Letters stretched in justified text. On lines with few words, the gaps were filled by spreading the letters apart, up to +24% on the worst lines.
  3. Huge gaps in narrow columns. Sidebars set to justify, with no hyphenation, ended up with rivers of white space.

Cause 1: the line breaker lets left-aligned lines overflow

textkit uses a Knuth-Plass style line breaker. Each space is a piece of "glue" that can stretch and shrink. The defaults:

const opts = { width: 3, stretch: 6, shrink: 9 };
// per space: shrink = (width * opts.width) / opts.shrink  -> a third of the space
Enter fullscreen mode Exit fullscreen mode

That shrink is applied whatever the alignment, so the breaker happily accepts a left-aligned line that is a bit wider than the box, counting on squeezing the spaces later. Then, when each line is aligned:

const shouldJustify = align === 'justify' || lineWidth > line.box.width;
Enter fullscreen mode Exit fullscreen mode

A line that overflows gets sent to the justifier even if it is left-aligned. The justifier can only take a little out of each space, so it takes the rest out of the letters.

Fix: only justified text is allowed to count on shrinking spaces. A left-aligned line can never be wider than its box, so it never reaches the justifier.

const shrink = align === 'justify' ? (width * opts.width) / opts.shrink : 0;
Enter fullscreen mode Exit fullscreen mode

Cause 2: the justifier moves letters, not just spaces

The justifier distributes the extra (or missing) width with priority factors. Spaces go first, but once each space has moved beyond a small limit, letters start absorbing the difference (EXPAND_CHAR_FACTOR is 37/256 per side). That is where the +24% came from.

Fix: letters get a factor of 0, spaces get a very large one, so all of the adjustment always fits in the spaces:

const EXPAND_WHITESPACE_FACTOR = { before: 50, after: 50, priority: WHITESPACE_PRIORITY, unconstrained: false };
const EXPAND_CHAR_FACTOR       = { before: 0,  after: 0,  priority: LETTER_PRIORITY,     unconstrained: false };
const SHRINK_WHITESPACE_FACTOR = { before: -50, after: -50, priority: WHITESPACE_PRIORITY, unconstrained: false };
const SHRINK_CHAR_FACTOR       = { before: 0,  after: 0,  priority: LETTER_PRIORITY,     unconstrained: false };
Enter fullscreen mode Exit fullscreen mode

Why not just mark spaces as unconstrained? I tried. The unconstrained path in getDistances only adds the "before" side of a space when the glyph before it is also unconstrained, so half of the adjustment gets lost and justified lines come out short. Large constrained factors avoid that path entirely.

Cause 3: narrow columns should not be justified

Without hyphenation, a column of about 20 to 25 characters per line cannot be justified nicely. No factor fixes that. So below 25 em, justified text is laid out like its last line (usually left-aligned):

const FOLIUM_NARROW_EM = 25;
const folNarrowJustify = (attributes, width) => {
  if (!attributes || attributes.align !== 'justify' || !(width > 0)) return attributes;
  if (width >= (attributes.fontSize || 12) * FOLIUM_NARROW_EM) return attributes;
  return Object.assign({}, attributes, { align: attributes.alignLastLine || 'left' });
};
Enter fullscreen mode Exit fullscreen mode

It is applied in two places: when breaking lines (so the breaker treats the paragraph as not justified) and when aligning each line.

Patching node_modules without losing the patch

These are changes inside node_modules/@react-pdf/textkit/lib/textkit.js, applied by a postinstall script. Each patch is a find/replace on an exact fragment of the library. The rule I follow: if neither the original fragment nor the patched one is found, the script fails. A library update must make me look at the patch again; it must never drop it silently. That way the build, the Cloudflare workers, the tests and my scripts all see the same textkit.

Tests that fail without the patch

The test lays out a real paragraph with textkit at 30 widths (18 to 44 em at 10 pt), left and justified, with hyphenation turned off like in the templates, and checks four things:

  • every letter keeps its natural advance (difference under 0.001 pt), in every width and alignment;
  • left-aligned lines never exceed the box;
  • in a wide column, justified lines fill the box using the spaces;
  • under 25 em, justified text breaks into exactly the same lines as left-aligned text.

Three of the four fail on unpatched textkit, which is how I know the patch is still doing something.

Result

Across 150 PDFs (30 templates times 5 cases), no document changed its number of pages, and no line has squeezed or stretched letters anymore. Justified resumes look justified in the main column and calm in the sidebars.

If you use react-pdf with justified text or long paragraphs, it is worth measuring a few of your PDFs: open them with PyMuPDF, compare each glyph's advance with the font's natural width, and see how many lines were "fixed" by moving letters. I was surprised by how many.

Top comments (1)

Collapse
 
colinbarnes profile image
Colin Barnes •

The line that explains the left-aligned squeezing is shouldJustify = align === 'justify' || lineWidth > line.box.width. Once the breaker has accepted a slightly-too-wide line (shrink is still on the glue even for left-aligned text), that condition sends it to the justifier, and whatever the spaces can't absorb comes out of the letters. Zeroing shrink unless the paragraph is actually justified is the right fix.

I would have tried marking spaces unconstrained, too. It's not obvious that getDistances only adds the "before" side when the previous glyph is also unconstrained, so half the adjustment vanishes and the line comes out short. Staying on the constrained path with large factors makes sense once you've hit that.

The postinstall rule — fail if neither the original fragment nor the patched one is found — is how I'd want a typography patch in node_modules to behave across CI and Cloudflare workers.