本文へスキップ
レシピ番号26

レシピ集 · 第10章 · 出力と組み込み

組版前にすべてのフォントを読み込む書体見本

4ページの書体見本。証拠としてわざと早すぎる組版を1回行い、続いて設定と本文が求める書体をすべて読み込んでから組みます。

このページの内容

1ページ(全4ページ)

  • 英語の見本:日本語版はまだありません
  • 仕上がり180 × 240 mm
  • 1段
  • Ysabeau Office 11/15.5
  • IBM Plex Mono
  • Noto Serif Display
  • 4ページ
  • レベル
  • Postext 1.57.1
  • 組版時間4 ms
  • コード188行

かんたんな説明

3つの書体を見せる4ページの小冊子。ページを組む前にすべてのフォントを読み込み終えておかないと、行が間違った位置で改行される理由を示します。

できあがり

架空の出版社Pellow Lane Pressの『House Specimen Nº 3』は、3つの書体を見せる4ページの書体見本です。表紙では、群青色の地に240 ptのNoto Serif Displayイタリックで白い「Ag」を置き、3つの書体の名前を記した等幅の2行を添えます。題はその地の下に組みます。2ページ目はYsabeau Officeを7 ptから14 ptまでのウォーターフォールで見せ、続いてスペイン語、ポーランド語、チェコ語のパングラムを組みます。そこに含まれるż、ř、ůには2つ目のフォントファイルが要ります。3ページ目は検査表で、小冊子が宣言する10の書体、ページが実際に組まれている6つの書体、それぞれにブラウザーが取得したファイルを、サンプルが書き込むIBM Plex Monoの表に並べます。4ページ目には1ページ目の最初の段落を、早すぎた組版の結果と最後の組版の結果で2回組みます。早すぎた組版はブラウザーにフォントファイルが1つもないうちに走ったので、行末の位置が異なり、いくつかの行は行長からはみ出します。

このレシピが答える質問

  • 行の分割が変わったりPDFで単語が重なったりするのはなぜですか?フォントを正しく読み込むには?
  • 自社ブランドのフォントやライセンスを受けたフォントでレイアウトし、PDFに埋め込むには?
  • 文書のどこに問題があるか(警告、はみ出し、収束しないレイアウト)を調べるには?

手短な答え

script.js · 314〜331行コード全体で見る
// buildDocumentWithFonts starts with prepareFonts: it reads the config and the text for every
// face they ask for (text, headings, chips, table, captions, opener, running heads), in each
// weight and slant, and loads them for the characters the document sets. The page declares its
// files (declareFaces), so they load through document.fonts; a face nothing declares would be
// asked of a resolve(family, weight, style) option. Then it builds, reads the faces the pages
// are set in, loads any that the config did not name and builds again.
let report; // { loaded, missing, synthesized }: lists of { family, weight, style }
const build = () => buildDocumentWithFonts(content(), config(),
  { onFonts: (found) => { report = found; } }); // what the last look at the pages found

kitStatus('Loading fonts…'); // the kit's bar: it also reports any error thrown below
const early = buildDocument(content(), config()); // on purpose: the page has no font yet (page 4)
declareFaces(FONTS);
const fitted = await build(); // every face loaded before a line is measured
audit = auditOf(fitted, report); // page 3's table
drawProof(early, fitted); // page 4's picture
const doc = await build(); // nothing left to load: the same pages, table and picture filled in
showPages(doc, { title: 'Load every font before layout' });

材料

種類
Ysabeau Office, Noto Serif Display, IBM Plex Mono (SIL OFL 1.1)
素材
なし:画像はすべてコードで描画

作り方

#1 · ファイルを取得せずにすべて宣言する

script.js · 268〜287行コード全体で見る
const SUBSETS = { // the characters each file covers, copied from the family's @font-face CSS
  latin: 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,'
    + 'U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD',
  'latin-ext': 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,'
    + 'U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,'
    + 'U+A720-A7FF' };
const FILES = new Map(); // FontFace → the subset its file covers, for the audit
function declareFaces(fonts) { // Fontsource's static files stand in for your own /fonts/ folder
  for (const { family, weight, style } of facesOf(fonts)) {
    const id = family.toLowerCase().replaceAll(' ', '-');
    for (const [subset, unicodeRange] of Object.entries(SUBSETS)) {
      const file = `${id}@5/files/${id}-${subset}-${weight}-${style}.woff2`;
      // Adding a face fetches nothing: the file downloads when a load or a line needs it.
      const face = new FontFace(family, `url(https://cdn.jsdelivr.net/npm/@fontsource/${file})`,
        { weight: `${weight}`, style, unicodeRange });
      FILES.set(face, subset);
      document.fonts.add(face);
    }
  }
}

