Substitute Fonts in PDFs Using JavaScript

Font substitution allows you to replace the fonts used to render text annotations and form fields that don’t have an appearance stream so that they can be rendered with the font designed as a substitute. Font substitution provides the flexibility to change the visual representation of fonts in text annotations and form fields without modifying the original file.

When used in Office conversion, font substitution can also be used to replace fonts that were used to produce a converted PDF.

Define Font Substitutions

Before loading your document, set up your font substitutions, which take the form of an array of objects. Each object specifies the font pattern you want to replace (pattern) and the font you want to replace it with (target).

Patterns support the following wildcards:

  • /*/ matches multiple characters.

  • ? matches a single character.

Both the pattern and target names are case-insensitive.

As an example, to substitute all fonts that start with “Helv” with “Courier”, use the following:

const customFontSubstitutions = [
  {
    pattern: "Helv*",
    target: "Courier"
  }
];

As font names could match multiple patterns, it’s crucial to understand that the order of the patterns in the array matters. PSPDFKit will evaluate patterns in the order they’re defined in the array. For example, consider the scenario where you have the following font substitutions:

const customFontSubstitutions = [
  {
    pattern: "Helv*",
    target: "Courier"
  },
  {
    pattern: "Helvetica",
    target: "Arial"
  }
];

In this scenario, the font substitution will match all fonts that start with “Helv” and replace them with “Courier”. However, if you swap the order of the patterns, the substitution will match “Helvetica” and replace it with “Arial”.

Loading PSPDFKit with Font Substitutions

Once you’ve defined your font substitutions, you can load PSPDFKit with the PSPDFKit.Configuration#fontSubstitutions configuration option:

await PSPDFKit.load({
  ...defaultConfiguration,
  fontSubstitutions: customFontSubstitutions
});

Font Substitution in Action

When exporting a document with font substitution and viewing the document in any PDF viewer, the substituted fonts will be displayed in place of the original fonts in the appearance stream of text annotations and form fields.