Back to Devexpress

DXFontRepository Class

corelibraries-devexpress-dot-drawing-d8304ba4.md

latest17.4 KB
Original Source

DXFontRepository Class

A repository of user-defined fonts.

Namespace : DevExpress.Drawing

Assembly : DevExpress.Drawing.v25.2.dll

NuGet Package : DevExpress.Drawing

Declaration

csharp
public class DXFontRepository :
    IDisposable
vb
Public Class DXFontRepository
    Implements IDisposable

The following members return DXFontRepository objects:

Remarks

The DXFontRepository class allows you to use fonts that are not installed in the hosting environment. Add required fonts to the font repository to eliminate font substitution effects. This class is available for the following products:

  • Word Processing Document API
  • Spreadsheet Document API
  • PDF Document API (used in graphics content only)
  • Reporting
  • Charts
  • Rich Text Editor and Spreadsheet controls (WinForms/WPF)

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

Loaded fonts are not saved to the document - they are used to display, print, or export Word and Spreadsheet documents. Custom fonts are applied to the report when it is exported to PDF or an image from code.

Add Fonts to the Repository Directly

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 layout recalculations, add the fonts to DXFontRepository before you load a document, report, or chart that uses these fonts.

The code sample below adds custom fonts to DXFontRepository. This example uses the following preloaded Google Fonts:

csharp
using DevExpress.Drawing;
//...
DXFontRepository.Instance.AddFont(@"Fonts\EmilysCandy-Regular.ttf");
DXFontRepository.Instance.AddFont(@"Fonts\FrederickatheGreat-Regular.ttf");
// you usage code here
//...
vb
Imports DevExpress.Drawing
'...
DXFontRepository.Instance.AddFont("Fonts\EmilysCandy-Regular.ttf")
DXFontRepository.Instance.AddFont("Fonts\FrederickatheGreat-Regular.ttf")
' your usage code here
'...

Use Fonts in Word Processing Document API

The code sample below uses fonts added to the repository to format the document content. The resulting document is exported to PDF.

csharp
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");
}

private static void FormatCharacters(CharacterProperties formatting,
float size, string fontName, Color color)
{
  formatting.FontSize = size;
  formatting.FontName = fontName;
  formatting.ForeColor = color;
}
vb
Using wordProcessor As New RichEditDocumentServer()
    Dim document As Document = wordProcessor.Document
    ' Load a document.
    document.LoadDocument("Documents\Alice in Wonderland.docx")

    ' Format the first paragraph, which contains the book title. 
    Dim titleFormatting As CharacterProperties = 
      document.BeginUpdateCharacters(document.Paragraphs(0).Range)
    FormatCharacters(titleFormatting, 20, "Fredericka the Great", 
                      Color.FromArgb(&H2E, &H74, &HB5))
    document.EndUpdateCharacters(titleFormatting)

    ' Format the second paragraph, which contains the author's name. 
    Dim subtitleFormatting As CharacterProperties = 
      document.BeginUpdateCharacters(document.Paragraphs(1).Range)
    FormatCharacters(subtitleFormatting, 14, "Emilys Candy", 
                      Color.FromArgb(&H3B, &H38, &H38))
    document.EndUpdateCharacters(subtitleFormatting)

    ' Export the document to PDF.
    wordProcessor.ExportToPdf("Documents\Alice in Wonderland.pdf")
End Using

Private Sub FormatCharacters(formatting As CharacterProperties,
                          size As Single, fontName As String, color As Color)
formatting.FontSize = size
formatting.FontName = fontName
formatting.ForeColor = color
End Sub

The image below illustrates the result.

Use Fonts in Spreadsheet Document API

The code sample below 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:

csharp
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");
            }
        }
    }
}
vb
Imports DevExpress.Drawing
Imports DevExpress.Spreadsheet

Module Module1
    Sub Main()
        DXFontRepository.Instance.AddFont("Fonts\advent-pro.regular.ttf")
        DXFontRepository.Instance.AddFont("Fonts\Roboto-Light.ttf")

        Using workbook As New Workbook()
            ' Load a workbook.
            workbook.LoadDocument("Documents\Sales Report.xlsx", DocumentFormat.Xlsx)
            Dim worksheet As Worksheet = workbook.Worksheets("Report")

            ' Return the cell that contains the document title.
            Dim cell As 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.
            Dim range As CellRange = worksheet.Range("B4:F20")

            ' Start range format update. 
            Dim rangeFormatting As Formatting = 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")
        End Using
    End Sub
End Module

The image below illustrates the result.

Use Fonts in Reporting

The code sample below adds custom fonts to DXFontRepository and uses these fonts to format report labels. The resulting report is exported to PDF. This example uses the following Google fonts:

csharp
using DevExpress.Drawing;
//...
    public XtraReport1()
    {
        InitializeComponent();
        DXFont labelFont = new DXFont("Advent Pro", 26);
        DXFont cellFont = new DXFont("Roboto", 14);

        xrLabel4.Font = labelFont;
        xrTableCell4.Font = cellFont;
        xrTableCell7.Font= cellFont;
        xrTableCell10.Font = cellFont;
        xrTableCell13.Font= cellFont;

        XtraReport1 report = new XtraReport1();
        report.ExportToPdf("result.pdf");

    }
vb
Imports DevExpress.Drawing
'...

  Public Sub New()
    InitializeComponent()
    Dim labelFont As New DXFont("Advent Pro", 26)
    Dim cellFont As New DXFont("Roboto", 14)

    xrLabel4.Font = labelFont
    xrTableCell4.Font = cellFont
    xrTableCell7.Font= cellFont
    xrTableCell10.Font = cellFont
    xrTableCell13.Font= cellFont

    Dim report As New XtraReport1()
    report.ExportToPdf("result.pdf")

  End Sub

The image below demonstrates the result.

Note

Custom fonts are not displayed in the report preview.

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:

csharp
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);
    }
}
vb
Private Shared Sub Report_QueryNotFoundFont(ByVal sender As Object, ByVal e As NotFoundFontEventArgs)
    If e.RequestedFont = "Sankofa Display" Then
        Dim font As String = Environment.CurrentDirectory & "\Data\SankofaDisplay-Regular.ttf"
        e.FontFileData = File.ReadAllBytes(font)
    End If
End Sub

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 Information About Fonts in the Repository

Use the FontRepository.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:

csharp
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<DXFontData> fonts = DXFontRepository.Instance.GetFonts();
    for (int i = 0; i < fonts.Count; i++)
    {
        Console.WriteLine($" \u002A {fonts[i].Name}");
    }
}
vb
Imports DevExpress.Drawing
Imports System
Imports System.Collections.Generic
' ...

If DXFontRepository.Instance.IsEmpty Then
    Console.WriteLine("Font repository is empty.")
Else
    Console.WriteLine("Font repository contains the following fonts:")
    Dim fonts As IList(Of DXFontData) = DXFontRepository.Instance.GetFonts()
    For i As Integer = 0 To fonts.Count - 1
        Console.WriteLine($" " & ChrW(&H002A).ToString() & " {fonts(i).Name}")
    Next i
End If

The following image demonstrates a sample 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.

csharp
using DevExpress.Drawing;
// ...

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

' Check whether the font repository is empty.
If Not DXFontRepository.Instance.IsEmpty Then
    ' If false, clear the font repository.
    DXFontRepository.Instance.Clear()
End If

Inheritance

Object DXFontRepository

See Also

DXFontRepository Members

DevExpress.Drawing Namespace