Skip to main content

Fonts

Layout measures text with real font files, so the fonts available decide where lines break and pages end. Twip makes no font choices of its own: your application decides which fonts exist, what draws a family a document names, and what happens when nothing does. Every session draws with a FontLibrary. Share one: in the browser FontLibrary.default() is the page's library, and in .NET FontLibrary.System is the process's.

Twip bundles three fonts, none of which a document can name:

  • A symbol font that draws bullets, checkboxes, arrows, check marks, card suits and common math signs when no other font has them. You can replace it or turn it off.
  • An East Asian punctuation font. In text marked East Asian (w:hint="eastAsia") whose East Asian font isn't an East Asian font, shared characters such as quotes, the section sign and arrows are drawn in MS Mincho. Twip draws them with MS Mincho when your library has it, or an alias or replacement for it; otherwise with this font, which has MS Mincho's widths and line height, so the text lays out the same. Its outlines are Noto Serif JP's.
  • An interface font that draws the ruler's numbers and overlay labels. It never draws document text.

How a family resolves​

For each family and style a document uses, the library tries these in order and stops at the first family it has:

  1. A replacement for the family (setReplacements), even when the family is in the library. The replacement's target goes through steps 2 and 3.
  2. The family itself.
  3. Its aliases (setAliases), followed up to 8 hops.
  4. What your resolver answered for it (a family or a category). While the resolver is still working, the family is pending and this step is skipped.
  5. The default of its generic category (setGenericDefaults), when you set one.
  6. The general fallback (setFallback).
  7. The first face added to the library. In an empty library, the symbol font draws text as boxes.

A character the resulting font doesn't have comes from your character-fallback families, then the symbol font, and otherwise draws as the font's missing-glyph box.

For example, take a document with bold Garamond text, a library without Garamond, and a serif default of Tinos. Steps 1 to 3 find nothing. The document's font table says Garamond is a serif (w:family="roman"), so step 5 draws it in Tinos Bold, and the report lists Garamond (bold) as missing, drawn with Tinos, by generic.

Nothing here changes the document. Saved files and the formatting a session reports (the font box) keep the family the document names. To change the document itself, see Rewriting a document's fonts.

Adding fonts​

add (AddAsync) takes TrueType, OpenType, a collection, WOFF or WOFF2, as bytes, a URL or a path, and returns the faces it added.

// One library per page, shared by every editor. The browser gives the engine no system fonts.
const fonts = FontLibrary.default();

// Files you ship: TTF, OTF, TTC, WOFF or WOFF2, as bytes or a URL. Each returns the faces it added.
await fonts.add('/fonts/Carlito-Regular.ttf');
await fonts.add(new URL('/fonts/Carlito-Bold.ttf', location.href));
// The system's fonts, shared per process. FontLibrary.CreateEmpty() starts with none.
var fonts = FontLibrary.System;

// Files you ship: TTF, OTF, TTC, WOFF or WOFF2, as bytes or a path. Each returns the faces it added.
await fonts.AddAsync("fonts/Carlito-Regular.ttf");
  • Variable fonts. Each named instance of a variable font is a face, named as Windows names it ("Bahnschrift SemiBold", "Segoe UI Variable Display Semib"), so documents find them by those names, and bold picks the font's Bold instance. PDF export draws variable faces as outlines (Type 3 fonts): the text stays selectable, but isn't hinted.
  • System fonts (.NET and Rust). FontLibrary.System loads the machine's fonts; FontLibrary.CreateEmpty() starts with none. The browser gives the engine no fonts, so a web page adds what its documents use, or resolves them on demand.
  • Linux. On Debian and Ubuntu, fonts-crosextra-carlito fonts-crosextra-caladea fonts-liberation installs the metric-compatible families the recommended setup names. On Alpine, install a font package such as font-liberation.

families() (GetFamiliesAsync) lists every family the library can draw, for a font box.

Aliases​

An alias draws a family the library doesn't have with another, such as Arial with Arimo. It applies only when the family is missing: where Arial is installed, Arial draws. Aliases match names case-insensitively, can apply to one style only (bold, italic), chain up to 8 hops (A → B → C), and can point at a generic category instead of a family.