FontFaceは、@font-face規則と同じく1つのファイルを表します。latinとlatin-extの2ファイルからなる書体なら、ファミリー、ウェイト、スタイルが同じでunicodeRangeだけが違う2つのFontFaceオブジェクトで宣言します。範囲の値はファミリーのCSSから写します。document.fontsに加えただけでは何もダウンロードされません。ブラウザーがファイルを取りに行くのは、load()が呼ばれたときか、その文字を必要とするテキストの行が現れたときです。Postextは、ページが宣言した書体をdocument.fontsを通して読み込みます。どこにも宣言のない書体はresolveオプションに求めます。ほかのレシピがキットからFontsourceのファイルを受け取るのはこの方法です。設定のcustomFontsは.postextバンドル内のファイルを記述するだけなので、Markdownから組むページは自分でフォントを宣言するか、resolveを渡します。

#2 · 書体を読み込んでから組む

コードは上の手短な答えにあります。buildDocumentWithFontsはまずprepareFontsを実行します。これは設定と本文が求める書体をウェイトとスタイルごとにすべて読み取り、文書自身の文字をサンプル文字列にして読み込むので、latin-extのファイルはポーランド語とチェコ語のパングラムと一緒に届きます(レイアウトの前にフォントを読み込む)。続いて組版し、ページが実際に組まれた書体を読み取り、設定に名前のなかったものを読み込んで組み直します。onFontsはこの最後の確認の報告を受け取ります。読み込まれた書体(loaded)、欠けている書体(missing)、ブラウザーが別のウェイトやスタイルから擬似的に作るはずだった書体(synthesized)です。サンプルが3回組むのは、小冊子が自分の証拠を印刷するからです。わざと早すぎる1回、書体がそろった1回、表と図を書き込んだ最後の1回です。

#3 · 検査表を報告から作る

script.js · 291〜309行コード全体で見る
const SET = { loaded: 'yes', synthesized: 'faked', missing: 'in a fallback' }; // the report
const nameOf = (f) => `${f.family.replaceAll('"', '')} ${f.weight} ${f.style}`; // or a FontFace
function auditOf(doc, report) {
  const found = Object.keys(SET).flatMap((kind) => report[kind].map((f) => [nameOf(f), kind]));
  const inPages = new Map(found);
  const loaded = [...FILES].filter(([face]) => face.status === 'loaded');
  const faces = new Map([...facesOf(FONTS), ...Object.keys(SET).flatMap((kind) => report[kind])]
    .map((f) => [nameOf(f), f])); // the declared faces, then any the pages set without a file
  const rows = [...faces].map(([name, f], i, all) => [
    i && all[i - 1][1].family === f.family ? '' : f.family, // each family named once
    `${f.weight}${f.style === 'italic' ? ' italic' : ''}`, SET[inPages.get(name)] ?? 'no',
    loaded.filter(([face]) => nameOf(face) === name).map(([, subset]) => subset).join(' · ')
      || 'none'].map((cell) => ({ content: cell })));
  // What else to read in a finished layout: its content warnings, its passes, its warnings.
  return { rows, note: `${report.loaded.length} of ${rows.length} faces set in the pages · `
    + `${loaded.length} of ${FILES.size} files fetched · fontFallback warnings: `
    + `${fallbacksIn(doc) || 'none'} · ${doc.converged ? '' : 'not '}converged · layout warnings: `
    + `${doc.warnings?.length || 'none'}` };
}

表はFONTSが宣言する書体から始め、報告が各書体について述べることを加えます。ページがその書体で何かを組んでいるか、ブラウザーが擬似的に作ったか、代替書体で組まれたかです。最後の列には、FontFaceがloadedになったファイルを並べます。取得されたのは20ファイルのうち16です。Postextは本文ファミリーの4つの書体をすべて読み込みます。どの段落でも**と*でそれらを求められるからです。等幅書体の2つのイタリックはどの設定にも名前がないので、最後までダウンロードされませんでした。注記は、組み上がった文書からさらに3つを読みます。代替書体で計測した書体がfontFallbackとして並ぶcontentWarnings、レイアウトのパスが収束するとtrueになるconverged、そしてwarningsです。ページを表示したり書き出したりする前に、3つとも確かめてください。

