Search Docs
Loading...
Skip to content

Customize Fonts

Apply custom fonts, preserve requested font identities and verify text rendering in automated CE.SDK workflows.

10 mins
estimated time
Download
StackBlitz
GitHub

A concrete typeface describes a family and its available font files. A font request preserves the intended family and cut while the engine resolves the file. The runnable Add Text example demonstrates both approaches without an editor UI.

This guide covers font-file info, concrete font definitions, registered font sources, stored font requests, custom providers and rendering diagnostics.

Initialize the headless engine with the asset base URL supplied by the example runner. Keep its lifetime inside a try/finally block.

// Initialize CE.SDK engine in headless mode
const engine = await CreativeEngine.init({
baseURL: process.env.IMGLY_LOCAL_ASSETS_URL
// license: process.env.CESDK_LICENSE, // Optional (trial mode available)
});

Read the Font Info#

When you receive an uploaded font file, use engine.editor.getFontInfo() to read its names, weight and style. It takes the URI of a TTF, OTF, WOFF or WOFF2 file and resolves to a FontInfo object:

const fontUri =
'https://cdn.img.ly/assets/v2/ly.img.typeface/fonts/Roboto/Roboto-BoldItalic.ttf';
const info = await engine.editor.getFontInfo(fontUri);
console.log('Family:', info.family);
console.log('Subfamily:', info.subFamily);
console.log('Weight:', info.weight, info.fontWeight);
console.log('Style:', info.style);
console.log('Variable:', info.isVariable, info.variationAxes);
  • family is the typographic family name, such as Roboto. The legacy family name is in legacyFamily.
  • subFamily is the variant name, such as Bold Italic.
  • weight is the numeric weight class from 1 to 1000. fontWeight is the named weight that is closest to it, such as bold.
  • style is italic when the font is marked italic or oblique, otherwise normal.
  • postScriptName is the PostScript name of the font file.

For a variable font, isVariable is true and variationAxes lists each axis with its tag, minValue, defaultValue and maxValue. The other fields describe the default instance of the font. A readable file that is not a font rejects with EDITOR.FONT_INFO_EXTRACT_FAILED; an unreachable URI rejects with EDITOR.FONT_LOAD_FAILED.

Register the Font on a Typeface Source#

Build the typeface from the font info without a separate font parser. info.family becomes the typeface name, and subFamily, fontWeight and style fill the font entry. Add the typeface to a local asset source with engine.asset.addLocalSource() and engine.asset.addAssetToSource():

const typeface = {
name: info.family,
fonts: [
{
uri: fontUri,
subFamily: info.subFamily,
weight: info.fontWeight,
style: info.style
}
]
};
const sourceId = 'my-custom-typefaces';
engine.asset.addLocalSource(sourceId);
await engine.asset.addAssetToSource(sourceId, {
id: fontUri,
label: { en: info.family },
payload: { typeface }
});

The asset payload must carry the typeface in payload.typeface. The example uses the font file URI as the asset ID, so each file gets its own asset. The family becomes the label. Read each file of a family and add one font entry for each file to provide multiple weights and styles.

The font registration example shows this flow from reading a font file through registration, application and PNG export. The sections below use the Add Text example to apply a known typeface and preserve its requested identity.

Define and Apply a Concrete Font#

Use setFont() when you already know the file and typeface to apply. The definition lists each cut’s URI, subfamily, weight and style. The call replaces the entire block’s font and resets existing formatting.

// Apply a custom font to the title
// Font URIs point to hosted font files (TTF, OTF, WOFF, WOFF2)
const fontUri =
'https://cdn.img.ly/packages/imgly/cesdk-js/latest/assets/extensions/ly.img.cesdk.fonts/fonts/Caveat/Caveat-Bold.ttf';
const typeface = {
name: 'Caveat',
fonts: [
{
uri: fontUri,
subFamily: 'Bold',
weight: 'bold' as const,
style: 'normal' as const
}
]
};
engine.block.setFont(titleBlock, fontUri, typeface);
// Set font size (80pt for visibility)
engine.block.setTextFontSize(titleBlock, fontSize);