// When a document asks for Arial and the library doesn't have it, draw Arimo. A family the library has is never
// aliased, the document keeps naming Arial, and chains (A → B → C) are followed.
fonts.setAliases({ Arial: 'Arimo', 'Times New Roman': 'Tinos' });

// Per style, or to a generic category's default.
fonts.setAliases([
{ from: 'Arial', to: 'Arimo' },
{ from: 'Garamond', bold: true, to: 'EB Garamond SemiBold' },
{ from: 'Brand Script', to: { category: 'script' } },
]);
// When a document asks for Arial and the library doesn't have it, draw Arimo. A family the library has is
// never aliased, the document keeps naming Arial, and chains (A → B → C) are followed.
fonts.SetAliases(new Dictionary<string, string> { ["Arial"] = "Arimo", ["Times New Roman"] = "Tinos" });

// Per style, or to a generic category's default.
fonts.SetAliases([
new Alias("Arial", "Arimo"),
new Alias("Garamond", "EB Garamond SemiBold", Bold: true),
new Alias("Brand Script", AliasTarget.ToCategory(GenericFamily.Script)),
]);

Setting aliases replaces the earlier ones, lays every open document out again, and asks your resolver again about families it had answered.

Draw-time replacements​

A replacement draws a family with another even when the family is installed: to draw a brand font in place of a document's, or to make every machine draw the same fonts. When the replacement's target isn't in the library, the document's own family draws, and the target is reported missing with by: 'original'.

// Always draw Comic Sans MS with the house font, even where Comic Sans MS is installed. The document is unchanged.
fonts.setReplacements({ 'Comic Sans MS': 'Inter' });
// Always draw Comic Sans MS with the house font, even where Comic Sans MS is installed. The document is unchanged.
fonts.SetReplacements(new Dictionary<string, string> { ["Comic Sans MS"] = "Inter" });

Generic defaults​

Generic defaults are opt-in. Set a family for any of five categories (serif, sans serif, monospace, script, decorative), and a missing family of that category draws with it. With none set, no family draws through a category.

A missing family's category comes from what the document says about it. Documents describe each font they use in their font table, and Twip reads only what that description states, never the family's name:

The description saysCategory
fixed pitch (w:pitch="fixed"), or a monospaced PANOSE proportionMonospace
w:family="roman"Serif
w:family="swiss"Sans serif
w:family="modern"Monospace
w:family="script"Script
w:family="decorative"Decorative
no class (auto): a Latin-text PANOSE with a sans serif styleSans serif
no class: a Latin-text PANOSE with any other serif styleSerif
no class: a hand-written or decorative PANOSE family kindScript, Decorative
nothing, or nothing that decidesnone: the general fallback draws

Fixed pitch wins over the class, so a family the table calls swiss but fixed-pitch is monospace.

// Opt-in: a missing family draws with the default of its category, which the document's font table gives it.
fonts.setGenericDefaults({ serif: 'Tinos', sansSerif: 'Arimo', monospace: 'Cousine', script: 'Dancing Script', decorative: 'Lobster' });

// Classify only through aliases to a category and resolver answers, not the font table.
fonts.setClassification({ fromDocument: false });

// {} turns generic defaults off again.
fonts.setGenericDefaults({});
// Opt-in: a missing family draws with the default of its category, which the document's font table gives it.
fonts.SetGenericDefaults(new GenericDefaults(Serif: "Tinos", SansSerif: "Arimo", Monospace: "Cousine", Script: "Dancing Script", Decorative: "Lobster"));

// Classify only through aliases to a category and resolver answers, not the font table.
fonts.SetClassification(fromDocument: false);

// new GenericDefaults() turns generic defaults off again.
fonts.SetGenericDefaults(new GenericDefaults());

With classification off, only an alias to a category or a resolver's category answer gives a family its category.

The general fallback and the last resort​

The general fallback draws any family nothing else resolves. When it isn't set, or isn't in the library, the first face added draws. An empty library draws text with the symbol font's boxes, so pages still lay out; with the symbol font off as well, text takes no space.

// The family for anything nothing else resolves. With null, the first face added draws.
fonts.setFallback('Arimo');
// The family for anything nothing else resolves. With null, the first face added draws.
fonts.SetFallback("Arimo");

Character fallback and the symbol font​