#4 · 早すぎた組版を証拠として残す

script.js · 126〜174行コード全体で見る
const STRIP = { lines: 8, overrun: 10 }; // page 1's first paragraph; mm shown past the measure
const PROOF = { // px: two strips a lead apart, cut at 300 dpi
  width: Math.round(((MEASURE + STRIP.overrun) / 25.4) * 2 * DPI),
  height: Math.round((((2 * STRIP.lines + 1) * LEAD) / 72) * 2 * DPI) };
const proof = { moved: 0, total: 0, faces: 0 }; // lines the early build broke elsewhere, of all
const fallbacksIn = (doc) => // a build lists each face its font set could not give
  (doc.contentWarnings ?? []).filter((w) => w.kind === 'fontFallback').length;
const proofFigure = () => ({ id: 'proof', typeId: 'figure', kind: 'bitmap', createdAt: 0,
  updatedAt: 0, placement: here,
  bitmap: { fileId: 'proof.png', format: 'png', width: PROOF.width, height: PROOF.height },
  caption: 'The first paragraph of page 1 as the early build set it, measured before the fonts '
    + 'had arrived (above), and as the last build set it (below). The early build broke '
    + `${proof.moved} of its ${proof.total} lines of text elsewhere, and its own warnings name `
    + `${proof.faces} faces set in a fallback. The rule marks the measure.`,
  altText: `Two strips of the same ${STRIP.lines} lines of text. In the upper strip the lines `
    + 'break in other places and some run past a vertical rule; in the lower one every line '
    + 'stops short of it.' });
function drawProof(first, last) {
  const linesOf = (doc) => doc.blocks.filter((b) => b.type === 'paragraph')
    .map((b) => b.lines.map((l) => l.text));
  const [before, after] = [first, last].map(linesOf);
  proof.total = before.flat().length;
  proof.faces = fallbacksIn(first);
  proof.moved = before.flatMap((lines, i) => lines.filter((t, j) => t !== after[i]?.[j])).length;
  const canvas = Object.assign(document.createElement('canvas'), PROOF);
  const ctx = canvas.getContext('2d');
  const strip = (PROOF.height * STRIP.lines) / (2 * STRIP.lines + 1);
  const edge = Math.round((PROOF.width * MEASURE) / (MEASURE + STRIP.overrun));
  // The renderer clips each column 2 pt past its edge, which would cut the early build's lines
  // at the measure: paint a copy of page 1 whose column reaches across the whole strip.
  const wide = (column) => ({ ...column,
    bbox: { ...column.bbox, width: column.bbox.width + (STRIP.overrun / 25.4) * DPI } });
  [first, last].forEach((doc, i) => {
    const page = document.createElement('canvas');
    renderPageToCanvas({ ...doc.pages[0], columns: doc.pages[0].columns.map(wide) }, doc, page,
      { scale: 2 }); // 300 dpi
    const { x, y } = doc.pages[0].columns[0].blocks.find((b) => b.type === 'paragraph').bbox;
    ctx.drawImage(page, 2 * x, 2 * y, PROOF.width, strip,
      0, i * (PROOF.height - strip), PROOF.width, strip);
  });
  ctx.fillStyle = `${palette.ultramarine}1f`; // a pale wash over the margin past the measure
  ctx.fillRect(edge, 0, PROOF.width - edge, PROOF.height);
  ctx.fillStyle = palette.ultramarine; // a hairline at the measure, and each strip's name
  ctx.fillRect(edge, 0, 2, PROOF.height);
  ctx.font = `700 ${(7 / 72) * 2 * DPI}px "IBM Plex Mono"`; // 7 pt, loaded by now
  ['early', 'last'].forEach((name, i) => // on the last line of each strip
    ctx.fillText(name, edge + 12, (i ? PROOF.height : strip) - 16));
  registerResourceImage('proof.png', canvas);
}

サンプルは書体を1つも宣言しないうちにbuildDocumentを1回呼ぶので、その組版はすべての語をブラウザーの代替書体で計測します。本物の書体がそろった後でそれを描き直し、最後の組版と1行ずつ比べます。キャプションの行数はこの比較から、書体の数は早すぎた組版自身のfontFallback警告から出ています。幅の狭い代替書体で計測した普通の行は行長を越え、段の端から2 pt外にあるクリップで最後の文字が切り取られます。そこでサンプルは、はみ出し全体が見えるように段を広げて1ページ目を描きます。Canvasとpostext-pdfは、両端そろえの行や複数のスタイルが混じる行の各ランを、レイアウトが計測した位置に描きます。そのため代替書体より幅の広い本物の書体は次の単語に重なって印刷され、フォントが届く前に生成したPDFでは単語どうしが重なります。早すぎた組版の結果は次の組版に持ち越されません。prepareFontsがdocument.fontsに新しい書体を見つけ、そのファミリーで計測した幅を捨てるので、clearMeasurementCache()を呼ぶ必要はありません。