Use setTypeface() to change a family while preserving compatible formatting, including on a text range. getTypeface() reads the base definition; getTypefaces() reads the unique definitions in a range. These concrete APIs remain available alongside font requests.

Saved Content and Reader Compatibility#

The first concrete typeface definition for a family keeps the family name as its asset ID. If another definition uses that name with different font files or cuts, the engine saves it under a separate ID. Font requests also use their own identity keys. This applies to scenes, archives and saved blocks.

text/typeface can hold an ID that is not the family name. Read the name with block.getTypeface(id).name.

Earlier engines can render text from its stored font files, but cannot read a typeface or change its weight and style when the saved ID differs from the family name. Content with one concrete definition per family and no font requests stays editable in earlier engines.

Upgrade engines that must edit content with these separate identities. The updated reader still accepts older content. Keep original files before re-saving content that older applications must continue to edit.

Change the Fonts of a Registered Typeface#

When a font family changes, register its typeface again in your local asset source: remove the old asset, then add one with the current fonts. A typeface counts as registered again when it has the same name and at least one of the same font files.

A weight or style that the new typeface no longer has stays in the scene while text uses it, so that text keeps its look. Once no text uses it, the scene drops it, the font style menu stops offering it, and saved scenes no longer store it. To move text off a removed weight, set an available weight or style on that text.

A typeface with the same name but other font files, such as one that a template brings, keeps all its fonts.

Register a Typeface Source#

Register the definition in a local asset source so the engine can resolve font requests without an application provider. Each asset carries the typeface in payload.typeface.

const sourceId = 'brand-typefaces';
const assetId = 'brand-bold';
engine.asset.addLocalSource(sourceId);
await engine.asset.addAssetToSource(sourceId, {
id: assetId,
payload: { typeface }
});

The example pins its request to this source and asset. You can leave those identifiers out when the engine should search its registered local sources by family.

Preserve Requested Font Identity#

Set the desired family and cut, await resource resolution and read the stored request back. The request remains in the scene when its font is unavailable on another host.

const font = typeface.fonts[0];
engine.block.setFontRequest(titleBlock, {
family: typeface.name,
subFamily: font.subFamily,
weight: font.weight,
style: font.style,
assetSourceId: sourceId,
assetId
});
await engine.block.forceLoadResources([titleBlock]);
console.log('Stored requests:', engine.block.getFontRequests(titleBlock));

A font request preserves the intended family, cut, weight, style and optional asset identity through scene and archive round trips, even when that font is unavailable. setFontRequest() stores this identity and starts asynchronous resolution. getFontRequests() returns the unique stored requests in source order, rather than the fonts currently used for rendering.

The request fields below use TypeScript names. Swift uses assetSourceID and assetID for the asset identifiers.

Field Purpose and default
family Required, nonempty family name.
subFamily Optional cut name; defaults to an empty string.
weight Requested weight; defaults to normal.
style Requested style; defaults to normal.
postScriptName Optional exact identity checked against the loaded font’s PostScript name.
assetSourceId Optional source identifier that limits asset lookup.
assetId Optional asset identifier within that source; requires assetSourceId.

Returned requests include the default subfamily, weight and style. Supplied optional identifiers must be nonempty.

Calling the setter without a range replaces the request for the whole block, even when text is selected. Calling the getter without a range reads the current selection, or the whole text when there is no selection. Explicit ranges follow the platform’s editable-text convention. These ranges can differ from the rendered UTF-16 ranges returned by diagnostics after case conversion or template substitution.

By default, the engine searches registered local asset sources for matching typeface definitions, reading at most 100 pages of each source. Identical requests share a pending lookup. Other sources are queried only when the request names an assetSourceId; an assetId selects one asset directly. To retry unresolved requests after registering a source, call editor.setTypefaceResolver() again. Applications with an external font catalog can also install editor.setTypefaceResolver(). The provider returns the concrete typeface and chosen font, or no result when unavailable. Configure it on each engine before loading a scene that needs it; the callback itself is not saved in the scene.