A character the run's font doesn't have (a symbol, CJK text, an emoji) is drawn from the first of your character-fallback families that has it, then from the symbol font. Twip searches no families of its own.

// Searched in order for a character the run's font doesn't have, then the symbol fallback.
fonts.setCharacterFallback(['Noto Sans Symbols 2', 'Noto Sans CJK JP', 'Noto Color Emoji']);
// Searched in order for a character the run's font doesn't have, then the symbol fallback.
fonts.SetCharacterFallback(["Noto Sans Symbols 2", "Noto Sans CJK JP", "Noto Color Emoji"]);

The symbol font is bundled so bullets and checkboxes draw in an empty library. Replace it with a font of yours (its first face draws), or turn it off, and characters no font has draw as their font's missing-glyph box and are reported. A font that holds no face is refused with invalidArgument, and the setting stays as it was.

// The bundled symbol font draws bullets and checkboxes no other font has. Replace it, or turn it off.
await fonts.setSymbolFallback('/fonts/MySymbols.ttf');
await fonts.setSymbolFallback('off');
await fonts.setSymbolFallback('bundled');
// The bundled symbol font draws bullets and checkboxes no other font has. Replace it, or turn it off.
await fonts.SetSymbolFallbackAsync(SymbolFallback.FromFile("fonts/MySymbols.ttf"));
await fonts.SetSymbolFallbackAsync(SymbolFallback.Off);
await fonts.SetSymbolFallbackAsync(SymbolFallback.Bundled);

Resolvers​

A resolver fetches fonts on demand. The library asks it once per family and style that a document uses and the library doesn't have. While it runs, the family is in state.fonts.pending and draws with a stand-in; when it answers, the document is laid out again. In .NET the resolver runs on the thread pool; in the browser it runs on the page, whichever thread the engine is on.

// Asked once per family and style the document uses and the library lacks. Return bytes, a URL, or null.
fonts.setResolver(async (request, signal) => {
const style = `${request.bold ? 'Bold' : ''}${request.italic ? 'Italic' : ''}` || 'Regular';
const response = await fetch(`/fonts/${encodeURIComponent(request.family)}-${style}.woff2`, { signal });
return response.ok ? new Uint8Array(await response.arrayBuffer()) : null;
});
// Asked once per family and style the document uses and the library lacks. Return the font, or null. It runs
// on the thread pool; an exception reports the family missing with the error.
fonts.SetResolver(async (request, ct) =>
{
var style = (request.Bold, request.Italic) switch
{
(true, true) => "BoldItalic",
(true, false) => "Bold",
(false, true) => "Italic",
_ => "Regular",
};
var response = await http.GetAsync($"https://fonts.example.com/{request.Family}-{style}.ttf", ct);
return response.IsSuccessStatusCode ? FontSource.FromBytes(await response.Content.ReadAsByteArrayAsync(ct)) : null;
});

A resolver can also decide how to draw a family instead of fetching it. The request carries the document's description of the family (description: its class, pitch, PANOSE and character set, each absent when the document doesn't state it) and the category that description gives (proposed), whether or not classification is on. Answer with:

AnswerWeb.NETThen
A fontbytes, a URL or a URL stringFontSource.FromBytes, FromUriadded; the family resolves if the font has it
Another family{ family }FontSource.FromFamilydrawn like an alias, for every style
A category{ category }FontSource.FromCategorydrawn with that category's default, for every style
Nothingnullnullreported missing
A failurethrow or rejectthrowreported missing, with the error
// Or decide how to draw it: another family, or a category's default. The request says what the document's font
// table states about the family (`description`) and the category that gives (`proposed`).
fonts.setResolver(async (request: FontRequest) => {
if (request.family === 'Corporate Sans') return { family: 'Inter' };
if (request.proposed) return { category: request.proposed };
return request.description?.pitch === 'fixed' ? { category: 'monospace' } : null;
});
// Or decide how to draw it: another family, or a category's default. The request says what the document's
// font table states about the family (Description) and the category that gives (Proposed).
fonts.SetResolver((request, _) => ValueTask.FromResult(request switch
{
{ Family: "Corporate Sans" } => FontSource.FromFamily("Inter"),
{ Proposed: { } category } => FontSource.FromCategory(category),
{ Description.Pitch: FontPitch.Fixed } => FontSource.FromCategory(GenericFamily.Monospace),
_ => null,
}));

