Skip to main content
Recipe number 76

Cookbook · Chapter 2 · Type & text

A pinyin primer: readings over every character

Mono ruby in a Hong Kong first reader: {人之初|rén zhī chū} centres one pinyin syllable over each character, in Andika, inside a 28 pt line gap.

On this page

pp. 36–37 · 1–2 of 4

  • Trim 184 × 260 mm
  • 1 column
  • LXGW WenKai TC 26/54
  • Andika
  • Noto Sans TC
  • 4 pages
  • Level
  • Postext 1.57.1
  • Laid out in 73 ms
  • 180 lines of code

In short

Pages from a first reader for children in Hong Kong. It shows how to print the pronunciation in Latin letters above every Chinese character, with squares for practising writing.

What you'll build

Two spreads of 《蒙學誦讀》, an invented first reader from Hong Kong, where children read the Three Character Classic aloud in Putonghua. Each page is a lesson of four couplets in 一号 Kai (26 pt), every character under its pinyin syllable. The syllables are set in Andika because it draws the one-storey a and g that Chinese schoolbooks print. A pale band carries a red lesson badge, a small watercolour, and the title at 初号 (42 pt) with its own readings. Under the text, six writing squares (田字格) hold the characters to copy, and a note tells the family what the lines mean. The Spanish counterpart is the primer with syllable chips, where each syllable is a coloured chip instead of a reading over a character.

A primer leaves the rules of a Chinese book on purpose. A child reads a few large characters at a time, so a line holds twelve at 26 pt, where a book sets 25 to 40 at 10.5 pt, and the leading is a little over twice the size to hold the readings. Each couplet stands centred on a line of its own, neither justified nor indented. The text is in Kai, the face that follows the brush, because it shows the strokes a child learns to write; a book would set it in Song.

This recipe answers

  • How do I add pinyin above Chinese characters?

The short answer

script.js · lines 36–56in full code
// {人之初|rén zhī chū} gives each character its own syllable (mono ruby): three readings for
// three characters, split on the spaces. The reading sits in the line gap, centred on its
// character; a syllable wider than the character widens that character's box by what the
// reading needs, less the quarter of the reading's size it may lend a neighbour.
const cjk = {
  // The type area in characters: 12 per line, 11 lines of 54 pt. The margins grow to centre it.
  grid: { enabled: true, charsPerLine: CHARS, linesPerPage: 11 },
  ruby: {
    fontFamily: PINYIN, // one-storey a and g, as a Chinese primer prints them
    // 9.9 pt over the text, 16 pt over the title: the widest syllables (xiāng, zhuān) still fit
    // over one character, so every couplet is 8 em long and keeps to the grid.
    fontSize: em(0.38),
    color: col('pinyin'),
  },
};
// The line pitch never changes for a reading: the gap between lines (54 − 26 = 28 pt) must
// hold it, or the build warns rubyExceedsLeading.
const text = {
  fontFamily: KAI, fontSize: pt(TEXT), lineHeight: pt(LINE),
  textAlign: 'center', firstLineIndent: pt(0), // one couplet to a line, centred
};

One reading per character, in Andika, in a line gap wide enough to hold it

Ingredients

Type
LXGW WenKai TC, Noto Sans TC, Andika (SIL OFL 1.1)
Assets
  • brush-800.jpg
  • jade-800.jpg
  • shuttle-800.jpg
  • sprout-800.jpg
  • The writing squares, drawn in code in the page’s palette (Postext Cookbook, CC BY 4.0)
  • Lesson 1’s vignette: a seedling, a watercolour (Generated With Diffusion Models, original)
  • Lesson 2’s vignette: the shuttle of a loom, a watercolour (Generated With Diffusion Models, original)
  • Lesson 3’s vignette: a brush and its first stroke, a watercolour (Generated With Diffusion Models, original)
  • Lesson 4’s vignette: a jade disc on a red cord, a watercolour (Generated With Diffusion Models, original)

Method

#1 · A syllable over each character

The code is the short answer above. {人之初|rén zhī chū} gives three characters three readings, split on the spaces: each syllable is centred over its own character, and a line may break between them. A reading takes no room of its own. It sits in the line gap, 54 − 26 = 28 pt here, and a gap narrower than the reading is reported as rubyExceedsLeading. A syllable wider than its character does take room: it widens that character's box, and in a centred line the characters that follow move off the grid. The readings are set at the size where the widest syllables here, xiāng and zhuān, still fit over one character, 0.38 em (9.9 pt): every couplet is eight characters long and each character keeps its square. At 0.45 em, 性相近,習相遠 would stretch to eight and a half characters and open gaps around 相.