When the provider returns no result, throws or rejects, the engine uses the default font, and the request reports substituted. It reports unresolved only when the default font cannot load either. Replacing the provider starts resolution again; completions from replaced providers, superseded requests or disposed engines are ignored. Removing the provider restores registered-source resolution.

Await block.forceLoadResources() when subsequent work needs settled font resources. A new request or provider replacement can move a ready text block back to pending. Block-state subscriptions let your application observe readiness changes; read the current state when notified. Resource failure rejects the resource-loading call and can still leave a fallback layout to inspect.

getTextRenderDiagnostics() retains the stored request alongside the actual loaded font and effective size. A fallback does not replace the stored identity, and substitution can change line breaks and dimensions. A resolved request alone does not guarantee that every glyph is present.

Existing setFont() and setTypeface() calls continue to apply concrete font choices and clear requests for the affected text. Use them when you already have the concrete definition. Use a font request when the design should retain its intended identity while availability changes.

Supply an Application Font Provider#

Install a provider when your application resolves fonts from its own catalog. A provider can return its result immediately or asynchronously. The example returns its known typeface and font, then restores registered-source resolution.

const unsubscribe = engine.block.onStateChanged([titleBlock], (blocks) => {
for (const block of blocks) {
console.log('Font resource state:', engine.block.getState(block));
}
});
engine.editor.setTypefaceResolver(async (request) => {
if (request.family !== typeface.name) return undefined;
return { typeface, font };
});
try {
await engine.block.forceLoadResources([titleBlock]);
} finally {
engine.editor.setTypefaceResolver(undefined);
unsubscribe();
}

Use engine.block.onStateChanged() to observe the affected blocks and read their current state with getState(). A provider replacement can change a ready block to pending while the replacement resolves. Keep the returned unsubscribe function and call it when you stop observing. Await forceLoadResources() before work that requires settled resources.

Verify Text Rendering#

Inspect the current font runs and missing glyphs before exporting. The layout result reports the full required height and clipped lines without temporarily resizing the block.

await engine.block.forceLoadResources([titleBlock]);
const diagnostics = engine.block.getTextRenderDiagnostics(titleBlock);
const substitutedRuns = diagnostics.fontUsage.runs.filter(
(run) => run.status === 'substituted'
);
if (diagnostics.layout) {
console.log({
substitutedRuns,
missingGlyphRanges: diagnostics.missingGlyphRanges,
overshoot: diagnostics.layout.overshoot,
totalLineCount: diagnostics.layout.totalLineCount,
visibleLineCount: diagnostics.layout.visibleLineCount,
clippedLineCount: diagnostics.layout.clippedLineCount,
requiredHeight: diagnostics.layout.requiredHeight,
fontScale: diagnostics.layout.fontScale,
effectiveFontSizes: diagnostics.fontUsage.runs.map(
(run) => run.effectiveFontSize
)
});
} else {
console.log('Layout unavailable', diagnostics.fontUsage.state);
}

The call updates pending layout and returns a snapshot without waiting for font downloads. Call it again after resources finish loading.

fontUsage contains the rendered text, its block state, and font runs. Each run names the requested font file and the loaded font file, when available.

Run status Meaning
resolved The requested font loaded for the run.
substituted A different font loaded, including fallback or emoji fonts.
unresolved No usable font loaded for the run.

Each run’s effectiveFontSize reports the shaped size in the scene’s font unit. It includes automatic fitting and superscript or subscript scaling.

The block state separately reports resource loading or failure. A failed font can produce a current fallback layout. Pending resources produce no runs or layout. If no current shape exists after a loading failure, the snapshot omits stale text and measurements.

A resolved run does not guarantee that every glyph is available. These diagnostics describe shaped text; they do not confirm that a frame was drawn or exported.

All ranges use half-open UTF-16 offsets into fontUsage.text, after case conversion and template substitution. Font runs return from and exclusive to values on every platform. Missing-glyph ranges use the same endpoints; Swift represents these ranges as Range<Int>. These offsets can differ from offsets used to edit the original text.

