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

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

同じフォントを埋め込んだ本物のPDF

PDFに書き出すリサイタルのプログラム。各書体はFontFace用とPDF用を兼ねて1回だけ取得し、見出しはそれぞれしおりになります。

このページの内容
出力
Canvas · PDF
レベル
中級
Postext
Postext 1.65.0で検証済み
1.25.0以上が必要 · postext-pdf ≥ 1.25.0
ライセンス
2026年10月10日更新
コードMIT · 本文CC BY 4.0

1ページ(全4ページ)

  • 英語の見本:日本語版はまだありません
  • 仕上がり148 × 210 mm
  • 1段
  • Crimson Text 10/13.3
  • Fraunces
  • Tenor Sans
  • 4ページ
  • レベル
  • Postext 1.57.1
  • 組版時間54 ms
  • コード180行

かんたんな説明

夕べの演奏会の4ページのプログラム。画面とぴったり同じPDFとして保存する方法を示します。フォントはファイルの中に収まり、見出しは一覧からすぐに移動できます。

できあがり

夕暮れのリサイタル『Home from Sea』のプログラムです。ソプラノ、チェロ、ハープの小編成のアンサンブルのためのA5判4ページで、表紙は夜の青緑、題は金色のFrauncesイタリックで、金色の波模様の鱗が下端から何列も立ち上がります。中面では、演奏順を表にします。見出し行は青緑の地にTenor Sansの大文字で、合計行には色を敷きます。曲目解説は両端そろえのCrimson Textです。3つの歌の歌詞はLongfellow、Stevenson、Tennysonの詩で、刊本どおりのインデントで組みます。「Build the PDF」ボタンで作るのは、聴衆にメールで送ったり会場のWebサイトに載せたりするファイルです。4ページは画面と1行ずつ一致します。ブラウザーが読み込んだ5つのフォントファイルだけを埋め込み、見出しはそれぞれしおりになります。商業印刷に入稿するなら入稿用PDFを参照してください。

このレシピが答える質問

  • フォントを埋め込んだ本物のPDFをブラウザーで書き出すには?
  • 行の分割が変わったりPDFで単語が重なったりするのはなぜですか?フォントを正しく読み込むには?

手短な答え

script.js · 15〜51行コード全体で見る
// Hook-up: `await registerFaces()` before the first build; `renderToPdf(doc, { fontProvider })`.
const files = new Map(); // 'crimson-text-latin-600-normal' → its WOFF2 (gotcha: latin-subset)
function fontFile(family, weight, style) {
  const id = family.toLowerCase().replaceAll(' ', '-'), file = `${id}-latin-${weight}-${style}`;
  if (!files.has(file)) {
    files.set(file, fetch(`https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/${file}.woff2`)
      .then((res) => {
        if (!res.ok) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
        return res.arrayBuffer();
      }));
  }
  return files.get(file);
}
const facesOf = (family) => (FONTS[family] ?? []).map((spec) =>
  ({ spec, weight: parseInt(spec, 10), style: spec.endsWith('i') ? 'italic' : 'normal' }));

// The screen: a FontFace per face, from those bytes, before the first build.
const registerFaces = () => Promise.all(Object.keys(FONTS).flatMap((family) =>
  facesOf(family).map(async ({ weight, style }) => {
    const face = new FontFace(family, await fontFile(family, weight, style),
      { weight: `${weight}`, style });
    document.fonts.add(await face.load());
  })));

// The PDF: the same bytes as TrueType. renderToPdf asks for each face the pages paint and no
// other. A face FONTS lacks gets the closest one it has, and is logged as a stand-in: the
// status line should list none.
const embedded = new Set(), standIns = new Set(); // shown once the PDF is ready
async function fontProvider(family, weight, style) {
  if (!FONTS[family]) throw new Error(`${family} is not in FONTS: no page was set in it`);
  const cost = (f) => (f.style === style ? 0 : 1000) + Math.abs(f.weight - weight);
  const best = facesOf(family).reduce((a, b) => (cost(b) < cost(a) ? b : a));
  const asked = `${weight}${style === 'italic' ? 'i' : ''}`;
  embedded.add(`${family} ${best.spec}`);
  if (asked !== best.spec) standIns.add(`${family} ${asked} → ${best.spec}`);
  return decompressWoff2(new Uint8Array(await fontFile(family, best.weight, best.style)));
}

