Friday, January 29, 2010

Add Custom Font Using FOP

This post is about Java PDF generation using Apache FOP and XSL-FO. Your client wants a font in their PDF report generation that isn't available in the system. I found the documentation a little over the top and obscured what I needed to do. Therefore in 3 easy steps this is what you need to do:
  1. Create a metrics xml of the font using FOP Utility.
  2. Define custom font in FOP configuration.
  3. Use font in XSLT.
Create a metrics xml of the font using FOP Utility I'm using maven and therefore it is easier to create a simple class within my project to call FOPs font util rather than messing about with command line java and classpaths.
import org.apache.fop.fonts.apps.TTFReader;

public class ConvertFont {
public static void main(String[] args) {
    TTFReader.main(new String[] {"/home/farrd/fonts/TheSans","/home/farrd/fonts/TheSans.xml"});
}
}
Define custom font in FOP configuration Copy the font and the metric xml file into your project so that it is available on the classpath. Now create a fop configuration file and define the font. Apache FOP uses Apache FVS so you can prefix the location of the font files with res and it will resolve them correctly. (nice!)





  





Use font in XSLT When constructing your FopFactory, set the above configuration. I'm using BulterIO to resolve the file. (this is a nice also [yes, shameless self plug as I've worked on some of the code in BulterIO])
...
FopFactory fopFactory = FopFactory.newInstance();
try {
    fopFactory.setUserConfig(ButlerIO.fileAt("fop_config.xml"));
} catch (Exception e) {
    throw new RuntimeException(e);
}

fopFactory.setURIResolver(new URIResolver() {
    public Source resolve(String href, String base) throws TransformerException {
        return new StreamSource(ButlerIO.inputStreamFrom(href));
    }
});
...

You can now reference your font in the normal way within your XSLT.
...


...


...

0 comments:

Post a Comment