#5 · 本文のリズムに乗るウォーターフォール

script.js · 30〜44行コード全体で見る
const bodyText = () => ({
  fontFamily: TEXT, fontSize: pt(11), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  textAlign: 'left', firstLineIndent: pt(0), paragraphSpacing: true }); // ragged and spaced
// Every waterfall size and pangram is two leads (31 pt) deep, on the text's 15.5 pt rhythm.
const line = (size) => ({ fontSize: pt(size), lineHeight: pt(2 * LEAD) });
const paragraphStyles = () => [
  ...[7, 8, 9, 10, 11, 12, 14].map((size) => ({ id: `s${size}`, ...line(size) })),
  { id: 'pangram', ...line(13) },
  { id: 'colophon', fontSize: pt(7), lineHeight: pt(10), fontFamily: MONO, color: col('muted') }];
// Size labels: boxless mono chips. A Plex Mono letter is 0.6 em wide, so a one-digit label gets
// half a letter each side and the samples start on one edge.
const tag = { fontFamily: MONO, fontSize: pt(7), color: col('ultramarine'),
  backgroundEnabled: false, borderWidth: pt(0), paddingX: pt(0), gap: mm(2.5) };
const chipStyles = () => [{ id: 'size', ...tag }, { id: 'size-1', ...tag, paddingX: em(0.3) }];

本文はYsabeau Officeの11 pt、行送り15.5 ptで組み、段落の間は字下げでなく1行空けます。本文は左そろえ(行末不ぞろい)なので、どの語間も自然な幅を保ちます。太字、イタリック、参照はインキ色で組みます。指定しなければメインカラーになるところです。ウォーターフォールの各サイズとパングラムは、どれも行送り2つ分(31 pt)の高さの段落スタイルなので、ページは本文の15.5 ptのリズムを保ちます。サイズのラベルは等幅のチップです。1桁のサイズには左右に半文字分の内側余白を付けるので、どの見本も同じ端から始まります。

#6 · 1枚の表紙に3つの書体

script.js · 48〜74行コード全体で見る
const Y = { kicker: 14, glyphs: 17, label: FIELD - 12, title: FIELD + 10, // mm from the top edge
  end: FIELD + 42 }; // where the opener ends: under the title, the lead and a line of air
const ITALIC_FOOT = 5; // mm: the italic A's foot reaches this far left of the glyphs' origin
const at = (x, y, width) => ({ anchor: { to: 'page', edge: 'top-left' },
  offset: { x: mm(x), y: mm(y) }, ...(width && { size: { width: mm(width) } }) });
const text = (id, content, style, placement) => ({ kind: 'text', id, content, align: 'left',
  overflow: 'wrap', ...style, placement }); // a running head wraps too, never '…'
const cover = () => ({ level: 1, fontSize: pt(30), italic: true, // headings.levels[0]
  breakBefore: { enabled: true, parity: 'odd' }, // the cover is a recto
  span: 'page', // the heading is set across the page; its field hangs from the bleed
  advancedDesign: { enabled: true, minHeight: mm(Y.end - MARGIN.top), // from the top margin
    slot: { elements: [
      { kind: 'box', id: 'field', style: { backgroundColor: col('ultramarine') }, placement: {
        anchor: { to: 'bleed', edge: 'top-left' }, size: { width: 'fill', height: mm(FIELD) } } },
      text('kicker', '{attr.kicker}', { ...label, fontWeight: 700, color: col('paper') },
        at(MARGIN.inner, Y.kicker)),
      text('glyphs', '{attr.glyphs}', { ...display, fontSize: pt(240), lineHeight: 1,
        color: col('paper') }, at(MARGIN.inner + ITALIC_FOOT, Y.glyphs)),
      text('label', '{attr.label}', { ...label, color: col('mist') }, at(MARGIN.inner, Y.label)),
      text('faces', '{attr.faces}', { ...label, color: col('mist') },
        { anchor: { to: '#label', edge: 'below' }, offset: { y: mm(1.2) } }),
      text('title', '{titleText}', { ...display, fontSize: pt(30), lineHeight: 1.05,
        color: col('ink') }, at(MARGIN.inner, Y.title, PAGE.width - 2 * MARGIN.inner)),
      text('lead', '{attr.lead}', { fontFamily: TEXT, italic: true, fontSize: pt(12),
        lineHeight: 1.35, color: col('ink') }, { anchor: { to: '#title', edge: 'below' },
        offset: { y: mm(3) }, size: { width: mm(MEASURE) } }),
    ] } } });