材料

種類
Crimson Text, Fraunces, Tenor Sans (SIL OFL 1.1)
素材
  • The seigaiha waves on the cover, drawn in code in the page’s palette (Ignacio Ferro, CC BY 4.0)

作り方

#1 · 書体ごとに1回のダウンロードを、ページとPDFで共有する

コードは上の手短な答えにあります。Postextは組版の時点でブラウザーが読み込んでいる書体ですべての語を計測し、PDFは各行をそのレイアウトが置いた位置に描きます。PDFが別のファイル、たとえば可変フォントの既定のインスタンスやシステムの代替フォントを埋め込むと、各語は計測した位置から始まるものの、文字の幅が違うので、語が重なったり隙間が空いたりします。そこでこのレシピは各書体を1回だけ取得します。そのバイト列は最初の組版の前にFontFaceになり、フォントプロバイダーは同じバイト列をdecompressWoff2に通してPDFに渡します。書き出しのために別途ダウンロードするフォントはありません。

#2 · フォントが先、レイアウトは後

script.js · 363〜367行コード全体で見る
await registerFaces(); // the answer: every face in FONTS, from its own bytes
await loadSvg('cover.svg', coverArt(PAGE.width, PAGE.height, WAVES));
// Every face is declared by now; one FONTS forgot would come from Fontsource, for the screen only.
const doc = await buildDocumentWithFonts({ markdown, resources }, config(), kitFonts(FONTS));
showPages(doc, { title: 'Home from Sea · a recital programme' });

registerFaces()はFONTSのすべての書体が読み込まれたときにだけ解決するので、最初の組版はPDFが埋め込むのと同じ書体で計測します。これが唯一の組版でもあります。FONTSにはページで使う書体をすべて並べてあるので、buildDocumentWithFontsが探す書体はどれもすでに宣言されているからです(レイアウトの前にフォントを読み込む)。ただし、この確認が助けになるのは画面だけです。FONTSに書体が欠けていると、エンジンはそれをキットに求め、Fontsourceのファイルを読み込んでレイアウトをもう一度走らせます。コンソールには何も出ません。それでもPDFには、プロバイダーが持つ最も近い書体が入ります。

#3 · 書き出しと、埋め込んだものの一覧

script.js · 371〜386行コード全体で見る
const bar = Object.assign(document.createElement('progress'), { max: 1, value: 0 });
const list = (faces) => [...faces].join(', ') || 'none';
offerPdf(() => {
  document.getElementById('pt-actions').prepend(bar);
  return renderToPdf(doc, {
    fontProvider, // the answer: the page's own font files
    resourceBytes: imageBytes, // the cover drawing, as vector paths
    outlines: true, // the default, spelled out: each heading becomes a bookmark
    onProgress: ({ phase, pages, totalPages }) => {
      bar.value = pages / totalPages;
      const says = { prepare: 'fonts and cover embedded', pages: `page ${pages} of ${totalPages}`,
        save: `embedded: ${list(embedded)} · stand-ins: ${list(standIns)}` };
      kitStatus(`PDF · ${says[phase]}`);
    },
  });
}, `${RECIPE}.pdf`);

renderToPdfはonProgressを3つの段階で呼びます。フォントと表紙を埋め込んだ後のprepare、各ページの後のpages、ファイルを書く前のsaveです。プロバイダーに求めるのはページに描かれる書体だけで、ここでは5つです。状態の行は、プロバイダーが渡した5つのファイル(FONTSにあるものとちょうど同じ)を列挙し、代用はありません。代用が出たら、FONTSに欠けている書体があるということです。Crimson Text 600を外すと、状態の行はCrimson Text 600 → 400と報告し、4ページ目の太字の「The Harbour Consort」はレギュラーのウェイトで印刷されます。CodePenのプレビューはPDFを表示できないので、キットのofferPdfがボタンを2つのリンクに置き換えます。1つは新しいタブでPDFを開き、もう1つはダウンロードします(PDFの生成)。

