Movatterモバイル変換


[0]ホーム

URL:


 

Apache XML Graphics Project Logo

Apache™ FOP

This document is for an old version of FOP that is no longer supported.Latest version of this page
The Apache FOP Project

The Apache™ FOP Project

Apache™ FOP: Servlets

How to use Apache™ FOP in a Servlet

Overview

This page discusses topic all around using Apache™ FOP in a servlet environment.

Example Servlets in the FOP distribution

In the directory {fop-dir}/fop-core/src/main/java/org/apache/fop/servlet, you'll find a working example of a FOP-enabled servlet.

The servlet is automatically built when you build Apache FOP using the supplied Ant script. After building the servlet, drop fop.war into the webapps directory of Apache Tomcat (or any other web container). Then, you can use URLs like the following to generate PDF files:

The source code for the servlet can be found under {fop-dir}/fop-core/src/main/java/org/apache/fop/servlet/FopServlet.java.

This example servlet should not be used on a public web server connected to the Internet as it does not contain any measures to prevent Denial-of-Service-Attacks. It is provided as an example and as a starting point for your own servlet.

Create your own Servlet

This section assumes you are familiar withembedding FOP.

A minimal Servlet

Here is a minimal code snippet to demonstrate the basics:

privateTransformerFactorytFactory=TransformerFactory.newInstance();publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException{try{response.setContentType("application/pdf");FopFactoryfopFactory=FopFactory.newInstance(newFile(".").toURI());Fopfop=fopFactory.newFop(MimeConstants.MIME_PDF,response.getOutputStream());Transformertransformer=tFactory.newTransformer();Sourcesrc=newStreamSource("foo.fo");Resultres=newSAXResult(fop.getDefaultHandler());transformer.transform(src,res);}catch(Exceptionex){thrownewServletException(ex);}}

There are numerous problems with the code snippet above. Its purpose is only to demonstrate the basic concepts. See below for details.

Adding XSL tranformation (XSLT)

A common requirement is to transform an XML source to XSL-FO using an XSL transformation. It is recommended to use JAXP for this task. The following snippet shows the basic code:

privateTransformerFactorytFactory=TransformerFactory.newInstance();publicvoidinit()throwsServletException{//Optionally customize the FopFactory and TransformerFactory here}[..]FopFactoryfopFactory=FopFactory.newInstance(newFile(".").toURI());//Setup a buffer to obtain the content lengthByteArrayOutputStreamout=newByteArrayOutputStream();//Setup FOPFopfop=fopFactory.newFop(MimeConstants.MIME_PDF,out);//Setup TransformerSourcexsltSrc=newStreamSource(newFile("foo-xml2fo.xsl"));Transformertransformer=tFactory.newTransformer(xsltSrc);//Make sure the XSL transformation's result is piped through to FOPResultres=newSAXResult(fop.getDefaultHandler());//Setup inputSourcesrc=newStreamSource(newFile("foo.xml"));//Start the transformation and rendering processtransformer.transform(src,res);//Prepare responseresponse.setContentType("application/pdf");response.setContentLength(out.size());//Send content to Browserresponse.getOutputStream().write(out.toByteArray());response.getOutputStream().flush();

Buffering the generated PDF in a ByteArrayOutputStream is done to avoid potential problems with the Acrobat Reader Plug-in in Microsoft Internet Explorer.

TheSource instance used above is simply an example. If you have to read the XML from a string, supply anew StreamSource(new StringReader(xmlstring)). Constructing and reparsing an XML string is generally less desirable than using a SAXSource if you generate your XML. You can alternatively supply a DOMSource as well. You may also use dynamically generated XSL if you like.

Because you have an explicitTransformer object, you can also use it to explicitely set parameters for the transformation run.

Custom configuration

You can easily set up your own FOUserAgent as demonstrated on theEmbedding page.

Improving performance

There are several options to consider:

Of course, theperformance hints from the Embedding page apply here, too.

Accessing resources in your web application

Often, you will want to use resources (stylesheets, images etc.) which are bundled with your web application. FOP provides a URIResolver implementation that lets you access files via the Servlet's ServletContext. The class is calledorg.apache.fop.servlet.ServletContextURIResolver.

Here's how to set it up in your servlet. Instantiate a new instance in the servlet's init() method:

/** URIResolver for use by this servlet */protectedURIResolveruriResolver;publicvoidinit()throwsServletException{this.uriResolver=newServletContextURIResolver(getServletContext());[..]}

The ServletContextURIResolver reacts on URIs beginning with "servlet-context:". If you want to access an image in a subdirectory of your web application, you could, for example, use: "servlet-context:/images/myimage.png". Don't forget the leading slash after the colon!

Further down, you can use the URIResolver for various things:

Here are some example snippets:

//Setting up the JAXP TransformerFactorythis.transFactory=TransformerFactory.newInstance();this.transFactory.setURIResolver(this.uriResolver);[..]ResourceResolverresolver=newResourceResolver(){publicOutputStreamgetOutputStream(URIuri)throwsIOException{URLurl=getServletContext().getResource(uri.toASCIIString());returnurl.openConnection().getOutputStream();}publicResourcegetResource(URIuri)throwsIOException{returnnewResource(getServletContext().getResourceAsStream(uri.toASCIIString()));}};//Setting up the FOP factoryFopFactoryBuilderbuilder=newFopFactoryBuilder(newFile(".").toURI(),resolver);fopFactory=builder.build();[..]//The stylesheet for the JAXP TransfomerSourcexsltSrc=this.uriResolver.resolve("servlet-context:/xslt/mystylesheet.xsl",null);Transformertransformer=this.transFactory.newTransformer(xsltSrc);transformer.setURIResolver(this.uriResolver);

Notes on Microsoft Internet Explorer

Some versions of Internet Explorer will not automatically show the PDF or call the servlet multiple times. These are well-known limitations of Internet Explorer and are not a problem of the servlet. However, Internet Explorer can still be used to download the PDF so that it can be viewed later. Here are some suggestions in this context:

Servlet Engines

When using a servlet engine, there are potential CLASSPATH issues, and potential conflicts with existing XML/XSLT libraries. Servlet containers also often use their own classloaders for loading webapps, which can cause bugs and security problems.

Tomcat

Check Tomcat's documentation for detailed instructions about installing FOP and Cocoon. There are known bugs that must be addressed, particularly for Tomcat 4.0.3.

WebSphere 3.5

Put a copy of a working parser in some directory where WebSphere can access it. For example, if /usr/webapps/yourapp/servlets is the CLASSPATH for your servlets, copy the Xerces jar into it (any other directory would also be fine). Do not add the jar to the servlet CLASSPATH, but add it to the CLASSPATH of the application server which contains your web application. In the WebSphere administration console, click on the "environment" button in the "general" tab. In the "variable name" box, enter "CLASSPATH". In the "value" box, enter the correct path to the parser jar file (/usr/webapps/yourapp/servlets/Xerces.jar in our example here). Press "OK", then apply the change and restart the application server.

Handling complex use cases

Sometimes the requirements for a servlet get quite sophisticated: SQL data sources, multiple XSL transformations, merging of several datasources etc. In such a case consider usingApache Cocoon instead of a custom servlet to accomplish your goal.

Apache Software Foundation

Copyright © 2025 The Apache Software Foundation, Licensed undertheApache License, Version 2.0.
Apache, Apache XML Graphics, Apache FOP, Apache Batik, the Apache logo, and theApache XML Graphics logos are trademarks ofThe ApacheSoftware Foundation. All other marks mentioned may be trademarks or registeredtrademarks of their respective owners.


[8]ページ先頭

©2009-2026 Movatter.jp