表紙はH1レベルの見出しデザインです。見出しのglyphs属性の文字をディスプレイ書体の240 ptで組み、その下に、活字鋳造所の見本帳のように、その書体と本文用、ラベル用の書体の名前を記した等幅の2行を置きます。span: 'page'は見出しをページ幅いっぱいに組み、地は塗り足し領域の左上の角に固定するので、上端からはみ出します。minHeightは天の余白から数え、地から42 mm下のY.endまでの領域を確保します。これがないと本文が1行上から始まり、リードのすぐ下に詰まります。

レシピの全体

Sandbox
// ═══ Postext Cookbook · Nº 026 · Type specimen with every font loaded before layout ═════════
// https://postext.dev/en/cookbook/fonts-before-layout
// Code: MIT · Text: original (CC BY 4.0) · Picture: cut from the pen's own early and last builds
// Fonts: Ysabeau Office, Noto Serif Display, IBM Plex Mono (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import { buildDocument, buildDocumentWithFonts, renderPageToCanvas, defaultResourceTypes,
  registerResourceImage } from 'https://esm.sh/postext';

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

// ─── 1 · Design ─────────────────────────────────────────────────────────────
const PAGE = { width: 180, height: 240 }; // mm
const MARGIN = { top: 22, bottom: 24, inner: 20, outer: 48 }; // mm: inner is the spine side
const MEASURE = PAGE.width - MARGIN.inner - MARGIN.outer; // 112 mm: about 70 letters at 11 pt
const FIELD = 122; // mm from the top edge: the ultramarine field of the opener
const LEAD = 15.5; // pt: the body leading and the step of every vertical space
const DPI = 150; // the page's resolution: the proof on page 4 is cut at twice this
const [TEXT, DISPLAY, MONO] = ['Ysabeau Office', 'Noto Serif Display', 'IBM Plex Mono'];
const palette = { ink: '#16161a', ultramarine: '#3246d3', mist: '#c9d0f6', // mist: 4.6:1 on
  rule: '#cfc9bd', muted: '#6b6a70', paper: '#ffffff' }; // ultramarine, for labels on the field
// Every colour is linked to its palette entry; main-color catches any default left unstated.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = () => Object.entries({ ...palette, 'main-color': palette.ultramarine })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const label = { fontFamily: MONO, fontSize: pt(7.5), letterSpacing: pt(1.2),
  textTransform: 'uppercase' };
const display = { fontFamily: DISPLAY, fontWeight: 900, italic: true };

// #region type: the text face at 11 on 15.5 pt, and a waterfall of it on two leads a line
const bodyText = () => ({
  fontFamily: TEXT, fontSize: pt(11), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  textAlign: 'left', firstLineIndent: pt(0), paragraphSpacing: true }); // ragged and spaced
// Every waterfall size and pangram is two leads (31 pt) deep, on the text's 15.5 pt rhythm.
const line = (size) => ({ fontSize: pt(size), lineHeight: pt(2 * LEAD) });
const paragraphStyles = () => [
  ...[7, 8, 9, 10, 11, 12, 14].map((size) => ({ id: `s${size}`, ...line(size) })),
  { id: 'pangram', ...line(13) },
  { id: 'colophon', fontSize: pt(7), lineHeight: pt(10), fontFamily: MONO, color: col('muted') }];
// Size labels: boxless mono chips. A Plex Mono letter is 0.6 em wide, so a one-digit label gets
// half a letter each side and the samples start on one edge.
const tag = { fontFamily: MONO, fontSize: pt(7), color: col('ultramarine'),
  backgroundEnabled: false, borderWidth: pt(0), paddingX: pt(0), gap: mm(2.5) };
const chipStyles = () => [{ id: 'size', ...tag }, { id: 'size-1', ...tag, paddingX: em(0.3) }];
// #endregion

