mardi 25 mai 2010

FOP & Jython

#!/usr/bin/env jython

import sys

from java.io import File, FileOutputStream, BufferedOutputStream

# JAXP
from javax.xml.transform import Transformer, TransformerFactory, Source, Result
from javax.xml.transform.stream import StreamSource
from javax.xml.transform.sax import SAXResult

# FOP
from org.apache.fop.apps import FOUserAgent, Fop, FopFactory, MimeConstants

xmlfile = File("projectteam.xml")
xsltfile = File("projectteam2fo.xsl")
pdffile = File("out.pdf")

fopFactory = FopFactory.newInstance()
foUserAgent = fopFactory.newFOUserAgent()

out = FileOutputStream(pdffile)
out = BufferedOutputStream(out)

fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out)
factory = TransformerFactory.newInstance()
transformer = factory.newTransformer(StreamSource(xsltfile))
transformer.setParameter("versionParam", "2.0");
src = StreamSource(xmlfile)
res = SAXResult(fop.getDefaultHandler())
transformer.transform(src, res)

out.close()

Quite funny, but there's the bug in Jython ClassLoader so we have to place all FOP jars in CLASSPATH instead of sys.path.append(...) way.