Family and category answers hold until you set aliases or replacements again, which asks about those families anew.

Missing-font reports​

state.fonts (State.Fonts) and the fontsChanged event (FontsChanged) report what the document can't draw as it asks:

  • missing: each family and style that draws with a stand-in. It names the family, the style, the replacement and alias targets tried (tried), its category, the family that draws instead (drawnWith), and why (by): the original family because a replacement's target is missing, a generic default, the fallback, or the lastResort. A resolver's failure is in error.
  • pending: the same, for families a resolver is still fetching.
  • characters: characters no font has, by the family their runs name (up to 64 per family; truncated says there were more).

A family that draws through an alias or a replacement whose target the library has isn't missing.

const editor = await HeadlessEditor.create({ fonts });
editor.on('fontsChanged', ({ pending, missing, characters }) => {
for (const m of missing) {
const style = [m.bold && 'bold', m.italic && 'italic'].filter(Boolean).join(' ');
console.log(`${m.family} ${style}: drawn with ${m.drawnWith ?? 'nothing'} (${m.by})${m.error ? `, ${m.error}` : ''}`);
}
for (const c of characters) console.log(`no font has ${c.characters} (${c.family})`);
console.log(`${pending.length} still loading`);
});
console.log(editor.getState().fonts, await fonts.families());
await using var session = new EditorSession(new EditorSessionOptions(Fonts: fonts));
session.FontsChanged += (_, e) =>
{
foreach (var m in e.Missing)
Console.WriteLine($"{m.Family} {(m.Bold ? "bold " : "")}{(m.Italic ? "italic" : "")}: drawn with {m.DrawnWith ?? "nothing"} ({m.By}){(m.Error is { } error ? $", {error}" : "")}");
foreach (var c in e.Characters)
Console.WriteLine($"no font has {c.Characters} ({c.Family})");
Console.WriteLine($"{e.Pending.Count} still loading");
};
Console.WriteLine(string.Join(", ", await fonts.GetFamiliesAsync()));

The font-unresolved warning names each family the first time it goes missing in a document, with what draws it.

Rewriting a document's fonts​

