Apache FOP with Saxon

Apache FOP is a print formatter that uses XSL formatting objects (XSL-FO) to transform XML into a PDF for viewing or printing. We use FOP in uzERP to output documents like invoices, orders and reports. Recently, I wanted to use some XSLT2.0 features in a document that I was developing for a uzERP customer, but FOP uses Xalan as its default transformation engine and that only supports XSLT1.0.

FOP is a Java application and XML processing is pluggable using the Java API for XML Processing (JAXP), so Xalan can be replaced with an alternative processor. We are deploying our customer systems on Ubuntu 14.04 and packages are available for Saxon 6.5.5, an XSLT processor that supports new features first defined in the XSLT 1.1 working draft. This was enough for me to be able to use the format-date function and a few others in my stylesheet, but…

How to persuade FOP to use Saxon?

First of all, install the Saxon packages:

$ sudo apt-get update && apt-get install libsaxon-java libsaxonb-java

Copy the FOP command line script:

$ cp /usr/bin/fop /usr/local/bin/fop

Edit the copied script file:

#Add this before any other find_jars
find_jars saxon saxonb

#Add the saxon processor to the java_run command at the bottom of the script
run_java $HEADLESS $LOG_OPTION -Djavax.xml.transform.TransformerFactory=net.sf.saxon.TransformerFactoryImpl org.apache.fop.cli.Main "$@"

I want this script to override the standard FOP script when using the fop command, so added a system wide alias by creating a file called fop-alias.sh in /etc/profile.d with the following contents:

alias fop="/usr/local/bin/fop"

With all that done, the fop command will now load the Saxon XSLT processor, which enables access to a number of useful extensions not available in XLST1.0