Skip to content

Custom Fonts

Cristian Talau edited this page May 20, 2017 · 7 revisions

Changing the font is one of the most common customizations when configuring PDF output. If you use a set of custom fonts in your documents, you probably re-use those same fonts in the generated PDF output.

In our case, we used the Google Roboto font. The resources associated with this font are located in the fonts directory.

Configuring the Apache FOP to use the Roboto font

The Apache FOP processor allows you to specify a directory for fonts. Moreover, you can configure it to scan the fonts directory recursively.

This is possible through the Apache FOP configuration file, in the fonts section:

<fonts>
    <!-- register all the fonts found in a directory -->
    <directory>C:\MyFonts1</directory>

    <!-- register all the fonts found in a directory and all of its sub directories (use with care) -->
    <directory recursive="true">C:\MyFonts2</directory>

    <!-- automatically detect operating system installed fonts -->
    <auto-detect/>
</fonts>

See more details in the Bulk Font Configuration section from the Apache FOP documentation.

In our customization, the Apache FOP configuration file is named fop.xconf and it is located in the project root directory.

Customizing the PDF plugin to use the Roboto font

The PDF plugin uses a font mapping mechanism, which basically means that you don't reference physical fonts in your XSL-FO file. Instead, in the XSL-FO file, you will use logical fonts (or aliases) and they will be replaced with references to the physical fonts found in the font-mappings.xml file that is located in the Customization/fo/ folder.

Here is the process:

  1. The XSLT stylesheets used to generate the XSL-FO output contains code like this:

    <xsl:attribute name="font-family">sans-serif</xsl:attribute>
    

    The font-family is defined to be sans-serif, but sans-serif is just an alias. It is not a physical font name.

  2. Therefore, another stage in the PDF generation uses this sans-serif alias and searches for it in the font-mappings.xml file.

    It finds a mapping like this:

    <aliases>
      <alias name="sans-serif">Sans</alias>
    </aliases>
    
  3. Then, it determines if Sans has a logical-font definition and if so, it will use the physical-font specified there:

    <logical-font name="Sans">
      <physical-font char-set="default">
        <font-face>Roboto, Helvetica, Arial Unicode MS, Tahoma, Batang, SimSun</font-face>
      </physical-font>
    ............
    </logical-font>
    

    Notice that the first referenced font is Roboto, so it will be preferred for rendering characters. If there is a character that cannot be rendered with Roboto, then the next referenced font will be used (Helvetica in our case) and so on.

Important: If no alias mapping is found for a font-family specified in the XSLT stylesheets, the processing defaults to Helvetica.

Related information:

Font configuration in PDF