replaceFont (ReplaceFontAsync) changes the document itself, so the saved file names the new family. It is one undo step, and returns how many places changed and how many it skipped.

  • Document scope, no style filter rewrites the text (each run's fonts, paragraph marks, symbol characters) in every story, and the tables below it: styles, document defaults, numbering levels, the theme's font slots and the font table.
  • Selection scope, or a bold/italic filter, rewrites only the text. A matching run whose family comes from a style or the theme gets the new family as its own.
  • Tracked changes: with tracking on, the text's changes are recorded as formatting revisions.
  • Locked content controls: text inside them is skipped and counted in skipped. A selection that includes one is refused.
  • A rewrite that changes nothing adds no undo step and leaves the document unmodified.
// Rewrite the document itself: every Calibri becomes Aptos, in the text, styles, theme, numbering and font table.
const { changed, skipped } = await editor.commands.replaceFont({ from: 'Calibri', to: 'Aptos' });
console.log(`${changed} places changed, ${skipped} in locked content controls`);

// Only the selected text, or only bold text.
await editor.commands.replaceFont({ from: 'Calibri', to: 'Aptos', scope: 'selection' });
await editor.commands.replaceFont({ from: 'Calibri', to: 'Aptos Display', bold: true });
// Rewrite the document itself: every Calibri becomes Aptos, in the text, styles, theme, numbering and font table.
var result = await session.Commands.ReplaceFontAsync("Calibri", "Aptos");
Console.WriteLine($"{result.Changed} places changed, {result.Skipped} in locked content controls");

// Only the selected text, or only bold text.
await session.Commands.ReplaceFontAsync("Calibri", "Aptos", ReplaceScope.Selection);
await session.Commands.ReplaceFontAsync("Calibri", "Aptos Display", bold: true);

Documents mostly use Calibri, Cambria, Arial, Times New Roman and Courier New. Where you can't ship those, alias them to their metric-compatible open stand-ins, which have the same widths and so the same line breaks: Carlito, Caladea, Arimo (or Liberation Sans), Tinos (or Liberation Serif) and Cousine (or Liberation Mono). Add freely licensed generic defaults for everything else. Copy this and add the fonts it names; Twip doesn't apply it for you.

// Metric-compatible open families for common office fonts: the same widths, so the same line and page breaks.
fonts.setAliases({
Calibri: 'Carlito',
'Calibri Light': 'Carlito',
Cambria: 'Caladea',
Arial: 'Arimo',
Helvetica: 'Arimo',
'Times New Roman': 'Tinos',
Times: 'Tinos',
'Courier New': 'Cousine',
Courier: 'Cousine',
});
fonts.setGenericDefaults({ serif: 'Tinos', sansSerif: 'Arimo', monospace: 'Cousine' });
fonts.setFallback('Arimo');
// Metric-compatible open families for common office fonts: the same widths, so the same line and page breaks.
fonts.SetAliases(new Dictionary<string, string>
{
["Calibri"] = "Carlito",
["Calibri Light"] = "Carlito",
["Cambria"] = "Caladea",
["Arial"] = "Arimo",
["Helvetica"] = "Arimo",
["Times New Roman"] = "Tinos",
["Times"] = "Tinos",
["Courier New"] = "Cousine",
["Courier"] = "Cousine",
});
fonts.SetGenericDefaults(new GenericDefaults(Serif: "Tinos", SansSerif: "Arimo", Monospace: "Cousine"));
fonts.SetFallback("Arimo");

Google Fonts through a resolver​

Twip doesn't contact any font service. To take families from Google Fonts, resolve them yourself:

// Google Fonts through a resolver: the css2 stylesheet for a family and style, then the font file it names.
fonts.setResolver(async ({ family, bold, italic }, signal) => {
const name = encodeURIComponent(family).replace(/%20/g, '+');
// Google answers a family it doesn't have with a 400 that has no CORS header, so the fetch rejects: not found.
const css = await fetch(`https://fonts.googleapis.com/css2?family=${name}:ital,wght@${italic ? 1 : 0},${bold ? 700 : 400}`, { signal }).catch(() => null);
if (!css?.ok) return null;
const url = /src:\s*url\(([^)]+)\)/.exec(await css.text())?.[1];
return url ?? null;
});
// Google Fonts through a resolver: the css2 stylesheet for a family and style (TTF for clients that send no user
// agent), then the font file it names.
fonts.SetResolver(async (request, ct) =>
{
var family = Uri.EscapeDataString(request.Family).Replace("%20", "+", StringComparison.Ordinal);
var css = $"https://fonts.googleapis.com/css2?family={family}:ital,wght@{(request.Italic ? 1 : 0)},{(request.Bold ? 700 : 400)}";
using var response = await http.GetAsync(css, ct);
if (!response.IsSuccessStatusCode) return null; // Google doesn't have this family or face
var url = Regex.Match(await response.Content.ReadAsStringAsync(ct), @"src:\s*url\(([^)]+)\)");
return url.Success ? FontSource.FromUri(new Uri(url.Groups[1].Value)) : null;
});

Migrating​

BeforeNow
useGoogleFonts() / UseGoogleFonts()a resolver: Google Fonts through a resolver
substitute(...) / Substitute(...), SubstitutionRulesetReplacements / SetReplacements, FontRule
the built-in substitutes (Calibri → Carlito, Aptos → Calibri, ...)your aliases: A recommended setup
the built-in fallback families (Segoe UI Symbol, Noto Sans, ...)setCharacterFallback / SetCharacterFallback
setDefault(family) / SetDefault(family)setFallback / SetFallback (null for none)
fonts.unresolved / Unresolved (family names)fonts.missing / Missing (per family and style, with what draws it)
FontLibrary::mark_unresolved (Rust)FontLibrary::answer(&request, FontAnswer::Missing)
resolver errors logged or ignoredMissingFont.error in the report
PdfFontSetOptions.Substitutions, DefaultFamilyReplacements, Fallback

PDF conversion​

Headless PDF conversion doesn't use a FontLibrary: it takes a font set (PdfFontSet in .NET, twip::pdf::FontSet in Rust) that is fixed once built, so many threads can share it. It takes the same settings, and its result reports the same missing families and characters. See PDF conversion.

Font files are licensed separately from Twip. Check that you may ship the fonts you add.