Skip to main content
All docs
V24.2

DevExpress v24.2 Update — Your Feedback Matters

Our What's New in v24.2 webpage includes product-specific surveys. Your response to our survey questions will help us measure product satisfaction for features released in this major update and help us refine our plans for our next major release.

Take the survey Not interested

Load and Use Custom Fonts Without Installation on the System

  • 10 minutes to read

DevExpress Office File API allows you to use custom fonts in your documents. The following font formats are available:

  • TrueType fonts (.TTF)
  • OpenType fonts that use TrueType or CFF (Compact Font Format) glyph outlines (.OTF)
  • OpenType Font Collections (.TTC, .OTC) that contain multiple fonts in a single file

Variable fonts (VF) are not supported.

#Install a Font

You can install the required font on your machine or server to use in a document. Follow the instructions below for your operating system.

#Windows

Download font files. If font files are zipped, right-click the .zip folder and then click Extract to unzip them. If you are prompted to allow the program to make changes to your computer, and if you trust the source of the font, click Yes. Re-login to complete the installation.

Note

The Windows Server OS installs fonts on a per-user basis. Make sure that the font is installed for all users or for the user who runs the application.

#Linux

Install the fontconfig library to manage fonts. Copy the font file in the fonts directory and then refresh the font cache. In the Linux docker file, you can use the usr/local/share/fonts/ directory, and the following commands:

console
COPY ["FontsFolderNameHere/MyFontFileName.ttf", "usr/local/share/fonts/"]
RUN apt-get -y install fontconfig
RUN fc-cache -vf

Different Linux distributions use slightly different commands:

sudo apt-get -y install fontconfig
cp <font name> ~/.local/share/fonts
fc-cache -vfkq

You can install the ttf-mscorefonts-installer package to add Microsoft TrueType core fonts (Arial, Times New Roman, Courier New, and so on) to your system. Run the following terminal command to install this package and accept the license agreement:

sudo apt-get install ttf-mscorefonts-installer

You can also use the SkiaSharp library to use fonts without fontconfig installation. Add the SkiaSharp.NativeAssets.Linux.NoDependencies package to your project. Copy font files to the /usr/share/fonts folder. The Skia library automatically uses fonts from this folder.

#Use a Font Without Installation

The Word Processing Document API and Spreadsheet Document API ship with the DXFontRepository class that allows you to use fonts that are not installed on the current operating system. When you load a document that uses such fonts, the RichEditDocumentServer and Workbook components substitute missing fonts with the fonts available on the current machine. The DXFontRepository class allows you to load and use custom fonts in your application to prevent font substitution when documents are printed or exported to PDF.

Use the DXFontRepository.Instance static property to access a DXFontRepository instance.

#Add Fonts to the Font Repository

Use the DXFontRepository.AddFont method overloads to add fonts to the font repository. You can load a font from a file, stream, or byte array.

Supported font formats include:

  • TrueType fonts (.TTF)
  • OpenType fonts that use CFF (Compact Font Format) glyph outlines (.OTF)
  • OpenType Font Collections (.TTC, .OTC) that contain multiple fonts in a single file

To avoid excessive document layout recalculations, add fonts to DXFontRepository before you load a document that uses these fonts.

Note

Loaded fonts are not saved to the document. These fonts are used to print or export the document to PDF.

#Example 1: Use Custom Fonts in the Word Processing Document API

The following example adds custom fonts to DXFontRepository and uses these fonts to format document paragraphs. The resulting document is exported to PDF. This example uses the following Google fonts:

using DevExpress.Drawing;
using DevExpress.XtraRichEdit;
using DevExpress.XtraRichEdit.API.Native;
using System.Drawing;

namespace ConsoleOfficeApp {
    class Program {
        static void Main(string[] args) {
            DXFontRepository.Instance.AddFont(@"Fonts\EmilysCandy-Regular.ttf");
            DXFontRepository.Instance.AddFont(@"Fonts\FrederickatheGreat-Regular.ttf");

            using (var wordProcessor = new RichEditDocumentServer())
            {
                Document document = wordProcessor.Document;
                // Load a document.
                document.LoadDocument(@"Documents\Alice in Wonderland.docx");

                // Format the first paragraph, which contains the book title. 
                var titleFormatting = 
                  document.BeginUpdateCharacters(document.Paragraphs[0].Range);
                FormatCharacters(titleFormatting, 20, 
                  "Fredericka the Great", Color.FromArgb(0x2E, 0x74, 0xB5));
                document.EndUpdateCharacters(titleFormatting);

                // Format the second paragraph, which contains the author's name. 
                var subtitleFormatting = 
                  document.BeginUpdateCharacters(document.Paragraphs[1].Range);
                FormatCharacters(subtitleFormatting, 14, 
                  "Emilys Candy", Color.FromArgb(0x3B, 0x38, 0x38));
                document.EndUpdateCharacters(subtitleFormatting);

                // Export the document to PDF.
                wordProcessor.ExportToPdf(@"Documents\Alice in Wonderland.pdf");
            }
            DXFontRepository.Instance.Dispose();
        }

        private static void FormatCharacters(CharacterProperties formatting,
            float size, string fontName, Color color)
        {
            formatting.FontSize = size;
            formatting.FontName = fontName;
            formatting.ForeColor = color;
        }
    }
}

The following image demonstrates the result:

