Substitute fonts in PDFs using JavaScript
Font substitution enables you to map one font name to another when a PDF references a font that isn’t embedded. The rules apply to page rendering and to text annotations and form fields that don’t have an appearance stream, so you can keep rendering consistent without modifying the original file. If you use dynamic font loading, the SDK resolves missing fonts using the substituted name.
Page-rendering substitution for non-embedded fonts is available starting with Nutrient Web SDK 1.13.0. Font substitution doesn’t modify the PDF itself. If the substituted font isn’t available, provide it with dynamic font loading or custom fonts.
When you use Office conversion, font substitution also replaces fonts used to generate the converted PDF.
Define font substitutions
Before you load a document, define fontSubstitutions as an array of objects. Each object includes:
pattern— The font name pattern to match.target— The replacement font name.
Patterns support the following wildcards:
- /*/ matches multiple characters.
- ? matches a single character.
Both the pattern and target names are case-insensitive.
For target, use the exact font face name expected by the SDK, including style and weight when applicable. For example, use Noto Sans SC Regular instead of Noto Sans SC.
To substitute all fonts that start with “Helv” with “Courier”, use the following:
const customFontSubstitutions = [ { pattern: "Helv*", target: "Courier", },];Font names sometimes match multiple patterns, so pattern order matters. Nutrient evaluates patterns in the order they appear in the array. For example, consider these substitutions:
const customFontSubstitutions = [ { pattern: "Helv*", target: "Courier", }, { pattern: "Helvetica", target: "Arial", },];In this order, the substitution matches all fonts that start with “Helv” and replaces them with “Courier”. If you swap the pattern order, the substitution matches “Helvetica” first and replaces it with “Arial”.
Loading Nutrient with font substitutions
After you define substitutions, load Nutrient Web SDK with the NutrientViewer.Configuration#fontSubstitutions configuration option:
await NutrientViewer.load({ ...defaultConfiguration, fontSubstitutions: customFontSubstitutions,});Font substitution in action
During viewing, substitutions are applied at render time for non-embedded page text. When exporting a document with font substitution and viewing it in any PDF viewer, substituted fonts appear in the appearance stream of text annotations and form fields.