#2 · The title keeps its readings

script.js · lines 60–77in full code
const BAND = 68; // mm from the top edge
// Heading designs ignore parity: a place for the drawing on each side, 14 mm from the outer
// edge, named {left="…"} on a verso and {right="…"} on a recto. A missing attribute draws nothing.
const picture = (side, x) => ({ kind: 'image', id: `picture-${side}`,
  resourceId: `{attr.${side}}`, decorative: true, reserve: false,
  placement: { anchor: { to: 'page', edge: `top-${side}` }, offset: { x: mm(x), y: mm(14) },
    size: { width: mm(42), height: mm(42) } } });
const opener = { enabled: true, slot: { elements: [
  { kind: 'box', id: 'band', reserve: false, style: { backgroundColor: col('tint') },
    placement: { anchor: { to: 'page', edge: 'top-left' },
      size: { width: mm(184), height: mm(BAND) } } },
  picture('left', 14), picture('right', -14),
  { kind: 'text', id: 'lesson', content: '{titleText}', fontFamily: HEI, fontSize: pt(11),
    fontWeight: 700, letterSpacing: pt(2), color: col('paper'), align: 'center', overflow: 'wrap',
    placement: { anchor: { to: 'container', edge: 'top' } },
    box: { backgroundColor: col('red'), borderRadius: mm(3.5),
      padding: { top: mm(1.2), right: mm(3.6), bottom: mm(1.2), left: mm(3.6) } } },
] } };

Design text prints no readings, so the title cannot come from the opener's design. The level-1 heading, 第一課, draws the band, the picture and the red badge; the title is the level-2 heading under it, a plain heading at 初号 that the text composer sets with its pinyin. reserve: false leaves the band and the picture out of the heading's height, and span: 'page' paints them under the text.

A heading design ignores parity, so the picture has an element on each side of the page: {attr.left} 14 mm from the left edge and {attr.right} 14 mm from the right. The lessons on versos write # 第一課 {left="sprout"} and the ones on rectos {right="shuttle"}, so every picture sits on the outer side of the spread; the element whose attribute is missing draws nothing.

#3 · Six squares from one attribute

script.js · lines 81–101in full code
// Design text prints no readings, so the squares hold the characters alone. A Han character
// is one em wide, so tracking of (pitch − em) sets one in the middle of each square.
const [SQ, GAP, WRITE] = [15, 3.4, 30]; // mm, mm, pt
const ROW = 6 * SQ + 5 * GAP; // mm
const X0 = (MEASURE - ROW) / 2; // the row is centred on the measure
const EM = WRITE * 25.4 / 72; // mm: one character at 30 pt, 10.6 mm wide
const squares = { enabled: true, slot: { elements: [
  { kind: 'text', id: 'label', content: '{titleText}', fontFamily: HEI, fontSize: pt(10),
    fontWeight: 700, letterSpacing: pt(1.5), color: col('red'), align: 'left', overflow: 'wrap',
    placement: { anchor: { to: 'container', edge: 'top-left' }, offset: { x: mm(X0) } } },
  ...Array.from({ length: 6 }, (_, k) => ({ kind: 'image', id: `square${k}`, resourceId: 'tian',
    decorative: true, placement: { anchor: { to: 'container', edge: 'top-left' },
      offset: { x: mm(X0 + k * (SQ + GAP)), y: mm(7) },
      size: { width: mm(SQ), height: mm(SQ) } } })),
  { kind: 'text', id: 'chars', content: '{attr.write}', fontFamily: KAI, fontSize: pt(WRITE),
    lineHeight: 1, letterSpacing: mm(SQ + GAP - EM), color: col('ink'), align: 'left',
    verticalAlign: 'middle', overflow: 'clip',
    placement: { anchor: { to: 'container', edge: 'top-left' },
      offset: { x: mm(X0 + (SQ - EM) / 2), y: mm(7) },
      size: { width: mm(ROW + GAP), height: mm(SQ) } } },
] } };

### 我會寫 {write="人之本不相以"} gives the design the six characters in one attribute. Every Han character of LXGW WenKai TC is one em wide, so a tracking of the squares' pitch less one em (18.4 − 10.6 mm) steps the characters from square to square, and one text element fills the row. The square is an SVG drawn in code: a red frame and a dashed cross.

#4 · Each face loads its own characters

