かんたんな説明
架空の地下鉄のスタイルガイドです。ブランド専用のフォントを一度だけダウンロードし、ページのプレビュー、PDF、保存したファイルのすべてで同じものを使う方法を示します。
できあがり
5路線の架空の地下鉄、Metro de Albaのアイデンティティーマニュアルを4ページ作ります。表紙では、Big Shoulders Displayで組んだ名称の下で、5本の路線が左下から1本の共有軌道で出発し、灰色の川を渡ったあと右へ枝分かれします。各節は墨色の帯の下で始まり、いずれかの路線の色で大きな2桁の番号が入ります。「01 Colour」では表の1列目が色そのもので、「02 Type」には見本行とホームの案内サインがあり、「03 Usage」は枠付きの路線図2点で終わります。規則どおりに描いたもの(Do)と、規則に反したもの(Don't)です。テキストはすべて6つのフォントファイルで組まれ、スクリプトは最初のレイアウトの前にそれらをダウンロードします。PDFも同じ6ファイルで描かれます。.postextファイルが運ぶのは5つです。ディスプレイ書体は再配布不可と指定されているためです。
このレシピが答える質問
- 自社ブランドのフォントやライセンスを受けたフォントでレイアウトし、PDFに埋め込むには?
- フォントを埋め込んだ本物のPDFをブラウザーで書き出すには?
- 見出し、太字、箇条書きの記号が青く出ないようにするには?
- 本文、キャプション、表の注に色見本(凡例の色)を加えるには?
- コードから.postextバンドルを作り、文書をSandboxやほかのプログラムに渡すには?
手短な答え
// Your licensed files, one per face in FONTS. Fontsource's copies stand in for them here:
// point FONT_URL at your own server (same origin, or one that lets this page in by CORS).
const slug = (family) => family.toLowerCase().replaceAll(' ', '-');
const FONT_URL = ({ family, weight, style }) => `https://cdn.jsdelivr.net/npm/@fontsource/`
+ `${slug(family)}@5/files/${slug(family)}-latin-${weight}-${style}.woff2`;
const brandFaces = () => Object.entries(FONTS).flatMap(([family, specs]) => specs.map((spec) => {
const weight = parseInt(spec, 10), style = spec.endsWith('i') ? 'italic' : 'normal';
return { family, weight, style, fileId: `${slug(family)}-${weight}-${style}.woff2` };
}));
const fontFiles = new Map(); // fileId → the WOFF2 bytes, fetched once
// 1 · Layout measures with document.fonts: register every face before the first build.
async function loadBrandFonts() {
await Promise.all(brandFaces().map(async ({ family, weight, style, fileId }) => {
const res = await fetch(FONT_URL({ family, weight, style }));
if (!res.ok) throw new Error(`No file for ${family} ${weight} ${style}`);
fontFiles.set(fileId, new Uint8Array(await res.arrayBuffer()));
const face = new FontFace(family, fontFiles.get(fileId), { weight: `${weight}`, style });
document.fonts.add(await face.load());
}));
}
// 2 · The PDF embeds the same bytes as TrueType. renderToPdf asks for the faces the pages
// paint; a weight or slant the brand lacks gets the family's closest file, embedded once.
async function brandFontProvider(family, weight, style) {
const cost = (f) => (f.style === style ? 0 : 1000) + Math.abs(f.weight - weight);
const own = brandFaces().filter((f) => f.family === family);
if (!own.length) throw new Error(`${family} is not one of the brand's fonts`);
return decompressWoff2(fontFiles.get(own.reduce((a, b) => (cost(b) < cost(a) ? b : a)).fileId));
}
// 3 · The bundle: customFonts names each face's file by its fileId; createBundle packs the bytes
// of every family it may hand on. Layout never reads it (gotcha: custom-fonts-declarative).
const customFonts = () => Object.keys(FONTS).map((name) => ({
name, redistributable: name !== DISPLAY, // the display face reaches suppliers another way
variants: brandFaces().filter((f) => f.family === name)
.map(({ weight, style, fileId }) => ({ weight, style, fileId, format: 'woff2' })),
}));
材料
- 機能
- 独自のフォントセマンティックカラーパレットセルの塗り色見本デザインした章扉番号付き見出し段抜きの章見出し帯名前付きの表スタイル段落スタイル独自のリソースの種類キャプションのスタイル図の配置ページデザインのテキスト・罫・ボックス本文の書体1段組みと2段組みレイアウト前のフォント読み込みPDFの書き出し.postextバンドルキャンバス上のページリソースとしての図と表
- 種類
- Public Sans, Big Shoulders Display, Spline Sans Mono (SIL OFL 1.1)
- 素材
- The network drawing on the cover and the two map examples, drawn in code (Ignacio Ferro, CC BY 4.0)
作り方
#1 · ブランドの書体を登録して組み、PDFに同じバイト列を渡す
await loadBrandFonts(); // the answer, step 1
for (const [fileId, markup] of Object.entries(ART)) await loadSvg(fileId, markup);
const doc = buildDocument({ markdown, resources }, config());
showPages(doc, { title: 'Metro de Alba · Identity manual' });
offerPdf(() => renderToPdf(doc, { fontProvider: brandFontProvider, resourceBytes: imageBytes }),
`${RECIPE}.pdf`); // step 2: the provider hands renderToPdf the same files
レイアウトはすべての語をdocument.fontsにある書体で計測します。そのため手短な答えのloadBrandFonts()は、各ファイルを一度だけ取得してバイト列を保持し、そのバイト列から作ったFontFaceをbuildDocumentの実行前に登録します。キットのkitFontsはFontsourceからしか取得しませんが、ブランドは自社のサーバーでファイルを配信しています。renderToPdfはページが描く書体だけを要求し、brandFontProviderは取得済みのバイト列で各要求に答えます。ブランドにないウェイトやイタリックを求められたら、同じファミリーで最も近いファイルを返します(なぜフォントプロバイダーが必要か)。PDFにはCanvasが計測した6ファイルが、それぞれ一度だけ埋め込まれます。
#2 · 色の体系は1つのリスト
const COLOURS = [ // id, name, screen, print (coated stock)
['line-1', 'Line 1 · Tile red', '#e4572e', '0 75 85 0'],
['line-2', 'Line 2 · Harbour teal', '#17bebb', '75 0 32 0'],
['line-3', 'Line 3 · Broom yellow', '#ffc914', '0 22 95 0'],
['line-4', 'Line 4 · Heather', '#6c4f9e', '65 75 0 0'],
['line-5', 'Line 5 · Pine', '#3f9b4a', '76 12 90 2'],
['signal-red', 'Signal red', '#c0391b', '10 88 100 2'],
['signal-green', 'Signal green', '#2b7d3c', '84 25 95 10'],
['ink', 'Ink', '#1f2124', '72 62 55 78'],
['rule', 'Rule grey', '#d9d9d4', '14 10 14 0'],
];
const palette = { ...Object.fromEntries(COLOURS.map(([id, , hex]) => [id, hex])),
paper: '#ffffff', section: '#e4572e' }; // section: the line colour of the current section
// col(): a colour linked to its palette entry, with the entry's hex beside the link.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [...Object.entries(palette), ['main-color', palette.ink]]
.map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const rgb = (hex) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16)).join(' ');
const swatchTable = () => COLOURS.reduce( // an empty first cell, filled with the colour itself
(model, [id], i) => setCellBackground(model, { row: i + 1, col: 0 }, col(id)),
{ headerRowCount: 1, columnWidths: [22, 34, 14, 15, 15], rows: [
['COLOUR', 'NAME', 'HEX', 'RGB', 'CMYK'].map((content) => ({ content, isHeader: true })),
...COLOURS.map(([, name, hex, cmyk]) =>
['', name, hex.toUpperCase(), rgb(hex), cmyk].map((content) => ({ content }))),
] });
パレットと表1.1は同じ9行から作られるので、ページで使わない値が表に載ることはありません。setCellBackgroundは各行の空いた1列目のセルをその行の色で塗り、パレットにリンクします。本文では:swatch{color="line-2"}がパレットのidを受け取り、テキストの色で縁取った正方形を描きます。main-colorにはInkの16進値が入っているので、既定でこれにリンクしている見出しや太字・イタリックの文字列は、エンジンの青ではなくInkで印刷されます。bodyText.referenceColor: col('ink')は参照の色もInkと明記します(カラーパレット)。
#3 · 扉は1つ、路線の色は3つ
// The body starts ten grid lines down, in both columns.
const opener = { enabled: true, minHeight: pt(10 * LEAD), slot: { elements: [
{ kind: 'text', id: 'number', content: '{number}', fontFamily: DISPLAY, fontWeight: 800,
fontSize: pt(130), lineHeight: 1, color: col('section'), align: 'left', overflow: 'wrap',
// Nudged by eye on the capture: the cap tops of number and title on one line.
placement: { anchor: { to: 'container', edge: 'top-left' },
offset: { x: mm(-1.5), y: mm(1.3) } } },
{ kind: 'text', id: 'title', content: '{titleText}', fontFamily: DISPLAY, fontWeight: 800,
fontSize: pt(34), lineHeight: 1, color: col('ink'), align: 'left', overflow: 'wrap',
placement: { anchor: { to: 'container', edge: 'top-left' },
offset: { x: mm(COL + GUTTER), y: mm(1) }, size: { width: mm(COL) } } },
{ kind: 'text', id: 'lead', content: '{attr.lead}', fontFamily: TEXT, fontSize: pt(12.5),
lineHeight: 1.36, color: col('ink'), align: 'left', overflow: 'wrap',
placement: { anchor: { to: '#title', edge: 'below' }, offset: { y: mm(3) },
size: { width: mm(COL) } } },
] } };
// Each section sets `section` to its line's colour; the number and the head square use it.
const section = (id) => ({ id, palette: { section: palette[id] } });
numberingTemplate: '{1:01}'はカウンターを2桁で書き、扉の{number}は01、02、03を印刷します。表紙の見出しはnumbered: falseなので番号が付きません。3つの節のスタイルの違いはパレット項目sectionだけで、それぞれが自分の路線の色をそこに設定します。番号と帯の中の正方形はsectionにリンクしているので、1つの扉のデザインで3つの節をまかなえます。minHeightは14 ptのグリッドの10行分を扉に確保するので、どの節の本文もページの同じグリッド線から始まります。
#4 · DoとDon'tは図の種類
const example = (id, name, colour) => ({ id, name, shortLabel: name, captionPrefix: name,
numberingTemplate: '{n}', resetOn: 'never', counterFormat: 'decimal',
captionStyle: { labelColor: col(colour) } });
const resourceTypes = [...defaultResourceTypes(LANG),
example('do', 'Do', 'signal-green'), example('dont', 'Don’t', 'signal-red')];
const FOOT = { position: 'bottom' }; // cited in one paragraph: its page's foot, one per column
リソースの種類には部分的なcaptionStyleを指定できます。この2つが設定するのはラベルの色だけで、DoはSignal green、Don'tはSignal redです(リソースの種類)。2つのシグナル色は白地に対して5.1:1と5.5:1に達しますが、路線1、2、3、5の色は小さな文字に必要な4.5:1に届きません。どちらの図もposition: 'bottom'でフロートし、見出しDrawing the mapの直後の同じ段落で引用されます。そのため2点は4ページの地を分け合い、Doが左の段、Don'tが右の段に入ります。
#5 · バンドルには共有してよいフォントを収める
const pack = Object.assign(document.createElement('button'), { type: 'button',
textContent: 'Build the .postext' });
pack.addEventListener('click', async () => {
const { bytes, manifest, warnings } = await createBundle({
name: 'Metro de Alba identity manual', locale: LANG, markdown, config: config(), resources,
files: new Map([...Object.entries(ART), ...fontFiles]), // fileId → SVG markup or font bytes
});
const size = `${Math.round(bytes.length / 1024)} KB`;
const packed = `fonts inside: ${manifest.fonts.map((font) => font.name).join(', ')}`;
kitStatus(['.postext', size, packed, ...warnings].join(' · ')); // warnings: what stayed out
pack.replaceWith(Object.assign(document.createElement('a'), { download: `${RECIPE}.postext`,
href: URL.createObjectURL(new Blob([bytes], { type: 'application/zip' })),
textContent: `Download ${RECIPE}.postext · ${size}` }));
});
document.getElementById('pt-actions').append(pack);
createBundleはconfig.customFontsを読み、各バリアントのバイト列をfileIdをもとにfilesから探してfonts/の下に書き込み、マニフェストにfonts項目を加えます。ディスプレイ書体のファミリーにはredistributable: falseが付いています。これはファイルを他者に渡すことを禁じるライセンスの代役です(Big Shoulders Display自体はOFLです)。そのファイルはバンドルに入らず、warningsがファミリー名を挙げます。81 KBのファイルには、章、設定、3点の図、5つのフォントファイルが収まります。レイアウトはcustomFontsを参照しないので、これがなくてもページは同じに仕上がります(バンドルを作成する)。
レシピの全体
// ═══ Postext Cookbook · Nº 040 · Brand fonts in layout, PDF and bundle ════════════
// https://postext.dev/en/cookbook/brand-fonts-identity-manual
// Code: MIT · Text and drawings: original (CC BY 4.0) · Metro de Alba is a fictional network
// Fonts: Public Sans, Big Shoulders Display, Spline Sans Mono (OFL 1.1) · Needs postext ≥ 1.25.0
import {
buildDocument, renderPageToCanvas, registerResourceImage, defaultResourceTypes, setCellBackground,
createBundle,
} 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 = 'brand-fonts-identity-manual';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region answer: the brand's font files, fetched once for the layout, the PDF and the bundle
// Your licensed files, one per face in FONTS. Fontsource's copies stand in for them here:
// point FONT_URL at your own server (same origin, or one that lets this page in by CORS).
const slug = (family) => family.toLowerCase().replaceAll(' ', '-');
const FONT_URL = ({ family, weight, style }) => `https://cdn.jsdelivr.net/npm/@fontsource/`
+ `${slug(family)}@5/files/${slug(family)}-latin-${weight}-${style}.woff2`;
const brandFaces = () => Object.entries(FONTS).flatMap(([family, specs]) => specs.map((spec) => {
const weight = parseInt(spec, 10), style = spec.endsWith('i') ? 'italic' : 'normal';
return { family, weight, style, fileId: `${slug(family)}-${weight}-${style}.woff2` };
}));
const fontFiles = new Map(); // fileId → the WOFF2 bytes, fetched once
// 1 · Layout measures with document.fonts: register every face before the first build.
async function loadBrandFonts() {
await Promise.all(brandFaces().map(async ({ family, weight, style, fileId }) => {
const res = await fetch(FONT_URL({ family, weight, style }));
if (!res.ok) throw new Error(`No file for ${family} ${weight} ${style}`);
fontFiles.set(fileId, new Uint8Array(await res.arrayBuffer()));
const face = new FontFace(family, fontFiles.get(fileId), { weight: `${weight}`, style });
document.fonts.add(await face.load());
}));
}
// 2 · The PDF embeds the same bytes as TrueType. renderToPdf asks for the faces the pages
// paint; a weight or slant the brand lacks gets the family's closest file, embedded once.
async function brandFontProvider(family, weight, style) {
const cost = (f) => (f.style === style ? 0 : 1000) + Math.abs(f.weight - weight);
const own = brandFaces().filter((f) => f.family === family);
if (!own.length) throw new Error(`${family} is not one of the brand's fonts`);
return decompressWoff2(fontFiles.get(own.reduce((a, b) => (cost(b) < cost(a) ? b : a)).fileId));
}
// 3 · The bundle: customFonts names each face's file by its fileId; createBundle packs the bytes
// of every family it may hand on. Layout never reads it (gotcha: custom-fonts-declarative).
組み立てたscript.jsはそのまま動きます。任意のページのモジュールスクリプトに貼り付けるか、レシピをCodePenで開いてください。 GitHub上のレシピのフォルダー ↗ (新しいタブで開きます)
アレンジ
#ディスプレイ書体も収める
ライセンスがファイルの再配布を認めているなら、フラグを外します。バンドルは3つのファミリーすべてを96 KBで運びます。
- name, redistributable: name !== DISPLAY, // the display face reaches suppliers another way
+ name,#本物のBoldを使う
ブランドにBoldがないため、boldFontWeight: 600が太字の文字列、表の見出し、キャプションのラベルをSemiBoldで組んでいます。ファミリーにBoldがあるなら、そのファイルをFONTSに加えて設定を削除し、サンプルの見本行とそこにある「There is no Bold」を書き直してください。Boldを加えると、この一文は事実でなくなります。
- boldFontWeight: 600, // the brand has no Bold: its SemiBold sets **emphasis**
- 'Public Sans': ['400', '400i', '600', '600i'],
+ 'Public Sans': ['400', '400i', '600', '600i', '700', '700i'],よくあるつまずき
つまずき
customFontsはフォントを読み込まない
config.customFontsはフォントファイルをfileIdで名指しするだけです。buildDocumentとCanvas、HTML、PDFのレンダラーはこれを読まないため、ここに挙げても登録していないファミリーは代替フォントで計測され、描かれます。各フォントは最初のビルドの前に自分で登録し(バイト列からFontFaceを作る)、同じバイト列をPDFのフォントプロバイダーにも渡してください。この一覧を読むのは、ファイルを.postextに詰めるcreateBundleと、フォントを登録するSandboxです。 独自のフォント →
つまずき
ファミリーにないボールドやイタリックは、画面では擬似的に作られ、PDFでは作られない
ファミリーが持たないウェイトやスタイル(1書体しかないラベル用フォントでの太字の表ヘッダー、イタリックのないサンセリフでのイタリック)を求めると、ブラウザーはCanvasとHTMLでそれを合成し、同じ幅のまま立体を太らせたり傾けたりします。PDFは実在するフォントしか埋め込まないため、そこではプロバイダーが返す最も近いフォントで通常の形のまま印字されます。フォントの一覧にはファミリーが持つフォントだけを入れ、tableStyle.headerBold: falseのように、すべてのスタイルをそれに合わせてください。 PDFに埋め込むフォント →
つまずき
Fontsourceのファイルは文字を収め、記号は収めない
キットは各書体のFontsourceのlatinファイルを埋め込み、本文にč、ł、†があればlatin-extファイルを、α、χがあればgreekファイル(それを持つファミリーのみ。LoraとGelasioにはない)を、画面でもPDFでも加えます。→、≈、✓、★などの記号はどのファイルにもなく、PDFでは欠けます。図として描くか、数式で書くか、それを収めたファイルを持つ書体を選んでください。 PDFに埋め込むフォント →
createBundleには、customFontsが与えるfileIdをキーにして各フォントのバイト列を渡してください。バイト列のないバリアントは「missing file, skipped」という警告とともに除外され、すべてのバリアントを失ったファミリーはマニフェストから消えます。
クレジット
- 本文
- The Metro de Alba identity manual, a fictional network · Ignacio Ferro · CC BY 4.0
- 画像
- The network drawing on the cover and the two map examples, drawn in code · Ignacio Ferro · CC BY 4.0
- フォント
- Public Sans (SIL OFL 1.1) · Big Shoulders Display (SIL OFL 1.1) · Spline Sans Mono (SIL OFL 1.1)