Custom Fonts in Word Processing Document API

#Example 2: Use Custom Fonts in the Spreadsheet Document API

The following example adds custom fonts to DXFontRepository and uses these fonts to format cells in a workbook. The resulting document is exported to PDF. This example uses the following Google fonts:

using DevExpress.Drawing;
using DevExpress.Spreadsheet;

namespace ConsoleOfficeApp {
    class Program {
        static void Main(string[] args) {
            DXFontRepository.Instance.AddFont(@"Fonts\advent-pro.regular.ttf");
            DXFontRepository.Instance.AddFont(@"Fonts\Roboto-Light.ttf");

            using (Workbook workbook = new Workbook())
            {
                // Load a workbook.
                workbook.LoadDocument(@"Documents\Sales Report.xlsx", DocumentFormat.Xlsx);
                Worksheet worksheet = workbook.Worksheets["Report"];

                // Return the cell that contains the document title.
                Cell cell = worksheet.Cells["B2"];

                // Specify font settings (font name and size).
                cell.Font.Name = "Advent Pro";
                cell.Font.Size = 26;

                // Return the cell range that contains report data.
                CellRange range = worksheet.Range["B4:F20"];

                // Start range format update. 
                var rangeFormatting = range.BeginUpdateFormatting();

                // Specify font settings (font name and size).
                rangeFormatting.Font.Name = "Roboto Light";
                rangeFormatting.Font.Size = 14;
                // End range format update. 
                range.EndUpdateFormatting(rangeFormatting);

                // Export the document to PDF.
                workbook.ExportToPdf(@"Documents\Sales Report.pdf");
            }

            DXFontRepository.Instance.Dispose();
        }
    }
}

The following image demonstrates the result:

Custom Fonts in Spreadsheet Document API

#Identify Missing Fonts and Add Them to the Repository

Your document design and layout may rely on a font type that is not available in the application’s hosting environment. As a result, the font cannot be installed on the client machine, in a Docker image, in Azure, or in another host/container. In such cases, your document replaces unavailable fonts with default fonts, which may alter the appearance of a document from the original design.

The DXFontRepository contains a mechanism to ensure that a document uses the correct fonts regardless of the hosting environment. A document will notify the application about missing typefaces so that you can obtain the required font data. Once you obtain these fonts, add them to the DXFontRepository, thus making them available to DevExpress controls.

The DXFontRepository.QueryNotFoundFont event fires for every unavailable font type. Handle this event to do the following:

  • Identify the missing typeface and its suggested alternative (e.RequestedFont and e.ActualFont)
  • Obtain the required font file from a font hosting service (such as Google Fonts)
  • Prepare a byte array and pass it to e.FontFileData

This implementation ensures that DXFontRepository contains all required font types before document generation begins.

The following code sample contains simple code that registers the preloaded “Sankofa Display” font in case it is unavailable in the application environment:

private static void Report_QueryNotFoundFont(object sender, NotFoundFontEventArgs e) {
    if (e.RequestedFont == "Sankofa Display") {
        string font = Environment.CurrentDirectory + "\\Data\\SankofaDisplay-Regular.ttf";
        e.FontFileData = File.ReadAllBytes(font);
    }
}

#Obtain Missing Fonts from a Font Hosting Service (Google Fonts)

You can use the DXFontRepository.QueryNotFoundFont event to identify missing fonts and download them from a hosting service. The following example implements a service that asynchronously downloads missing fonts from Google Fonts and adds them to DXFontRepository.

Use your personal Google API Key to run this example. For instructions on how to obtain your key, see Google Fonts Developer API.

Assign your API Key to the apiKey variable in the FontCollectorService.cs file before you launch the example.

Review license agreements associated with fonts that you use. Use and redistribution permissions may vary. The service used in this example (Google Fonts) hosts fonts that are open source and available at no cost. Review the following page for details: Google Fonts FAQ.

The report in this example contains a few fonts that may be missing in many hosting environments: Ga Maamli, Roboto, and Nerko One. The example obtains these fonts if missing and makes them available to report controls. When exported to PDF, the report uses the original fonts.

View Example: Obtain Missing Fonts from Google Fonts

#Obtain Information About Fonts in the Repository

Use the DXFontRepository.GetFonts method to return a list of all fonts in the font repository. Each item in this list is a DXFontData object that contains font information.

The following code sample retrieves the names of all fonts in the repository and displays this information in the console window:

using DevExpress.Drawing;
using System;
using System.Collections.Generic;
// ...

if (DXFontRepository.Instance.IsEmpty)
    Console.WriteLine("Font repository is empty.");
else
{
    Console.WriteLine("Font repository contains the following fonts:");
    IList<FontData> fonts = DXFontRepository.Instance.GetFonts();
    for (int i = 0; i < fonts.Count; i++)
    {
        Console.WriteLine($"  \u002A {fonts[i].Name}");
    }
}

The following image demonstrates a sample console output:

Console Output

#Clear the Font Repository

Call the DXFontRepository.Clear method to remove all fonts from the font repository. Use the DXFontRepository.IsEmpty property to check whether the repository contains fonts.

using DevExpress.Drawing;
// ...

// Check whether the font repository is empty.
if (!DXFontRepository.Instance.IsEmpty)
    // If false, clear the font repository.
    DXFontRepository.Instance.Clear();