Build-Time OG Cards with Pillow and CJK Line Breaking A developer added a build-time Open Graph image generator to a Python static site generator, producing a 1200×630 PNG per post with Pillow 11.3.0 and variable Noto Sans fonts for Latin, Japanese and Korean. The 142-line script picks the largest of six fixed font sizes that fits a title in four lines and wraps Japanese titles without spaces, after three earlier cards broke Japanese titles at awkward points. Cards are drawn during the build so no post ships without one, and the rendered PNGs are the only font-derived assets deployed. Until this week, no post on this blog had an og:image . Shared links showed a bare text preview, and the JSON-LD for each article had no image , which is one of the fields search engines look for in article markup. This post is for anyone running a static site who wants a generated card per post, especially with Japanese or Korean titles. It covers the generator we added to our Python static site generator https://tlaboratory.net/en/python-static-site-generator-multilingual/ , and the three wrong cards it drew before Japanese titles broke in sensible places. Every post now gets a 1200×630 PNG, drawn during the build by scripts/og card.py , 142 lines of Pillow code: Drawing everything in code means there is no image licensing question. Nothing is a stock photo or an AI-generated picture. The only third-party asset is the font, and that has a clear license next section . Generating at build time also means a new post can never ship without a card: the build calls draw card for every post it collects. scripts/build.py trimmed for p in posts lang : … draw card OUT / "static" / "og" / lang / f"{p 'slug' }.png", p "title" , p "cat" "name" , lang, p "category" , brand=site "brand" p "og image" = f"{base}/static/og/{lang}/{p 'slug' }.png" draw card OUT / "static" / "og" / "default.png", site "langs" "en" "tagline" , "t.laboratory", "en", "web", brand=site "brand" fig:ogcard-pipeline We use three variable fonts from the google/fonts repository on GitHub: Noto Sans for Latin about 2.0 MB , Noto Sans JP about 9.6 MB and Noto Sans KR about 10.4 MB . All three are under the SIL Open Font License 1.1. The OFL restricts selling or renaming the font files, but it allows commercial use of what you render with them, so a PNG card is fine. The font files live in an assets folder of the repository and are never deployed; only the rendered PNGs go to the server. Pillow 11.3.0 loads a variable font like any TrueType file. You pick the weight afterwards by its named instance: python def font lang, size, weight="Bold" : f = ImageFont.truetype str FONTS / FONT FILE.get lang, FONT FILE "en" , size try: f.set variation by name weight except Exception: pass return f The try/except is deliberate. set variation by name raises if the font has no instance with that name, or if the FreeType library Pillow uses lacks variation support. In both cases we would rather draw the default weight than fail the whole build over a card. One font per language is the simplest way to avoid tofu empty boxes . Noto Sans JP covers kana and the kanji used in Japanese, Noto Sans KR covers Hangul, and both include Latin, so "iOS" or "AI" inside a Japanese title renders without fallback logic. The brand and domain always use the Latin font. Titles range from four words to a long Korean sentence. Instead of measuring and computing a size, the code just tries a fixed list from large to small and takes the first one that fits in four lines: max w = W - pad 2 1200 - 160 for size in 68, 62, 56, 50, 46, 42 : tf = font lang, size, "Bold" lines = wrap d, title, tf, max w, lang if len lines <= 4: break lines = lines :4 line h = int size 1.32 The line height of 1.32× the font size is enough room for Japanese and Korean glyphs, which sit taller in the em box than Latin capitals. The block is then centered vertically, but never higher than y = 140, so it cannot collide with the category label. If even 42 px needs a fifth line, lines :4 silently drops the rest. That has not happened with our titles, but it is the first thing to check if you reuse this with longer ones. For English, and for Korean titles that contain spaces, wrapping is plain word wrap measured with draw.textlength . Korean breaks at spaces between words, just like English, so the same loop works. Japanese has no spaces, and that is where things went wrong. fig:ogcard-wrap-fixes Version 1: one character at a time. The first version treated Japanese as a stream of characters and broke wherever the next one did not fit. The test card for a post on share links came out as: iOSとAndroidで共通の共有リン ク:流入元ごと… The katakana word リンク link was cut in half. A Japanese reader notices that instantly. Version 2: a regex tokenizer. We split the title into tokens that must not be broken: Latin words including things like C or Node.js , runs of katakana, and otherwise single characters. We also force a break after a full-width colon, because our titles often use 「:」 between topic and detail: tokens = re.findall r" A-Za-z0-9 A-Za-z0-9.+ /'’- | ァ-ヶー・ +|\s+|.", text … if tok in ":", ":", "—" and cur.strip : lines.append cur.rstrip cur = "" That fixed リンク. The next post's card then read: AIコーディングエージェントに本 番サーバー… 本番 production is a two-kanji compound, and the tokenizer had no idea. Kanji compounds are not marked in the text in any way. Version 3: break after a particle. Japanese grammar helps here. Particles such as に, を, の, で, が, は, と, へ, も, や, and commas, end a phrase a bunsetsu . Breaking right after one is almost always natural. So when a line overflows, the code looks back for the last particle or comma and breaks there, as long as that point is at least halfway through the line: if cur and draw.textlength cur + tok, font=font max w: cut = max i + 1 for i, c in enumerate cur if c in "にをのでがはとへもや、," , default=0 if cut = len cur 0.5 and cut < len cur : lines.append cur :cut .rstrip cur = cur cut: .lstrip + tok else: lines.append cur.rstrip cur = tok.lstrip The 50% rule stops a particle near the start of the line from producing a very short line followed by a very long one. The same title now reads: AIコーディングエージェントに 本番サーバーを触らせる: 効いたガードレール Finally, kinsoku. Japanese typesetting has rules kinsoku shori about characters that must not start a line: commas and periods, closing brackets, the long-vowel mark ー, and small kana such as ッ or ょ. After wrapping, any such character at the start of a line is pulled back to the end of the previous one: for i in range 1, len lines : while lines i and lines i 0 in "、。,.)」』ーっゃゅょァィゥェォッャュョ": lines i - 1 += lines i 0 lines i = lines i 1: Two honest caveats. First, this is a heuristic, not morphological analysis. A particle character can also sit inside a word は in はじめて, or の in a name written in hiragana , so a break can still land mid-word, and a title with no particles falls back to breaking between tokens. Google's BudouX or a morphological analyzer such as MeCab would segment phrases properly and is the more robust choice. We did not use one because it would add a dependency to a build whose dependencies are Pillow, Jinja2, Markdown, PyYAML and python-dotenv, and because our titles are short, hand-written, and checked visually. Second, the kinsoku step does not re-measure the line it appends to. It relies on the 80 px right padding to absorb one extra character. Drawing 130-odd PNGs with large CJK fonts on every build would be wasteful, since titles rarely change. Each card is keyed by an md5 of everything that affects its pixels: VERSION = "3" bump when the design changes → every card is redrawn key = hashlib.md5 "|".join VERSION, title, label, lang, category, brand .encode .hexdigest cached = CACHE / f"{key}.png" .cache/og/