missingGlyphRanges identifies glyphs that remain missing after fallback. Ignored controls and trailing whitespace do not count as missing glyphs. This field remains available for curved text.

When present, layout contains:

  • totalLineCount: All laid-out lines, including hidden lines.
  • visibleLineCount: Lines visible with the block’s clipping configuration, independent of temporary editing visibility.
  • clippedLineCount: Lines hidden by that clipping configuration.
  • requiredHeight: The full Auto-height result at the current effective sizes, even when no line fits the frame.
  • fontScale: The common automatic fitting scale applied to authored font sizes.
  • overshoot: Nonnegative distances that glyph ink extends beyond the frame’s left, top, right, and bottom edges.

requiredHeight and overshoot use local scene design units before block transformations, stroke, effects, or animations. Overshoot includes ink on hidden lines. Intentional glyph overhang can produce nonzero overshoot; choose limits that suit your design.

Curved text omits planar layout measurements. An absent layout means those measurements are unavailable; it does not mean the text passed verification.

If forceLoadResources() rejects, handle the error before inspecting diagnostics. A missing layout means measurements are unavailable, rather than confirming that the text fits.

Export the Result#

Export the page as a PNG file to inspect the rendered font:

// Export the scene to PNG
const blob = await engine.block.export(page, { mimeType: 'image/png' });
const buffer = Buffer.from(await blob.arrayBuffer());
// Ensure output directory exists
if (!existsSync('output')) {
mkdirSync('output');
}
// Save to file
writeFileSync('output/add-text.png', buffer);
console.log('Exported to output/add-text.png');

Dispose the Engine#

Release the engine in a finally block so failed font downloads or exports do not leave it running.

engine.dispose();

Troubleshooting#

  • An uploaded font file is rejected: getFontInfo() rejects with EDITOR.FONT_INFO_EXTRACT_FAILED when the file is not a supported font. Use a TTF, OTF, WOFF or WOFF2 file.
  • The font info does not load: Check that the server can reach the font URI. An unreachable URI rejects with EDITOR.FONT_LOAD_FAILED.
  • Bold or italic is unavailable: A typeface built from one file has one font entry. Read each file in the family and add one entry for each file to the fonts array.
  • The request remains unresolved: Check the family, source and asset identifiers. Confirm the provider returns a matching typeface and a readable font file.
  • The text uses a different font: Inspect each diagnostic run’s requested identity, actual URI and status. Font availability and glyph fallback are separate checks.
  • The layout is unavailable: Wait for resources, handle any load failure and query again. Curved text has no planar layout measurements.
  • An older application cannot edit a newly saved scene: Upgrade its engine together with the saving engine, or keep using the original scene file.

API Reference#

Method Purpose
engine.editor.getFontInfo(fontFileUri, options) Read the family, subfamily, weight, style and variation axes of a font file.
engine.asset.addLocalSource(sourceId) Register a local typeface source.
engine.asset.addAssetToSource(sourceId, asset) Add a concrete typeface definition.
engine.block.setFont(block, uri, typeface) Apply a concrete file to the whole block.
engine.block.setTypeface(block, typeface, from?, to?) Apply a concrete typeface while preserving compatible formatting.
engine.block.getTypeface(block) Read the base typeface definition.
engine.block.getTypefaces(block, from?, to?) Read the unique typeface definitions in a range.
engine.block.setFontRequest(block, request, from?, to?) Store the requested identity for resolution.
engine.block.getFontRequests(block, from?, to?) Read the unique stored requests.
engine.editor.setTypefaceResolver(resolver?) Install a provider or restore registered-source lookup.
engine.block.forceLoadResources(blocks) Await pending resource resolution.
engine.block.onStateChanged(blocks, callback) Observe block-state changes.
engine.block.getState(block) Read the current resource state.
engine.block.export(block, options) Export a block as an image.
engine.block.getTextRenderDiagnostics(block) Inspect shaped fonts, missing glyphs and layout.

Next Steps#

  • Add Text for creating and styling text in the complete example.
  • Auto-Size Text for choosing text-frame sizing behavior.