How to use a system font for rendering text

This code sample shows how you can render text using a system font.

By default, PDFRasterizer.NET and PDFControls.NET render text as curves (paths) that are filled with a particular color. Any font information that is present in the PDF document gets interpreted and transformed into curves, and then rendered.

We do this, because this results in the most accurate representation of the text. Windows does not support all font types that are possible in a PDF document. So we cannot always tell .NET to render the fonts for us.

There are however cases that it makes sense to have text rendered as system fonts. For example to speed up print jobs as explained in the article named how to speed up print jobs. This code sample will show you how to do this exactly.

Below we will just talk about PDFRasterizer.NET, but it applies to PDFControls.NET as well.

The UseOSFont sample

The following snippets comes from the UseOSFont sample that is included in the PDFRasterizer.NET distribution. This sample shows how you can use the ResolveFont event to map PDF fonts to system fonts. The first step is to assign a handler for this event before rendering.

renderSettings1 = new RenderSettings();
renderSettings1.TextSettings.ResolveFont += new ResolveFontEventHandler(TextSettings1_ResolveFont);

The handler itself will be called whenever a PDF font needs to be rendered. It will pass information about this font in the event arguments. In addition it will pass information about the way that it is going to be rendered (in the FontRenderMode), and where the font definition has been obtained (in the FontLocation). The handler can inspect this information and change it in order to request a different way of rendering.

The code below will first check if the font information already originates from a system font. If not, it will set the RenderMode to RenderAsFont and set the SystemFontName. This will cause the rendering system to look up this font and avoid rendering it as curves.

void TextSettings1_ResolveFont(TextRenderSettings sender, ResolveFontEventArgs args)
  if (args.FontLocation != FontLocation.System)
    args.FontRenderMode = FontRenderMode.RenderAsFont;

    if (args.PdfFontName.EndsWith("Bold"))
      args.Bold = true;

    args.SystemFontName = "Arial";

Please note that certain combinations are not supported currently. For system fonts the FontRenderMode cannot be set to RenderAsCurves. If an inappropriate combination is used, the ResolveFont event will be raised again, allowing the application to correct the requested render mode. For details please see the reference guide that is included in PDFRasterizer.NET.