advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

Tutorials : Using FOP with Java

Using FOP with Servlet

Web based applications often need to display different data and reports. Again, the same data may need to be formatted and presented differently to different users. In such contexts, FOP becomes very useful. We can maintain separate stylesheets for different display formats and can still reuse the same FOP formatting engine. Just to show how flexible it is to use FOP, we will write a Servlet which will use FOP to produce a PDF output of the Catalogue information XML (listing 1) and send it straight back to the browser.

The Servlet code is shown in Listing 3.

import org.apache.fop.apps.Driver;
import org.apache.fop.apps.XSLTInputHandler;
import org.apache.fop.render.Renderer;
import org.apache.avalon.framework.logger.Logger;
import org.apache.avalon.framework.logger.ConsoleLogger;
 
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.util.logging.Level;
 
 
public class FOPServlet extends HttpServlet
{
    private String xmlFile = "data.xml";
    private String xslFile = "pdfGen.xsl";
 
    protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse 
httpServletResponse) throws ServletException, IOException
    {
        // set up a FOP driver
        Driver driver = new Driver();
        // set up the logger for the driver
        Logger logger = new ConsoleLogger(ConsoleLogger.LEVEL_INFO);
        driver.setLogger(logger);
 
        try
        {
            //set the renderer to be PDF
            driver.setRenderer(Driver.RENDER_PDF);
 
            //create the input from the XSLT transform
            XSLTInputHandler inputHandler = new XSLTInputHandler(xmlFile, xslFile);
 
            // now prepare the outputStrean
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
 
            //set the driver outputStream
            driver.setOutputStream(outStream);
 
            //do the XSLT
            driver.render(inputHandler.getParser(), inputHandler.getInputSource());
 
            //now that the content is written in the output stream,
            //get ready to send the response back to browser
            byte[] content = outStream.toByteArray();
            httpServletResponse.setContentLength(content.length);
            // set the MIME-TYPE
            httpServletResponse.setContentType("application/pdf");
            //write the content
            httpServletResponse.getOutputStream().write(content);
            httpServletResponse.getOutputStream().flush();
 
        } catch (Exception e)
        {
            e.printStackTrace();
        }

    }
 
}
Listing 3-FOP Servlet code

Few important things to notice in this code example.

  • We start by creating a FOP Driver object and set the render type to be PDF. This lets FOP know that it has to produce a PDF output.
  • We let the drive know about an OutputStream object to write the rendered content.
  • We use the FOP XSLTInputHandler object to do the XSL transform by supplying it the xml file and the xsl file.
  • Then, we ask the Driver object to render the document and pipe it to the specified OutputStream.
  • Finally, before sending the response back to the browser, we set the MIME type to "application/pdf".

Following this example, it would be easy to convert this code to save the generated PDF output to a file in your hard drive. To do that, you just need to create a FileOutputStream object and set it to the Driver instead of the HTTP Response output stream. You will see a nice PDF file stored in the specified location.

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 Microsoft Visual Studio 2010 Showcase
 Avaya Developer Showcase
 MSDN Spotlight
 PHP for Windows Showcase
XML error: undefined entity at line 39
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Windows 7: From Beta to Final Code in One Year
Google Shows Off Chrome OS, Releases Source
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?
Fedora 12 Takes Aim at Linux Networking
Top Supercomputer Nearly Doubles in Speed
Fedora 12 Linux Tackles Virtualization
Apple Gives iPhone Developers App Status Tracker
Novell Sets OpenSUSE 11.2 Free

Creating Custom Export Filters for StarOffice with XSLT
WPF Wonders: Using DataTemplates
Crystal Reports Family Offers Options for Developers
Avaya Aura Session Manager video
Avaya Aura Overview video
Exploring HTML 5's Audio/Video Multimedia Support
Overriding Virtual Functions? Use C++0x Attributes to Avoid Bugs.
Understanding the Cloud Computing Security Vulnerabilities
Cisco and IBM Target a Greener World
Upgrade to Visual Studio 2010 with the Ultimate Offer

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs