In breve
Un manuale di stile per una metropolitana inventata. Mostra come scaricare una sola volta i font di un marchio e usarli per l’anteprima delle pagine, per il PDF e per il file salvato.
Che cosa comporrai
Quattro pagine del manuale d’identità di Metro de Alba, una metropolitana immaginaria di cinque linee. In copertina le cinque linee partono dal basso a sinistra su un binario comune e si diramano verso destra dopo aver attraversato un fiume grigio, sotto il nome in Big Shoulders Display. Ogni sezione si apre sotto una fascia color inchiostro, con un grande numero di due cifre nel colore di una linea. In 01 Colour la prima colonna della tabella è il colore stesso; 02 Type ha righe di campione e un cartello di banchina, e 03 Usage chiude con due disegni di mappa incorniciati, uno fatto secondo le regole (Do) e uno contro (Don't). Tutto il testo è composto con sei file di font che lo script scarica prima della prima impaginazione. Il PDF è disegnato con gli stessi sei file, e il file .postext ne contiene cinque, perché il carattere da titolo è marcato come non ridistribuibile.
Questa ricetta risponde a
- Come uso i font del mio marchio o con licenza nell’impaginazione e li incorporo nel PDF?
- Come esporto nel browser un vero PDF con i font incorporati?
- Come evito che titoli, parole in grassetto e punti elenco escano in blu?
- Come aggiungo campioni di colore come legenda nel testo, nelle didascalie o nelle note di tabella?
- Come creo un pacchetto .postext dal codice, per passare un documento alla Sandbox o a un altro programma?
La risposta breve
// 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' })),
}));
Ingredienti
- Funzionalità
- I tuoi fontTavolozza di colori semanticaRiempimenti delle celleCampioni di coloreAperture progettateTitoli numeratiFascia di capitolo a tutta larghezzaStili di tabella con nomeStili di paragrafoTipi di risorsa personalizzatiStile delle didascalieCollocazione delle figureTesto, filetti e riquadri nei progetti di paginaCarattere del testo correnteUna o due colonneI font prima dell’impaginazioneEsportazione in PDFPacchetti .postextPagine su un canvasFigure e tabelle come risorse
- Usa anche
- RiquadriCitazioni che collocano le figureAttributi dei titoliStili di titoloFigura e Tabella nella tua linguaColori per parteFont incorporati nel PDFTestatine per sezioneCapitoli non numerati
- Tipo
- Public Sans, Big Shoulders Display, Spline Sans Mono (SIL OFL 1.1)
- Risorse
- The network drawing on the cover and the two map examples, drawn in code (Ignacio Ferro, CC BY 4.0)
Preparazione
#1 · Registra i caratteri del marchio, componi e dai al PDF gli stessi byte
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
L’impaginazione misura ogni parola con i caratteri in document.fonts, quindi loadBrandFonts() nella risposta breve scarica ogni file una volta, ne conserva i byte e registra un FontFace costruito da essi prima che giri buildDocument. I kitFonts del kit scaricano solo da Fontsource, mentre un marchio serve i suoi file dal proprio server. renderToPdf chiede i caratteri che le pagine disegnano, e brandFontProvider risponde a ogni richiesta con i byte già scaricati; un peso o un’inclinazione che il marchio non ha riceverebbe il file più vicino della stessa famiglia (Why a font provider?). Il PDF incorpora i sei file che il canvas ha misurato, ognuno una volta.
#2 · Il sistema dei colori è un solo elenco
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 }))),
] });
Poiché la tavolozza e la tabella 1.1 si costruiscono dalle stesse nove righe, la tabella non può elencare un valore che le pagine non usano. setCellBackground riempie la prima cella vuota di ogni riga con il colore di quella riga, collegato alla tavolozza. Nel testo, :swatch{color="line-2"} prende un id della tavolozza e disegna un quadrato bordato nel colore del testo. main-color ha l’esadecimale di Ink, quindi titoli e parti in grassetto e corsivo, collegati a esso per impostazione predefinita, si stampano in Ink invece che nel blu del motore. bodyText.referenceColor: col('ink') assegna Ink anche ai rimandi (Color Palette).
#3 · Un’apertura, tre colori di linea
// 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}' scrive il contatore con due cifre, e {number} stampa 01, 02 e 03 nell’apertura; il titolo di copertina è numbered: false e non riceve numero. I tre stili di sezione differiscono solo nella voce della tavolozza section, che ognuno imposta al colore della sua linea. Il numero e il quadrato nella fascia sono collegati a section, così una sola grafica di apertura serve tutte e tre le sezioni. minHeight riserva all’apertura dieci righe della griglia da 14 pt, e il testo di ogni sezione comincia sulla stessa riga della griglia della sua pagina.
#4 · Do e Don't sono tipi di figura
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
Un tipo di risorsa può avere un captionStyle parziale, e questi due impostano solo il colore dell’etichetta, verde Signal per Do e rosso Signal per Don't (Resource types). I segnali arrivano a 5,1:1 e 5,5:1 sul bianco, mentre le linee 1, 2, 3 e 5 restano sotto il 4,5:1 che serve al testo piccolo. Entrambi i disegni flottano con position: 'bottom' e sono citati nello stesso paragrafo, il primo sotto «Drawing the map», quindi si dividono il piede di pagina 4, Do nella colonna sinistra e Don't in quella destra.
#5 · Il pacchetto include i font che può condividere
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 legge config.customFonts, cerca i byte di ogni variante in files tramite il suo fileId e li scrive sotto fonts/, con una voce fonts nel manifest. La famiglia da titolo ha redistributable: false, al posto di una licenza che vieti di cedere i file (Big Shoulders Display in realtà è sotto OFL). Il suo file resta fuori, e warnings indica la famiglia. Il file da 81 KB contiene il capitolo, la configurazione, i tre disegni e cinque file di font. L’impaginazione non legge mai customFonts; le pagine escono identiche senza (Creating a bundle).
La ricetta completa
// ═══ 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).
Lo script.js composto funziona così com’è: incollalo nello script modulo di qualsiasi pagina, oppure apri la ricetta su CodePen. Cartella della ricetta su GitHub ↗ (si apre in una nuova scheda)
Varianti
#Includi anche il carattere da titolo
Se la licenza ti permette di cedere i file, togli il flag, e il pacchetto contiene tutte e tre le famiglie in 96 KB.
- name, redistributable: name !== DISPLAY, // the display face reaches suppliers another way
+ name,#Usa un vero Bold
boldFontWeight: 600 compone le parti in grassetto, le intestazioni delle tabelle e le etichette delle didascalie nel SemiBold, perché il marchio non ha un Bold; se la tua famiglia ce l’ha, aggiungi i suoi file a FONTS, elimina l’impostazione e riscrivi la riga di campione dell’esempio e il suo «There is no Bold», che non sarebbe più vero.
- 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'],Errori frequenti
Errore frequente
customFonts non carica alcun font
config.customFonts si limita a nominare i file dei font per fileId: buildDocument e i renderer canvas, HTML e PDF non lo leggono mai, quindi una famiglia elencata lì e non registrata viene misurata e disegnata con un font di ripiego. Registra tu ogni variante (un FontFace creato dai suoi byte) prima della prima build e passa gli stessi byte al provider dei font del PDF. createBundle legge l’elenco per mettere i file in un .postext, e la Sandbox lo legge per registrare le varianti. I tuoi font →
Errore frequente
Un grassetto o un corsivo che la famiglia non ha viene simulato a schermo, non nel PDF
Quando il testo chiede un peso o uno stile che la sua famiglia non include (un’intestazione di tabella in grassetto con un font per etichette a una sola variante, un corsivo in un sans senza corsivi), il browser lo sintetizza sul canvas e in HTML, ispessendo o inclinando il tondo sulle stesse larghezze. Un PDF incorpora solo varianti reali, quindi lì la variante più vicina fornita dal provider si stampa in tondo. Metti nell’elenco dei font solo le varianti che la famiglia include e imposta ogni stile di conseguenza, per esempio tableStyle.headerBold: false. Font incorporati nel PDF →
Errore frequente
I file di Fontsource coprono le lettere, non i simboli
Il kit incorpora il file latin di Fontsource di un carattere, più il suo file latin-ext per č, ł, † e il suo file greek per α, χ (nelle famiglie che ne hanno uno: Lora e Gelasio no), quando il testo li compone, a schermo e nel PDF. Simboli come →, ≈, ✓ e ★ non sono in nessuno di quei file e spariscono nel PDF: disegnali, componili come matematica o scegli un carattere i cui file li contengano. Font incorporati nel PDF →
Passa a createBundle i byte di ogni font sotto il fileId che gli assegna customFonts. Una variante senza byte viene esclusa con un avviso «missing file, skipped», e una famiglia che perde tutte le varianti sparisce dal manifest.
Crediti
- Ricetta
- Ignacio Ferro
- Testo
- The Metro de Alba identity manual, a fictional network · Ignacio Ferro · CC BY 4.0
- Immagini
- The network drawing on the cover and the two map examples, drawn in code · Ignacio Ferro · CC BY 4.0
- Font
- Public Sans (SIL OFL 1.1) · Big Shoulders Display (SIL OFL 1.1) · Spline Sans Mono (SIL OFL 1.1)
- Codice
- MIT, come Postext
Modifica questo testo ↗ (si apre in una nuova scheda)Cartella della ricetta su GitHub ↗ (si apre in una nuova scheda)


