Fonts
Load font bytes for DOCX editor layout, replace fonts in place, customize the font picker, and set loading limits.
Pass a font configuration through fonts. The editor measures text with font bytes, so CSS @font-face rules do not affect layout.
Load application fonts
Host your font files and load them with loadFonts(). Include each weight and style the document uses.
// contract-fonts.ts
import { loadFonts } from '@docx-editor.dev/core/editor';
export function loadContractFonts() {
return loadFonts({
sources: [
{
url: '/fonts/ContractSans-Regular.ttf',
family: 'Contract Sans',
weight: 400,
style: 'normal',
},
{
url: '/fonts/ContractSans-Bold.ttf',
family: 'Contract Sans',
weight: 700,
style: 'normal',
},
],
});
}loadFonts() returns admitted sources and typed failures. One failure does not discard other faces.
import { useEffect, useState } from 'react';
import { DocxEditor } from '@docx-editor.dev/react';
import { loadContractFonts } from './contract-fonts';
type Fonts = Awaited<ReturnType<typeof loadContractFonts>>;
export function FontEditor({ bytes }: { bytes: Uint8Array }) {
const [fonts, setFonts] = useState<Fonts>();
const [failed, setFailed] = useState(false);
useEffect(() => {
let disposed = false;
loadContractFonts().then(
(value) => {
if (disposed) return;
if (value.failures.length > 0) setFailed(true);
else setFonts(value);
},
() => !disposed && setFailed(true)
);
return () => {
disposed = true;
};
}, []);
if (failed) return <p role="alert">Fonts failed to load.</p>;
if (!fonts) return <p role="status">Loading fonts…</p>;
return <DocxEditor document={bytes} fonts={fonts} />;
}<script setup lang="ts">
import { onMounted, onUnmounted, ref, shallowRef } from 'vue';
import { DocxEditor } from '@docx-editor.dev/vue';
import { loadContractFonts } from './contract-fonts';
defineProps<{ bytes: Uint8Array }>();
const fonts = shallowRef<Awaited<ReturnType<typeof loadContractFonts>>>();
const failed = ref(false);
let disposed = false;
onMounted(() => {
loadContractFonts().then(
(value) => {
if (disposed) return;
if (value.failures.length > 0) failed.value = true;
else fonts.value = value;
},
() => {
if (!disposed) failed.value = true;
}
);
});
onUnmounted(() => {
disposed = true;
});
</script>
<template>
<p v-if="failed" role="alert">Fonts failed to load.</p>
<DocxEditor v-else-if="fonts" :document="bytes" :fonts="fonts" />
<p v-else role="status">Loading fonts…</p>
</template>loadFonts() option | Use |
|---|---|
sources[].url | Application-selected font URL. |
sources[].family | Family the bytes supply. |
sources[].weight | Integer from 1 through 1000. |
sources[].style | normal or italic. |
sources[].hash | Optional sha256: hash. Mismatched bytes are refused. |
sources[].faceIndex | Collection face index. Default 0. |
cacheName | Cache API bucket. Default docx-editor-fonts. |
fetcher | Fetch implementation. Default global fetch. |
maxFontBytes | Per-source byte limit. Default is the engine hard limit. |
signal | Cancels the request. The operation rejects with signal.reason. |
Failure reasons are networkError, httpError, hashMismatch, overLimit, emptyResponse, invalidRequest, and malformed. Cached entries are validated before use. For bytes you hold, createFontSource returns a source or a typed failure.
Choose a font source
fonts accepts a FontConfigurationFragment, a complete FontConfiguration, or a FontResolver. Combine origins with useFonts() or composeFontConfiguration.
import { useFonts } from '@docx-editor.dev/react';
import { packagedFonts } from '@docx-editor.dev/fonts';
import { googleFonts } from '@docx-editor.dev/fonts/google';
const local = packagedFonts();
const remote = googleFonts({ allow: ['Lato', 'Arvo', 'PT Serif'] });
export function useContractFonts() {
return useFonts(local, remote);
}In Vue, call useFonts() the same way in <script setup> and bind the result to :fonts.
| Source | Use |
|---|---|
packagedFonts() | Metric-compatible substitutes for common defaults. |
customFonts() | Your own hosted families. |
googleFonts({ allow }) | Pinned Google Fonts catalog. allow limits downloads. onFailure reports failed downloads. |
FontResolver | Loads approved faces after the document requests families. |
| Embedded DOCX fonts | Load automatically when usable. |
Earlier sources win for the same family, weight, and style. A supplied face wins over a substitution. For more, see Fonts and measurement.
| Configuration field | Use |
|---|---|
sources | Validated bytes with family, weight, and style. |
supportedFamilies | Selectable families. Listing performs no fetch. |
substitutions | Maps a requested face to a supplied face. |
defaultFont | Family and sizeHalfPoints for undeclared text. Default Calibri, 22. |
language | BCP-47 tag for language-sensitive shaping. |
epoch | Identifies the font byte set. |
maxFontBytes | Per-face admission limit. |
A FontResolver receives families, defaultFamily, and optional signal and resolvedFaces. It returns a configuration, a fragment, or undefined. Map family names to URLs through your own lookup, and pass signal to your fetch calls so cancellation stops network work.
Render Chinese, Japanese, and Korean text
Choose one East Asian source. If you list both, both download and the first one paints.
import { useFonts } from '@docx-editor.dev/react';
import { packagedFonts } from '@docx-editor.dev/fonts';
import { googleFonts } from '@docx-editor.dev/fonts/google';
import { cjkFonts } from '@docx-editor.dev/fonts-cjk/browser';
// Option 1: regional Noto Sans faces from Google Fonts, 4.6 to 8.5 MB each.
export function useGoogleCjkFonts() {
return useFonts(packagedFonts(), googleFonts({ cjk: true }));
}
// Option 2: one pan-CJK face, about 16 MB, from your origin.
export function useSelfHostedCjkFonts() {
return useFonts(packagedFonts(), googleFonts(), cjkFonts());
}Call one of these hooks in your editor component and pass the result to fonts.
Neither downloads anything for documents without East Asian families. For setup details, see Chinese, Japanese, and Korean text.
Replace fonts
A new fonts prop value calls setFonts(). The instance, document, selection, undo history, protection, and collaboration session stay. On a createDocxEditor instance, call it directly.
await editor.setFonts(nextFonts);
// Remove host-supplied faces when their permission expires.
await editor.setFonts(undefined);| Change | Result |
|---|---|
| New fonts | Cancels the previous resolver. Current faces paint until the new ones are ready. |
| New fonts that fail or supply nothing usable | Removes the previous host faces anyway. Text uses fallback measurement unless the document embeds faces. onFontError reports the failure. |
undefined | Removes host faces at once. |
Keep fonts stable across renders, because each new value resolves fonts again.
Customize the font picker
Rearrange Toolbar.FontFamily with its Trigger, Content, and Item parts, or build a picker with useFontFamily().
import { useFontFamily } from '@docx-editor.dev/react';
export function ContractFontPicker() {
const { value, options, isEnabled, setValue } = useFontFamily();
return (
<select
aria-label="Font family"
disabled={!isEnabled}
value={value ?? ''}
onChange={(event) => setValue(event.currentTarget.value)}
>
<option value="" disabled>
Mixed or default
</option>
{options.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
</select>
);
}<script setup lang="ts">
import { useFontFamily } from '@docx-editor.dev/vue';
const { value, options, isEnabled, setValue } = useFontFamily();
function onChange(event: Event) {
setValue((event.target as HTMLSelectElement).value);
}
</script>
<template>
<select aria-label="Font family" :disabled="!isEnabled" :value="value ?? ''" @change="onChange">
<option value="" disabled>Mixed or default</option>
<option v-for="option in options" :key="option" :value="option">
{{ option }}
</option>
</select>
</template>useFontFamily() member | Meaning |
|---|---|
value | Current family. null for mixed values or no document. |
options | Sorted, deduplicated configured and document families. |
isEnabled | Whether the engine allows the change. |
setValue(family) | Applies a permitted family change. |
The picker lists document, served, and standard families. An unserved standard family appears only if the browser detects it. A listed family may have no loaded bytes.
Configure loading and limits
Choose when large fonts load
A waiting origin delays the first paint of a large document (over about 512 KB of uncompressed content, so a smaller DOCX file can still wait) by up to 2 seconds. A background origin never delays it, so text can move later.
| Source | Default | To wait |
|---|---|---|
googleFonts({ cjk: true }) | Background | googleFonts({ cjk: { loading: 'wait' } }) |
cjkFonts() | Background | cjkFonts({ loading: 'wait' }) |
| Any other origin | Wait | Leave it unwrapped. |
To load any other origin in the background, wrap it in deferFonts():
import { deferFonts, useFonts, type FontOrigin } from '@docx-editor.dev/react';
import { packagedFonts } from '@docx-editor.dev/fonts';
export function useDocumentFonts(brandFonts: FontOrigin) {
return useFonts(packagedFonts(), deferFonts(brandFonts));
}deferFonts()is also exported from@docx-editor.dev/vueand@docx-editor.dev/core.- While background faces load,
editor.fontMeasurement().resolvingistrue, for up to 10 seconds. Faces that arrive later still install. - A resolver can return large faces on its
deferredfield. It returnsdefaultFont,maxFontBytes, andlanguageimmediately. - Exports wait for every face.
Shaping limits
Text shaping uses up to 16 MiB per face by default. For larger admitted faces, set fontShaping: { maxFontBytes } on the editor, up to 64 MiB.
| Behavior | Detail |
|---|---|
Changed maxFontBytes value | React and Vue create another instance. Selection and undo history reset. |
| Same value in a new object | Keeps the instance. |
| Not a positive safe integer, or over 64 MiB | createDocxEditor throws RangeError. |
| Face over the shaping limit | Uses fallback measurement. onFontError reports overLimit with a HarfBuzzShapingError cause, code fontOverLimit, and a request with the face's family, weight, and style. |
The type is FontShapingOptions, from @docx-editor.dev/core and @docx-editor.dev/core/editor. createLayoutShaping takes it as its third argument, and font-backed Core, Markdown, and PDF exports accept it. Collaboration peers need the same bytes and limit.
Limits
- Document font names never authorize remote requests.
onFontErrorreports initialization failures with the original cause. Each oversized face reports once per resolution.- Replacing the document or destroying the editor discards errors from older loads.
- A throwing
onFontErrordoes not interrupt fallback or suppress the error event. - Missing coverage can change line breaks and pagination. A font command can succeed before its bytes arrive.
fontShapingdoes not affect a custom measurer. Markdown rejects that combination.- For font collection rendering details, see DOCX feature support.