PDFsharp Sample: Font Resolver

Modified on 2015/12/16 14:29 by Thomas Hövel — Categorized as: MigraDoc Samples, PDFsharp Samples, Samples

<< Previous^UpNext >>
This sample shows how to use fonts that are included with your application. This allows you to use fonts that are not installed on the computer.

For tasks running on web servers, private fonts may be the only available fonts.

Note:  When using the GDI build, you can use the XPrivateFontCollection class. As of PDFsharp 1.50 beta 2, the XPrivateFontCollection class is the recommended way for applications that use the GDI build of PDFsharp and that also use the screen preview or use the XGraphics class to draw on other contexts beside PDF files.
PDFsharp Sample: Private Fonts

The method shown in this sample works for the WPF build, the Core build, and the Silverlight build. This method has one drawback: it is not compatible with the DocumentPreview control that can be used with the WPF build. If your WPF application uses the DocumentPreview then stick to private fonts.
If you do not use the DocumentPreview, then use this method. It is the recommended method for applications running on web servers, it is the only method available for Silverlight applications.

Note:  The FontResolver is a global object and applies to all consumers of the PDFsharp library. It is also used when the MigraDoc library creates PDF files.

The IFontResolver Interface

In your application you create a class that implements the IFontResolver interface (it is in the PdfSharp.Fonts namespace).

There are only two methods you have to implement. The first method returns a FontResolverInfo for every supported font.
public FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic)

The other method is called using the FaceName from the FontResolverInfo you previously returned. At this stage, return the font data as a byte array.
public byte[] GetFont(string faceName)

Now you only need one more step: register your font resolver using the global font resolver property. Here SegoeWpFontResolver is the class that implements IFontResolver.
// Register font resolver before start using PDFsharp.
GlobalFontSettings.FontResolver = new SegoeWpFontResolver();

Additional Information

The font resolver set using GlobalFontSettings.FontResolver will be used by PDFsharp. Since MigraDoc uses PDFsharp to create PDF files, the font resolver will also be used when generating PDF files from MigraDoc.

Note: The samples on this site usually show and discuss code snippets only. The complete source code of the samples with solutions for Visual Studio is available from the download area on CodePlex.