DEV Community

GoToolsOnline
GoToolsOnline

Posted on

Boxes instead of letters in your PDF? That's a font problem, not an encoding problem

You generate a PDF from some text and part of it comes out as empty rectangles: □□□. Or you see café where you typed café. These look like the same bug. They aren't, and the fix for one does nothing for the other.

Two different failures

Mojibake (café, —) means the bytes were decoded with the wrong encoding. The text itself is now wrong: the characters in your string are different characters.

>>> "café".encode("utf-8").decode("latin-1")
'café'
Enter fullscreen mode Exit fullscreen mode

No font will fix that. You fix it where the text is read: decode the input as UTF-8 (or whatever it really is) before it ever reaches the PDF code.

Boxes (often called "tofu") mean the text is correct, but the font has no glyph for that character. The PDF renderer knows it should draw "é" or "क" or "中", looks it up in the font, finds nothing, and draws the font's fallback shape instead, which is usually an empty box.

How to tell which one you have

Copy the broken text out of the PDF and paste it somewhere else. If the pasted text is right, it was a font problem. If it's still garbage, it was an encoding problem upstream.

You can also check the font directly. With fontTools:

from fontTools.ttLib import TTFont

font = TTFont("DejaVuSans.ttf")
cmap = font.getBestCmap()          # code point -> glyph name

text = "Price: €50 — naïve 中文"
missing = sorted({ch for ch in text if not ch.isspace() and ord(ch) not in cmap})
print(missing)
Enter fullscreen mode Exit fullscreen mode

Anything in missing will come out as a box if that is the only font you use.

What actually fixes boxes

  • Use a font that covers the script. A Latin-only font will never draw Devanagari or Chinese, whatever you do to the text.
  • Use font fallback. Good generators try a list of fonts per character, so Latin text uses your main font and other scripts fall through to a font that has them.
  • Embed the font. If the PDF relies on fonts installed on the reader's machine, it can look fine for you and broken for someone else.
  • Expect some leftovers. Some emoji and rare symbols aren't in common text fonts at all. And for complex scripts like Devanagari or Arabic, copying text back out of a PDF may not paste cleanly even when it displays correctly, because the PDF stores shaped glyphs, not the original characters.

A quick checklist

  1. Weird letter pairs like é? Fix decoding, not fonts.
  2. Empty boxes, but copy-paste gives the right text? Add a font with that script, or fallback.
  3. Looks right on your machine only? Embed the font.

Disclosure: I run GoToolsOnline. Its free Text to PDF tool reads your text as UTF-8 and falls back to wider-coverage fonts for Greek, Cyrillic, CJK, Devanagari and Arabic. Some emoji can still show as boxes, which the page says plainly.

Top comments (0)