Overview
Default behaviour and the fonts option
The fonts load option is an ordered list of font sources. With no sources,
the library requests no fonts from any network host and the canvas uses the fonts installed
on the viewer's machine. Fonts embedded in a document and installed fonts with the authored
name always come first; sources only fill in families the host does not have.
A FontSource is opaque. Create every entry with one of the factories:
googleFonts(), fontCssApi(), fontCss(),
fontFiles() or fontResolver(), in the page that loads the document.
Its contents are not part of the API. A copy of a source (spread, structuredClone,
JSON) or a hand-written object throws a TypeError. Every factory validates its
input when it is called, before any load. A source is guaranteed to be accepted by the
load() and viewers of the same library copy that created it; if a page loads two
copies of the library, passing one copy's source to the other is best effort only.
The factories, officeFontSubstitutions and googleFontsSubstitutions
are exported from @silurus/ooxml and from the @silurus/ooxml/docx,
@silurus/ooxml/xlsx and @silurus/ooxml/pptx entries; they are the
same objects in every entry. fonts works the same way for DOCX, XLSX and PPTX,
on every engine load() and every viewer, in mode: 'main' and
mode: 'worker'.
import { DocxViewer, googleFonts } from '@silurus/ooxml/docx';
const viewer = new DocxViewer(canvas, { fonts: [googleFonts()] });
await viewer.load(await file.arrayBuffer());Sources load only what the document needs: the families it paints that the host lacks,
and normally only the unicode-range subsets that intersect its painted characters.
A failing source never rejects load(); the affected families keep their host
fallback and a console.warn names them.
Use case 1
Google Fonts
googleFonts() requests stylesheets from https://fonts.googleapis.com
with the CSS2 API (/css2?family=…&display=swap). It asks only for the families
in its catalog (the Office stand-ins such as Carlito and Caladea, the Noto script families and
a few popular web fonts) plus the families you add with additionalFamilies. The catalog
and the default substitution list are the current implementation's contents and may change in a
minor release: name the families and substitutions your application depends on yourself.
additionalFamiliesmaps a Google Fonts family name to its CSS2 axis query, sent afterfamily=<name>:. Request only axes the family has: CSS2 answers an unknown axis with HTTP 400, which fails the family. A key that names a catalog family (case-insensitively) replaces that family's query.substitutionsdefaults togoogleFontsSubstitutions: the Office substitutions followed by Google's names for the native Noto CJK families (Noto Sans CJK JP→Noto Sans JP, …). Passingsubstitutionsreplaces that list; spread it to extend it. A substitution'susemust be a family the preset requests.additionalFamiliesadds to the catalog. It is not thefamiliesoption offontCssApi(), which is an allow-list that replaces everything.
import { googleFonts, googleFontsSubstitutions } from '@silurus/ooxml';
fonts: [googleFonts({
// Google Fonts family (Google's spelling) → CSS2 axis query.
additionalFamilies: { Inter: 'wght@400;700', 'Source Serif 4': 'ital,wght@0,400;0,700;1,400;1,700' },
// Replaces the default list; spread it to extend it.
substitutions: [...googleFontsSubstitutions, { for: 'Corporate Sans', use: 'Inter' }],
})]With a Content Security Policy, allow the stylesheet host in connect-src and the
font file host in both connect-src and font-src. The library fetches
the stylesheets and the font files itself with fetch(); it does not inject a
<link>.
connect-src https://fonts.googleapis.com https://fonts.gstatic.com;
font-src https://fonts.gstatic.com;Google receives the end user's IP address and User-Agent with each request, which may have privacy implications for your application.
Use case 2
Proxy or mirror
A Google-compatible origin: googleFonts({ baseUrl })
In 0.90, baseUrl must be an origin: a scheme, host and optional port
(http: or https:); one trailing slash is accepted. A path, query or user
name throws a TypeError that names baseUrl when googleFonts()
is called. A later release may accept a path prefix; until then, use the proxy example below. The requests keep the Google
CSS2 path and query, so the origin must serve that API, and no stylesheet request goes to
fonts.googleapis.com.
fonts: [googleFonts({ baseUrl: 'https://fonts.googleapis.cn' })]
fonts: [googleFonts({ baseUrl: 'https://fonts.internal.example:8443' })]baseUrl sets only where the stylesheet requests start:
- Redirects are followed. The stylesheet is read from the final URL, which can be on another origin.
- Font file URLs come from the returned CSS and are used as given. Relative URLs resolve
against the stylesheet's final URL; absolute URLs can point anywhere, for example at
fonts.gstatic.comif the mirror passes Google's CSS through unchanged.
For network isolation, the mirror must control its redirects and rewrite the font URLs it
returns to hosts you allow. Your CSP (connect-src and font-src) is the
enforcement point. A failing mirror keeps the host fonts; the library never retries it against
the public Google origin.
A path-prefixed proxy: fontCssApi()
A proxy that serves the CSS2 API under a path prefix is not an origin, so baseUrl
cannot express it in 0.90. Use fontCssApi() with the full URL template, the families the
proxy serves with their CSS2 axes, and the default Google substitutions. List every family the
proxy should serve: CSS2 rejects an axis query a family does not have, and without
families every demanded family is requested.
import { fontCssApi, googleFontsSubstitutions } from '@silurus/ooxml';
const TEXT = 'ital,wght@0,400;0,700;1,400;1,700';
fonts: [fontCssApi({
urlTemplate: 'https://proxy.example/google-fonts/css2?family={family}:{query}&display=swap',
families: { Carlito: TEXT, Caladea: TEXT, 'Noto Sans JP': 'wght@400;700' },
substitutions: googleFontsSubstitutions,
})]An authenticated or private proxy: fontResolver()
When requests need tokens, signed URLs or your own network client, answer font demand with a function. It runs in the page that created it; in worker mode the worker asks the page to run it, so tokens and clients stay in your application. See the resolver contract.
import { fontResolver, googleFonts, officeFontSubstitutions } from '@silurus/ooxml';
const privateFonts = fontResolver(async (demand, { signal }) => {
const response = await fetch('/api/fonts/resolve', {
method: 'POST',
body: JSON.stringify({ authoredFamilies: demand.authoredFamilies, fallbackFamilies: demand.fallbackFamilies }),
signal,
});
return response.json(); // FontFaceDeclaration[]: { family, url | data, … }
}, { substitutions: officeFontSubstitutions });
fonts: [privateFonts, googleFonts({ baseUrl: 'https://fonts.internal.example' })]Use case 3
Third-party font providers
| Provider shape | Factory | Notes |
|---|---|---|
| CSS API with one request per family | fontCssApi() | Absolute http(s) urlTemplate with {family} (percent-encoded, + for spaces) and optional {query}, filled from query or the families allow-list, never from document content. |
| Static kit stylesheet: an Adobe Fonts web project, Bunny Fonts, a Fontsource CDN stylesheet, a Monotype or Morisawa static kit | fontCss() | One stylesheet describing any number of families. Only @font-face rules with url() sources are read; local(), @import and everything else are ignored. |
| Self-hosted font files | fontFiles() | Each face has exactly one of url (http(s), blob: or data:) or data (a non-empty ArrayBuffer), plus standard @font-face descriptors. |
| Authenticated or private service | fontResolver() | Your function returns FontFaceDeclaration objects for the families asked for. |
CSS API per family
query is required when the template has {query}, unless every
families entry supplies its own. With families, only those families are
requested. Without it, every demanded family is requested, and an error response (such as an
HTTP 400 for a family the API does not serve) fails that family. List the served families when
the source is not the last in the chain.
import { fontCssApi, officeFontSubstitutions } from '@silurus/ooxml';
fonts: [fontCssApi({
urlTemplate: 'https://fonts.example/css?family={family}:{query}',
query: '400,700',
families: { 'Open Sans': true, Lato: '400' },
substitutions: officeFontSubstitutions,
})]Static kit CSS
Documents that use the same configuration share one stylesheet fetch while any of them is open. No script in the page runs.
import { fontCss, officeFontSubstitutions } from '@silurus/ooxml';
fonts: [fontCss({ url: '/fonts/office.css', substitutions: officeFontSubstitutions })]Self-hosted files
weight, style, stretch and unicodeRange take
standard CSS @font-face descriptor values. ArrayBuffer views,
SharedArrayBuffers and resizable buffers are rejected. Relative URLs in
fontFiles() and fontCss() resolve against the page's base URL when the
factory is called, so build these sources on the page, not in a worker.
import { fontFiles, officeFontSubstitutions } from '@silurus/ooxml';
fonts: [fontFiles({
faces: [
{ family: 'Carlito', url: '/fonts/Carlito-Regular.woff2', weight: '400' },
{ family: 'Carlito', url: '/fonts/Carlito-Bold.woff2', weight: '700' },
{ family: 'Noto Sans JP', url: '/fonts/NotoSansJP-kana.woff2', unicodeRange: 'U+3000-30FF' },
{ family: 'Brand Display', data: brandDisplayBytes }, // an ArrayBuffer
],
substitutions: officeFontSubstitutions,
})]Not supported: per-text dynamic subsetting
Services that subset fonts per page text at run time (for example TypeSquare, FONTPLUS or
Adobe Fonts dynamic CJK kits) are not supported. They generate faces for the text their script
sees in the page, which a canvas viewer does not expose to them, and fontResolver()
does not see the text either. Serve static faces for those families with
unicode-range subsets, from a stylesheet, fontFiles() or a resolver; the
library then fetches only the subsets the document paints.
Licences and tracking
The library ships no font binaries and only reads @font-face url()
rules. It does not run a provider's embed code (<script> or JavaScript kits),
and it sends no usage or page-view tracking. Loading the embed code, any usage reporting the
provider requires, and the font licences, including whether a licence covers rendering in a
document viewer, are your application's responsibility.
fontResolver()
Resolver contract
This contract is settled for 0.90. Later versions may add fields to demand and
context; they will not remove or change these.
type FontResolver = (
demand: FontDemand,
context: FontResolverContext,
) =>
| readonly (Omit<FontFaceDeclaration, 'weight'> & { readonly weight?: string | number })[]
| Promise<readonly (Omit<FontFaceDeclaration, 'weight'> & { readonly weight?: string | number })[]>;
interface FontDemand {
readonly authoredFamilies: readonly string[]; // authored families the host lacks
readonly fallbackFamilies: readonly string[]; // library script fallbacks, e.g. Noto CJK
}
interface FontResolverContext {
readonly signal: AbortSignal;
}
interface FontFaceDeclaration {
readonly family: string;
readonly url?: string; // absolute http(s), blob: or data: URL
readonly data?: ArrayBuffer; // or owned font bytes (exactly one of url / data)
readonly weight?: string;
readonly style?: string;
readonly stretch?: string;
readonly unicodeRange?: string;
}demand.authoredFamiliesholds the authored families the host does not have and that no earlier call answered.demand.fallbackFamiliesholds the library's script fallback families for the text, such as Noto families for CJK.demandcarries family names only, never document text.- Answer each family the way an
@font-facestylesheet declares it: every face you have for it (all weights, styles andunicode-rangesubsets), or nothing. Withsubstitutions, a family may also be answered with faces of its substitute'susefamily. A family you do not answer goes to the next source. - A family is resolved once per document, so a face you leave out is not asked for again. The renderer picks the weight and style of each run.
- Returned URLs must be absolute.
http(s)andblob:faces are fetched by the library in the page, withcredentials: 'same-origin', only for theunicode-rangesubsets the document paints, in both modes. The worker never fetches them, so cookies, HTTP authentication and Referer checks see the page.datafaces anddata:URLs are used as returned. - A returned object is checked more leniently than
fontFiles()input, so one service can answer several library versions: properties the library does not know are ignored, andweightmay be a number from 1 to 1000.fontFiles()stays strict: an unknown property or a numericweightthrows aTypeError. - Send both
authoredFamiliesandfallbackFamiliesto your service: a resolver that reads onlyauthoredFamiliesnever serves the fallback families. - A
databuffer belongs to the library once returned. Do not modify it; in worker mode the worker receives a copy and your buffer is not detached.
Sharing and abort
Documents that need the same families from the same function at the same time share one call.
signal is aborted only when no document is waiting for that call any more: every
document sharing it was destroyed or reached its resolution deadline, or, in worker mode, the
worker cancelled the request. Destroying one of several documents that share a call does not abort it.
Errors
If the answer is not an array or contains a malformed declaration, every family of that call
keeps its host fallback and a console.warn reports the problem. If the function
throws, the same happens and the warning includes the error message. More than 2,048
declarations or a face over 30 MiB fails the call's families the same way. None of these
rejects the load.
Chaining
Source order
Sources are consulted per family, in option order:
- Each source tries the family itself, then the
usefamily of each of its matchingsubstitutions. - The first source that has a face for the family claims it. Later sources are never consulted for that family.
- A source that does not serve the family passes it on: a family outside a
fontCssApiallow-list, missing from a loaded stylesheet or file list, or not answered by a resolver. - A source that tries a family and fails makes the family final, with no retry elsewhere:
an unreachable or empty stylesheet, an HTTP error, a resolver error or the resolution deadline.
A
fontCssstylesheet that fails to load fails every family it is asked for. - A face that is claimed but fails to load keeps its host fallback. It does not re-enter the chain.
There is no strict mode and no callback. Failures are not cached, so a document opened later retries the same source. Source faces belong to the document that loaded them; two open documents never paint with each other's faces.
Paint priority
- A font embedded in the document.
- An installed face with the authored name. Installed families are never requested from a source.
- A source face for the authored family.
- A source face for a declared substitute.
- The host's fallback chain.
Substitutions
Office font substitutions
officeFontSubstitutions is the library's list of openly licensed stand-ins for
Office faces: Calibri → Carlito, Cambria → Caladea, Franklin Gothic Book and Franklin Gothic
Medium → Libre Franklin, and several Arabic faces → Noto Naskh Arabic or Noto Sans Arabic, for
Arabic text only. Any source can use it, or a list of your own, through substitutions.
import { officeFontSubstitutions } from '@silurus/ooxml';
substitutions: [...officeFontSubstitutions, { for: 'Corporate Sans', use: 'Inter' }]An entry is { for, use, script? }: for is the authored family,
matched case-insensitively; use is the family the source serves; the optional
script: 'arabic' limits the substitution to Arabic text; its type,
FontSubstituteScript, is exported from every entry. The renderers use a substitution
only when its face actually loaded. googleFonts() already includes
officeFontSubstitutions. The entries of both lists are the current implementation's
and may change in a minor release.
Network
CORS, credentials and CSP
- Fonts from another origin need CORS headers (
Access-Control-Allow-Origin) on stylesheets and font files. fontCssApi(),fontCss()andfontFiles()takecredentials:'same-origin'(the default, credentials to the same origin only, as CSS font loading does) or'omit'(no cookies or HTTP authentication at all).'include'and custom headers are not supported.googleFonts()takes nocredentials.- The library fetches font files itself (
fetch(), CORS mode) when the text first needs them, so that layout can read each face's own line metrics. A subset is fetched only when the text needs it, or when itsunicode-rangeoverlaps one that is needed. - Cookies are never sent to another origin. For an authenticated service on another origin,
use
fontResolverand returndatabytes or a signed URL. - A hosted source receives the end user's IP address and User-Agent.
Content Security Policy
- Stylesheet origins (
googleFonts,fontCssApi,fontCss) needconnect-src. - Font file origins need
font-srcand, because the library downloads them,connect-srcas well. That covers every font file ofgoogleFonts(),fontCssApi(),fontCss()andfontFiles()urlfaces, and every resolver URL. - Add
data:orblob:tofont-srcwhen you use those URLs.databuffers are not fetched and need no entry. - A mirror uses its own stylesheet and font file origins in place of Google's.
Privacy
Information sent to a font host
- A hosted source receives the end user's IP address and User-Agent with each request.
- Normally only the
unicode-rangesubsets that intersect the painted text are fetched (plus any subset whose range overlaps one of those), so the set of requested subset files reveals approximately which character ranges the document uses. This is coarse: no order, no counts and no text. With finely sliced CJK families it can still hint at the content. Ordinary web pages that use CSSunicode-rangehave the same property. fontResolverreceives family names only, never document text.- When some content cannot be demanded precisely (for example metafile pictures or equations), or the painted text has more than 65,536 distinct characters, the document requests every subset of the families concerned.
To keep these requests on infrastructure you control, self-host the fonts: fontFiles() or fontCss() on your own
origin, or a proxy that you control.
Timing and limits
Deadlines and fixed limits
The numbers in this section (deadlines, parallel downloads, size and count limits) are the
values the current implementation uses. They are documented so that you can size a deployment,
not as API: a minor release may change them. Do not build logic on the exact values; read
error.violation for the limit that applied.
A font load step runs each time a document needs new fonts or characters: for example once per DOCX document, once per PPTX slide that adds them, and once per XLSX workbook plus once per sheet that adds them. Layout waits for the step. Each step has two phases, each with its own 15 s deadline:
- Resolution walks the sources in order. One deadline covers the whole walk, so a slow first source leaves less time for the next. Families still unresolved when it expires keep their host fallback.
- Face loading fetches the faces the library downloads and waits for them to load. Faces not loaded when it expires keep their host fallback for that step.
A step therefore normally takes at most about 30 s. In worker mode the page owns a resolver's
deadline, and the worker adopts the page's answer even when it arrives after the worker's own
deadline; the faces it delivers then get a fresh face-loading deadline of their own. In DOCX, measuring a face whose metric tables
cannot be read waits at most another 15 s. In worker mode the worker waits silently while a
resolver runs, so a slow resolver combined with a short workerTimeoutMs can make the
load time out.
Font sources are application configuration, so they have fixed limits that are not part of
resourceLimits:
| Limit | Current value |
|---|---|
| Stylesheet size | 1 MiB per stylesheet |
| Declarations | 2,048 per document |
| Requested families | 256 per document |
| One face (data, the decoded body of a data: URL, or a font file the library downloads) | 30 MiB |
| Retained data bytes | 256 MiB per realm, across open documents |
| URL length (non-data: URLs and composed fontCssApi requests) | 8 KiB |
A limit that can be checked up front makes the factory throw an OoxmlError with
code === 'font-source-limit'; error.violation holds
{ resource: 'font-source', quota, metric, limit, observed }. quota and
metric are open-ended strings: a later release may report values this one does not
know, so give a switch over them a default branch. A limit reached
while a document loads never rejects load() or a later slide or sheet: only the
families concerned fail, with a console.warn, and the rest of the document loads.
Migration
Migration from useGoogleFonts
Version 0.90 replaces the boolean useGoogleFonts option with fonts.
Migration is required only if you pass useGoogleFonts.
| 0.89 | 0.90 |
|---|---|
useGoogleFonts: true | fonts: [googleFonts()] |
useGoogleFonts: false | omit the option |
In 0.90 the alias still works: useGoogleFonts: true without fonts becomes
fonts: [googleFonts()] and sends the same stylesheet requests, with a deprecation
warning printed once per JavaScript realm. useGoogleFonts: false does nothing but
still warns. When fonts is also given, fonts wins: useGoogleFonts
adds nothing to it and still warns, and nothing is thrown. From 0.91.0 the option is ignored with the same warning: no web fonts are
loaded until you migrate, but passing it never throws.