// #region opener: the H1 as a bleed field, the display face at 240 pt, labels naming the faces
const Y = { kicker: 14, glyphs: 17, label: FIELD - 12, title: FIELD + 10, // mm from the top edge

組み立てたscript.jsはそのまま動きます。任意のページのモジュールスクリプトに貼り付けるか、レシピをCodePenで開いてください。 GitHub上のレシピのフォルダー ↗ (新しいタブで開きます)

アレンジ

#ファイルをresolveで渡す

Markdownの文字列からデザインしたページへのkitFonts(FONTS)は何も宣言しません。Postextが各書体のファイルをそのresolveに求め、自分でdocument.fontsに加えます。

#書体を1つ忘れる

見出し上のラベル、表の見出し行、キャプションのラベルを組むIBM Plex Monoの太字を外すと、ブラウザーはレギュラーを太らせ、表はその書体にfakedと記し、注記はfontFallback警告を1件数えます。警告はIBM Plex Mono 700をsynthesizedとして挙げます。

-  'IBM Plex Mono': ['400', '400i', '700', '700i'], // labels, chips, the table, captions
+  'IBM Plex Mono': ['400', '400i', '700i'], // labels, chips, the table, captions

#同じ書体をPDFに埋め込む

renderToPdfは、各書体についてfontProviderが返すバイト列を埋め込みます。同じフォントを埋め込んだ本物のPDFのプロバイダーはFontsourceのlatinファイルを返しますが、これはLatin-1までしか収録していません。この小冊子のż、ł、ř、ůのためには、プロバイダーが自前のフォルダーから各書体のフォントファイル全体を返すようにします。

よくあるつまずき

つまずき

Fontsourceのファイルは文字を収め、記号は収めない

キットは各書体のFontsourceのlatinファイルを埋め込み、本文にč、ł、†があればlatin-extファイルを、α、χがあればgreekファイル(それを持つファミリーのみ。LoraとGelasioにはない)を、画面でもPDFでも加えます。→、≈、✓、★などの記号はどのファイルにもなく、PDFでは欠けます。図として描くか、数式で書くか、それを収めたファイルを持つ書体を選んでください。 PDFに埋め込むフォント →

レイアウト警告 · fontFallback

レイアウトで代替フォントを使用

原因. 文書を組んだ時点で、本文に使われたフォントがフォントセットになかった(`reason: 'missing'`)か、ファミリーにそのウェイトやイタリックのファイルがなくブラウザーが別のフォントから合成した(`'synthesized'`)ため、改行位置がPDFに埋め込まれるフォントとは別のフォントで計測されました。

対処. 最初のビルドの前にフォントを読み込んでください。`prepareFonts(content, config, { resolve })`を使うか、`buildDocumentWithFonts`でビルドすれば、ページが実際に使ったフォントも読み込んで再ビルドします。`synthesized`の場合は、そのウェイトやイタリックを読み込むか、ファミリーにあるウェイトを指定してください。 ドキュメント →

Sandboxの検査 · missingFont

フォントの欠落

原因. 設定で指定したフォントファミリーがブラウザーに読み込まれなかったため、テキストはシステムの代替フォントで計測・描画されました。

対処. ファミリー名を修正し(指定するファミリーは1つだけで、CSSのフォントスタックは使いません)、最初のレイアウトの前にすべてのフェイスを読み込んでください。CodePenのサンプルではFONTSに列挙します。 ドキュメント →

Sandboxの検査 · missingFontVariant

フォントのバリアントがありません

原因. カスタムファミリーに、文書が使うウェイトとスタイル(イタリックや太字など)のファイルがありません。

対処. 不足しているバリアントをアップロードまたは宣言するか、そのウェイトやスタイルを使わないようにしてください。 ドキュメント →

  • 書体を自分で読み込む場合、サンプル文字列なしのdocument.fonts.load(font)は、スペースを含むファイル、つまりlatinのファイルしか読み込まず、żやřはシステム書体に置き換わります。prepareFontsは文書自身の文字を渡します。
  • renderPageToCanvasとpostext-pdfは各段を端から2 pt外でクリップします。そのため幅の狭い代替書体で計測した行は最後の文字を失います。その行を計測した組版は、doc.contentWarningsにその書体をfontFallbackとして挙げます。ページを表示したり書き出したりする前に、この一覧を読んでください。

クレジット

レシピ
Ignacio Ferro
本文
書き下ろしの文章, CC BY 4.0
フォント
Ysabeau Office (SIL OFL 1.1) · Noto Serif Display (SIL OFL 1.1) · IBM Plex Mono (SIL OFL 1.1)
Sandbox