#4 · 見出しの木がしおりの木になる

script.js · 108〜116行コード全体で見る
const headings = { fontFamily: 'Fraunces', fontWeight: 300, color: col('band'),
  marginTop: pt(0), marginBottom: pt(0), // a two-line H2 carries its own space above
  levels: [ // a section opens on the next page, left or right: a programme has no blank pages
    { level: 1, breakBefore: { enabled: true, parity: 'any' }, advancedDesign: opener },
    { level: 2, ...H2 },
  ] };
// The performers: a top-level bookmark, no break, no opener (gotcha: style-inherits-break).
const aside = { id: 'aside', breakBefore: { enabled: false }, advancedDesign: { enabled: false },
  ...H2, marginTop: pt(LEAD) };

PDFのしおりパネルには、表紙の題、その下に「About the music」を含む「Programme」、3つの歌を含む「The texts」、「The performers」が並びます。アウトラインは見出しのレベルに従うので、レベルはしおりを念頭に置いて選びます。ここでは節ごとにH1、歌ごとにH2です。「The performers」には独自の見出しスタイルがあり、改ページも扉もないH1なので、Tennysonの詩と4ページ目を分け合いながら、最上位のしおりを得ます。表紙の題を2行に分ける\\は、しおりではスペースになります。

#5 · 題と著者はフロントマターから

script.js · 80〜93行コード全体で見る
const cover = {
  id: 'cover', span: 'page', header: { elements: [] }, footer: { elements: [] },
  advancedDesign: { enabled: true, slot: { elements: [
    { kind: 'image', id: 'night', resourceId: 'cover',
      placement: { anchor: { to: 'bleed', edge: 'top-left' }, size: { width: 'fill' } } },
    text('consort', '{author}', at('page', 'top', 18), label(8.5, 'gilt')),
    text('title', '{titleText}', at('page', 'top', 26, 120), // the \\ in the heading breaks it
      { ...title(68), lineHeight: 0.95, color: col('gilt') }),
    text('subtitle', '{subtitle}', at('page', 'top', 75, 66), { fontFamily: 'Crimson Text',
      italic: true, fontSize: pt(12.5), lineHeight: 1.25, color: col('foam') }),
    text('when', '{attr.when}', at('page', 'top', 91), label(LABEL, 'foam')),
    text('where', '{attr.where}', at('page', 'top', 96), label(LABEL, 'foam')),
  ] } },
};

表紙は{author}と{subtitle}でフロントマターの値を2つ印刷し、PDFの文書プロパティは同じブロックから題『Home from Sea』と著者「The Harbour Consort」を取ります。日付と会場は表紙の見出しの属性です。その背後の画像はページ幅のSVG1つで、PDFはそれをベクターのパスのまま保ちます。

レシピの全体

Sandbox
// ═══ Postext Cookbook · Nº 025 · A real PDF with the same fonts embedded ═══════════
// https://postext.dev/en/cookbook/pdf-with-embedded-fonts
// Code: MIT · Text: notes original (CC BY 4.0), poems in the public domain · Cover: drawn in code
// Fonts: Crimson Text, Fraunces, Tenor Sans (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

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

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region answer: one download per face: the layout measures it, the PDF embeds it
// Hook-up: `await registerFaces()` before the first build; `renderToPdf(doc, { fontProvider })`.
const files = new Map(); // 'crimson-text-latin-600-normal' → its WOFF2 (gotcha: latin-subset)
function fontFile(family, weight, style) {
  const id = family.toLowerCase().replaceAll(' ', '-'), file = `${id}-latin-${weight}-${style}`;
  if (!files.has(file)) {
    files.set(file, fetch(`https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/${file}.woff2`)
      .then((res) => {
        if (!res.ok) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
        return res.arrayBuffer();
      }));
  }
  return files.get(file);
}
const facesOf = (family) => (FONTS[family] ?? []).map((spec) =>
  ({ spec, weight: parseInt(spec, 10), style: spec.endsWith('i') ? 'italic' : 'normal' }));

