Customization

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} />;
}
loadFonts() optionUse
sources[].urlApplication-selected font URL.
sources[].familyFamily the bytes supply.
sources[].weightInteger from 1 through 1000.
sources[].stylenormal or italic.
sources[].hashOptional sha256: hash. Mismatched bytes are refused.
sources[].faceIndexCollection face index. Default 0.
cacheNameCache API bucket. Default docx-editor-fonts.
fetcherFetch implementation. Default global fetch.
maxFontBytesPer-source byte limit. Default is the engine hard limit.
signalCancels 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.

SourceUse
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.
FontResolverLoads approved faces after the document requests families.
Embedded DOCX fontsLoad 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 fieldUse
sourcesValidated bytes with family, weight, and style.
supportedFamiliesSelectable families. Listing performs no fetch.
substitutionsMaps a requested face to a supplied face.
defaultFontFamily and sizeHalfPoints for undeclared text. Default Calibri, 22.
languageBCP-47 tag for language-sensitive shaping.
epochIdentifies the font byte set.
maxFontBytesPer-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);
ChangeResult
New fontsCancels the previous resolver. Current faces paint until the new ones are ready.
New fonts that fail or supply nothing usableRemoves the previous host faces anyway. Text uses fallback measurement unless the document embeds faces. onFontError reports the failure.
undefinedRemoves 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>
  );
}
useFontFamily() memberMeaning
valueCurrent family. null for mixed values or no document.
optionsSorted, deduplicated configured and document families.
isEnabledWhether 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.

SourceDefaultTo wait
googleFonts({ cjk: true })BackgroundgoogleFonts({ cjk: { loading: 'wait' } })
cjkFonts()BackgroundcjkFonts({ loading: 'wait' })
Any other originWaitLeave 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/vue and @docx-editor.dev/core.
  • While background faces load, editor.fontMeasurement().resolving is true, for up to 10 seconds. Faces that arrive later still install.
  • A resolver can return large faces on its deferred field. It returns defaultFont, maxFontBytes, and language immediately.
  • 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.

BehaviorDetail
Changed maxFontBytes valueReact and Vue create another instance. Selection and undo history reset.
Same value in a new objectKeeps the instance.
Not a positive safe integer, or over 64 MiBcreateDocxEditor throws RangeError.
Face over the shaping limitUses 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.
  • onFontError reports 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 onFontError does 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.
  • fontShaping does not affect a custom measurer. Markdown rejects that combination.
  • For font collection rendering details, see DOCX feature support.

See also