script.js · lines 282–289in full code
// Fontsource cuts a Chinese face into about a hundred files by character range
// (gotcha: cjk-fonts-slices). The Kai sets the whole sample; the Hei only the headings'
// labels and the footer's series line, so it fetches a few files.
const labels = (markdown.match(/^#{1,3} [^{\n]*/gm) ?? []).join('') + '蒙學誦讀 第一冊';
await loadFonts(FONTS, markdown); // the latin files, and Andika's latin-ext for ǎ ǐ ǒ ǔ
await Promise.all([loadCjkFonts({ [KAI]: FONTS[KAI] }, markdown),
  loadCjkFonts({ [HEI]: FONTS[HEI] }, labels),
  loadSvg('tian.svg', tian), ...VIGNETTES.map((fileId) => loadImage(fileId, asset(fileId)))]);

Fontsource cuts each Chinese face into about a hundred files by character range. The Kai face sets the whole sample and loads the files that hold its characters. The Hei face sets only the badges, the labels and the footer, so it gets that text and fetches a few files. Andika comes from loadFonts, which adds the latin-ext file when the text has letters past Latin-1, as ǎ and ǐ are.

#5 · Hong Kong punctuation from the locale

script.js · lines 121–123in full code
  // Punctuation at full width, where LXGW WenKai TC centres it as Hong Kong and Taiwan print
  // it, and the basic line-breaking rules. Written out, never LANG (gotcha: cjk-locale-tag).
  locale: 'zh-HK',

zh-HK sets Hong Kong's rules: punctuation at full width and the basic line-breaking rules, which no couplet here needs. LXGW WenKai TC draws its commas and full stops in the middle of the square, as Hong Kong and Taiwan print them, and that is why this primer comes from Hong Kong. A mainland first reader is set in Kai as well, in simplified characters with the comma and the full stop in the lower left of the square. Fontsource has no Kai text face for simplified Chinese, though, and the Traditional one would crowd those marks against the next character, so a mainland page in this Cookbook takes Noto Serif SC, the Song face of the mainland novel page.

The whole recipe

Sandbox
// ═══ Postext Cookbook · Nº 076 · A pinyin primer: readings over every character ═══
// https://postext.dev/en/cookbook/pinyin-primer
// Code: MIT · Text: 三字經 (PD); pinyin, notes: CC BY 4.0 · Vignettes: diffusion models
// Fonts: LXGW WenKai TC, Noto Sans TC, Andika (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import {
  buildDocument, withLoadedFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'pinyin-primer';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: a primer's colours, every one linked by id
const palette = {
  ink: '#29241f', // the characters: a warm near-black
  pinyin: '#355a4d', // the readings, a shade off the ink so the two layers part
  red: '#bf3a2b', // lesson badges and the writing squares
  jade: '#2f7a5e', // the folio discs
  tint: '#edf4ea', // the band behind each lesson's title
  cream: '#faf3e4', // the note for families
  muted: '#6d665e', // series line, colophon
  paper: '#ffffff',
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
// The engine's defaults link to 'main-color': point it at the red.
const colorPalette = Object.entries({ ...palette, 'main-color': palette.red })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
// #endregion
const [KAI, HEI, PINYIN] = ['LXGW WenKai TC', 'Noto Sans TC', 'Andika'];
const TEXT = 26; // pt: 一号, the size of a first reader's text
const LINE = 54; // pt: 2.1 × the size, so a reading fits between two lines
const CHARS = 12; // characters per line: the measure is 12 × 26 pt = 110 mm
const MEASURE = CHARS * TEXT * 25.4 / 72; // mm

// #region answer: one reading per character, in Andika, in a line gap wide enough to hold it
// {人之初|rén zhī chū} gives each character its own syllable (mono ruby): three readings for
// three characters, split on the spaces. The reading sits in the line gap, centred on its
// character; a syllable wider than the character widens that character's box by what the
// reading needs, less the quarter of the reading's size it may lend a neighbour.
const cjk = {
  // The type area in characters: 12 per line, 11 lines of 54 pt. The margins grow to centre it.
  grid: { enabled: true, charsPerLine: CHARS, linesPerPage: 11 },
  ruby: {
    fontFamily: PINYIN, // one-storey a and g, as a Chinese primer prints them
    // 9.9 pt over the text, 16 pt over the title: the widest syllables (xiāng, zhuān) still fit
    // over one character, so every couplet is 8 em long and keeps to the grid.
    fontSize: em(0.38),
    color: col('pinyin'),

The composed script.js runs as it is: paste it into any page’s module script, or open the recipe on CodePen. Recipe folder on GitHub ↗ (opens in a new tab)

Variations

#Show the grid while you set the page

show: true draws the twelve squares of every line on the canvas; the PDF leaves them out unless renderToPdf is given characterGrid: true.

-  grid: { enabled: true, charsPerLine: CHARS, linesPerPage: 11 },
+  grid: { enabled: true, charsPerLine: CHARS, linesPerPage: 11, show: true },

#Put zhuyin beside the characters

Bopomofo readings stand in a column right of each character; the zhuyin reader sets them down a vertical page.

Pitfalls

Pitfall

Readings print in the text, not in designs, captions or cells

Ruby readings are drawn in paragraphs, headings, list items, quotations and boxes. A design text element (an opener, a running head, a badge), a caption, a footnote and a table cell print the base characters without their readings. A title that needs its pinyin is a heading without a design of its own: draw what surrounds it (a band, a lesson number) with the design of the heading before it, whose elements with reserve: false paint under the text of a span: 'page' opener. Ruby: pinyin and zhuyin readings →

Pitfall

Set each region's punctuation in a face of that region

The punctuation widths move the blank beside each mark to the side the document's region puts it, not the side the font draws it: under zh-Hans a Kaiming comma keeps the left half of its box, where a Simplified face draws the glyph, and gives up the right half. A Traditional face centres ,。 in the box, so the half that goes holds part of the glyph and the comma crowds the next character. LXGW WenKai TC, the only Kai text face on Fontsource, does this in Simplified text. Set mainland text, notes and quotations in Noto Serif SC or Noto Sans SC, keep the TC faces for zh-Hant, and use a Simplified brush face (Ma Shan Zheng) only for display lines, where design text applies no punctuation widths. It also draws inherited forms that neither the mainland nor the Taiwan standard prints, 為 with the 爫 top of 爲 and 令 (in 冷, 領) with a 卩 foot: check the characters a page sets in it. Chinese punctuation widths →

Pitfall

Chinese faces load by slices, through the cjk block

Fontsource serves a Chinese, Japanese or Korean family as about a hundred files per weight, each covering a range of characters. loadFonts fetches only the latin file, so on screen the Han characters come from a system face and measure wrong, and fontsourceProvider hands the PDF that latin file, which prints them as empty boxes. List the cjk kit block, call loadCjkFonts(FONTS, markdown) after loadFonts (once per voice, with the text it sets, when the book uses several CJK faces) and give renderToPdf fontProvider: cjkPdfProvider: both take the files that hold the text's characters. Chinese, Japanese and Korean fonts →

Pitfall

Tag the document zh-Hans or zh-Hant, not with LANG

A recipe's editions are en and es, but a Chinese sample is Chinese in both: `locale: LANG` would tag it English or Spanish, hyphenate its Latin words, label its figures Figure or Figura and give the PDF the wrong language. From postext 1.30 the tag is also the language the text is shaped in (measured, painted and embedded), so under an English or Spanish tag a Chinese face sets its digits and the punctuation it shares with Latin text in other forms, and the lines break elsewhere. Write the tag yourself: 'zh-Hans' (mainland conventions: GB line breaking, Kaiming punctuation) or 'zh-Hant' (Taiwan: full-width centred punctuation); 'zh-HK' for Hong Kong. A bare 'zh' reads as Simplified, mainland. A Japanese sample takes 'ja' (gotcha ja-locale-tag). Chinese line breaking →

Layout warning · rubyExceedsLeading

Readings crowd the next line

Why. A paragraph with ruby readings over or under its text has a line gap narrower than the readings: they sit in the leading and touch the line next to them.

Fix. Set the paragraph with more leading (at least the text size plus `cjk.ruby.fontSize`), or make the readings smaller. Docs →

  • This recipe offers no PDF. The kit's fontsourceProvider embeds a face's latin file only, and the tone letters ā ǎ ǐ ǒ ǔ are in latin-ext, so a PDF would lose them and postext-pdf would report each as missingGlyph. If you need one, set the readings in a Chinese face, whose files cjkPdfProvider picks character by character.

  • Check each character of the squares against the region's standard forms. LXGW WenKai TC draws 為 with the 爫 top of 爲, an older form that passes in running text, as in 老何為 and 為人子 here, but not in a square a Hong Kong child copies. Lesson three practises 幼 instead.

Credits

Text
Images
  • The writing squares, drawn in code in the page’s palette · Postext Cookbook · CC BY 4.0
  • Lesson 1’s vignette: a seedling, a watercolour · Generated With Diffusion Models · original
  • Lesson 2’s vignette: the shuttle of a loom, a watercolour · Generated With Diffusion Models · original
  • Lesson 3’s vignette: a brush and its first stroke, a watercolour · Generated With Diffusion Models · original
  • Lesson 4’s vignette: a jade disc on a red cord, a watercolour · Generated With Diffusion Models · original
Fonts
LXGW WenKai TC (SIL OFL 1.1) · Noto Sans TC (SIL OFL 1.1) · Andika (SIL OFL 1.1)
Sandbox