// The screen: a FontFace per face, from those bytes, before the first build.
const registerFaces = () => Promise.all(Object.keys(FONTS).flatMap((family) =>
  facesOf(family).map(async ({ weight, style }) => {
    const face = new FontFace(family, await fontFile(family, weight, style),
      { weight: `${weight}`, style });
    document.fonts.add(await face.load());
  })));

// The PDF: the same bytes as TrueType. renderToPdf asks for each face the pages paint and no
// other. A face FONTS lacks gets the closest one it has, and is logged as a stand-in: the
// status line should list none.
const embedded = new Set(), standIns = new Set(); // shown once the PDF is ready
async function fontProvider(family, weight, style) {
  if (!FONTS[family]) throw new Error(`${family} is not in FONTS: no page was set in it`);
  const cost = (f) => (f.style === style ? 0 : 1000) + Math.abs(f.weight - weight);
  const best = facesOf(family).reduce((a, b) => (cost(b) < cost(a) ? b : a));
  const asked = `${weight}${style === 'italic' ? 'i' : ''}`;
  embedded.add(`${family} ${best.spec}`);

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

アレンジ

#しおりを入れない

1ページのチラシやポスターには、しおりを付けるものがありません。outlines: falseにするとPDFにアウトラインはなく、サイドバーを閉じた状態で開きます。

-    outlines: true, // the default, spelled out: each heading becomes a bookmark
+    outlines: false,

#フォントを自分で配信する

取得先を、同じ静的WOFF2ファイルの自前のコピーに向けます。ウェイトとスタイルごとに1ファイルで、ファイル名はFontsourceと同じにします。ページとPDFは、引き続き各ダウンロードを共有します。

-    files.set(file, fetch(`https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/${file}.woff2`)
+    files.set(file, fetch(`/fonts/${file}.woff2`)
       .then((res) => {
-        if (!res.ok) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
+        if (!res.ok) throw new Error(`No font file ${file}.woff2`);

よくあるつまずき

つまずき

ファミリーにないボールドやイタリックは、画面では擬似的に作られ、PDFでは作られない

ファミリーが持たないウェイトやスタイル(1書体しかないラベル用フォントでの太字の表ヘッダー、イタリックのないサンセリフでのイタリック)を求めると、ブラウザーはCanvasとHTMLでそれを合成し、同じ幅のまま立体を太らせたり傾けたりします。PDFは実在するフォントしか埋め込まないため、そこではプロバイダーが返す最も近いフォントで通常の形のまま印字されます。フォントの一覧にはファミリーが持つフォントだけを入れ、tableStyle.headerBold: falseのように、すべてのスタイルをそれに合わせてください。 PDFに埋め込むフォント →

つまずき

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

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

つまずき

見出しスタイルはその階層の改ページを受け継ぐ

headingStylesの項目は、指定しなかったフィールドをすべて見出しの階層から受け継ぎ、breakBeforeも例外ではありません。:::pagebreakのあとのH1に付けた目次や奥付のスタイルはparity 'odd'を受け継ぎ、白ページの後ろに置かれます。こうしたスタイルにはbreakBefore: { enabled: false }を指定してください。 見出しスタイル →

ページで使う書体は、本文の太字とイタリックも含めて、すべてFONTSに並べます。1つでも欠けていると、キットが警告なしにその書体を読み込むので画面は正しく見えますが、PDFはプロバイダーの最も近い書体で印刷され、入れ替わりに気づける手がかりは状態の行に出る代用だけです。

静的なファイルを、ウェイトとスタイルごとに1つずつ使います。可変WOFF2からは既定のインスタンスしか埋め込まれないので、太字の部分がレギュラーのウェイトで印刷されてしまいます(なぜフォントプロバイダーが必要か)。

クレジット

レシピ
Ignacio Ferro
本文
画像
  • The seigaiha waves on the cover, drawn in code in the page’s palette · Ignacio Ferro · CC BY 4.0
フォント
Crimson Text (SIL OFL 1.1) · Fraunces (SIL OFL 1.1) · Tenor Sans (SIL OFL 1.1)
SandboxPDF