The source code change is here:

/*
 * Copyright 1999-2003,2005 The Apache Software Foundation.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* $Id$ */

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.fop.apps.Driver;
import org.apache.fop.messaging.MessageHandler;

import org.apache.avalon.framework.logger.ConsoleLogger;
import org.apache.avalon.framework.logger.Logger;

import embedding.ExampleObj2XML;
import embedding.model.ProjectTeam;

/**
 * Example servlet to generate a PDF from a servlet.
 * Servlet param is:
 * <ul>
 *   <li>fo: the path to a formatting object file to render
 * </ul>
 *
 * Example URL: http://servername/fop/servlet/FopServlet?fo=readme.fo
 * Example URL:
http://servername/fop/servlet/FopServlet?xml=data.xml&xsl=format.xsl
 * Compiling: you will need
 * - servlet_2_2.jar
 * - fop.jar
 * - sax api
 * - avalon-framework-x.jar (where x is the version found the FOP lib dir)
 *
 * Running: you will need in the WEB-INF/lib/ directory:
 * - fop.jar
 * - batik.jar
 * - xalan-2.0.0.jar
 * - avalon-framework-x.jar (where x is the version found the FOP lib dir)
 */
public class FopServlet extends HttpServlet {
    
    public static final String FO_REQUEST_PARAM = "fo";
    public static final String XML_REQUEST_PARAM = "xml";
    public static final String XSL_REQUEST_PARAM = "xsl";
    
    protected Logger log = null;
    protected TransformerFactory factory = null;

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response) throws ServletException
{
        if (log == null) {
            log = new ConsoleLogger(ConsoleLogger.LEVEL_WARN);
            MessageHandler.setScreenLogger(log);
        }
        try {
            String foParam = request.getParameter(FO_REQUEST_PARAM);
            String xmlParam = request.getParameter(XML_REQUEST_PARAM);
            String xslParam = request.getParameter(XSL_REQUEST_PARAM);

            if (foParam != null) {
                File fofile = new File(foParam);
                //log.warn("FO: "+fofile.getCanonicalPath());
                Source src = new StreamSource(fofile);
                renderFO(src, null, response);
            } else if ((xmlParam != null) && (xslParam != null)) {
                Source src = new StreamSource(new File(xmlParam));
                Source xslt = new StreamSource(new File(xslParam));
                renderFO(src, xslt, response);
            } else if (xslParam != null) {
                /**
                 * Example of going straight to PDF from ProjectTeam
                 * without touching file system
                 */
                ProjectTeam projectTeam =
ExampleObj2XML.createSampleProjectTeam();
                Source src = projectTeam.getSourceForProjectTeam();
                Source xslt = new StreamSource(new File(xslParam));
                renderFO(src, xslt, response);
            } else {
                PrintWriter out = response.getWriter();
                out.println("<html><head><title>Error</title></head>\n"+
                            "<body><h1>FopServlet Error</h1><h3>No 'fo' "+
                            "request param given.</body></html>");
            }
        } catch (ServletException ex) {
            throw ex;
        }
        catch (Exception ex) {
            throw new ServletException(ex);
        }
    }

    /**
     * Renders an FO inputsource into a PDF file which is written
     * directly to the response object's OutputStream
     * @param src Source (XML or FO file)
     * @param xslt Source for stylesheet (may be null)
     * @param response servlet response to send the PDF to
     * @throws ServletException in case of an exception
     */
    public void renderFO(Source src, Source xslt,
                         HttpServletResponse response) throws
ServletException {
        try {
            //Start with a bigger buffer to avoid too many buffer
reallocations
            ByteArrayOutputStream out = new ByteArrayOutputStream(16384);

            response.setContentType("application/pdf");

            Driver driver = new Driver();
            driver.setLogger(log);
            driver.setRenderer(Driver.RENDER_PDF);
            driver.setOutputStream(out);

            //Setup XSLT
            if (factory == null) {
                factory = TransformerFactory.newInstance();
            }
            Transformer transformer;
            if (xslt != null) {
                transformer = factory.newTransformer(xslt);
            } else {
                transformer = factory.newTransformer();
            }
        
            //Resulting SAX events (the generated FO) must be piped through
to FOP
            Result res = new SAXResult(driver.getContentHandler());

            //Start XSLT transformation and FOP processing
            transformer.transform(src, res);

            byte[] content = out.toByteArray();
            //log.debug("Created PDF: " + content.length);
            response.setContentLength(content.length);
            response.getOutputStream().write(content);
            response.getOutputStream().flush();
        } catch (Exception ex) {
            throw new ServletException(ex);
        }
    }

}

and the simplest way to sort the build.xml file is to add this to
servlet/build.xml:

  <property name="embedding.src.dir" value="./../embedding/java"/>

  <!-- ===================================================================
-->
  <!-- Compiles the source directory
-->
  <!-- ===================================================================
-->
  <target name="compile" depends="prepare">
    <echo message="Compiling the sources "/>
    <javac srcdir="${embedding.src.dir}" destdir="${build.dest}"
debug="${debug}" deprecation="${deprecation}" optimize="${optimize}">
      <classpath refid="project.class.path"/>
    </javac>

    <javac srcdir="${src.dir}" destdir="${build.dest}" debug="${debug}"
deprecation="${deprecation}" optimize="${optimize}">
      <classpath refid="project.class.path"/>
    </javac>
  </target>

Ben



-----Original Message-----
From: Jeremias Maerki [mailto:[EMAIL PROTECTED]
Sent: 11 March 2005 10:10
To: [EMAIL PROTECTED]
Subject: Re: FopServlet


The modified servlet has the same functionality as the example servlet
in the distribution. You're welcome to do the example involving the
ProjectTeam yourself. I don't have the time.

On 11.03.2005 11:06:59 Ben Gill wrote:
> Are you not creating an XML file on disk with this version with:
> 
> else if ((xmlParam != null) && (xslParam != null)) {
>                 Source src = new StreamSource(new File(xmlParam));
> 
> I think it would be good to include an example of how to generate the PDF
> from a ProjectTeam without touching the disk?
> 
> Ben
> 
> 
> -----Original Message-----
> From: Jeremias Maerki [mailto:[EMAIL PROTECTED]
> Sent: 11 March 2005 08:26
> To: [EMAIL PROTECTED]
> Subject: Re: FopServlet
> 
> 
> Here's a modified version of the servlet:
> http://cvs.apache.org/~jeremias/FopServlet.java
> 
> BTW, while updating the file I found an opportunity for a little
> optimization. In the servlet's case the ByteArrayOutputStream should not
> be instantiated with the default constructor. This only allocates 64
> bytes initially. Every time the buffer runs out of space the old buffer
> is discarded and a new one with twice the previous space is allocated.
> If you do "new ByteArrayOutputStream(16384)" (or an even higher number
> depending on the documents you serve), you will get a slight performance
> improvement almost for free. :-)
> 
> On 10.03.2005 13:02:22 Ben Gill wrote:
> > Maybe the example can be updated with my version?  I have not compiled
> this,
> > but I know it works...
> 
> 
> 
> Jeremias Maerki
> 
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: [EMAIL PROTECTED]
> For additional commands, e-mail: [EMAIL PROTECTED]
> 
> 
> _____________________________________________________________________
> This message has been checked for all known viruses by the 
> MessageLabs Virus Control Centre.
> 
> This message has been checked for all known viruses by the MessageLabs
Virus Control Centre.
> 
>       
> *********************************************************************
> 
> Notice:  This email is confidential and may contain copyright material of
Ocado Limited (the "Company"). Opinions and views expressed in this message
may not necessarily reflect the opinions and views of the Company.
> If you are not the intended recipient, please notify us immediately and
delete all copies of this message. Please note that it is your
responsibility to scan this message for viruses.
> 
> Company reg. no. 3875000.
> Ocado Limited
> Titan Court
> 3 Bishops Square
> Hatfield Business Park
> Hatfield
> Herts
> AL10 9NE
> 
> 
> *********************************************************************
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: [EMAIL PROTECTED]
> For additional commands, e-mail: [EMAIL PROTECTED]



Jeremias Maerki


---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]


_____________________________________________________________________
This message has been checked for all known viruses by the 
MessageLabs Virus Control Centre.

This message has been checked for all known viruses by the MessageLabs Virus 
Control Centre.

        
*********************************************************************

Notice:  This email is confidential and may contain copyright material of Ocado 
Limited (the "Company"). Opinions and views expressed in this message may not 
necessarily reflect the opinions and views of the Company.
If you are not the intended recipient, please notify us immediately and delete 
all copies of this message. Please note that it is your responsibility to scan 
this message for viruses.

Company reg. no. 3875000.
Ocado Limited
Titan Court
3 Bishops Square
Hatfield Business Park
Hatfield
Herts
AL10 9NE


*********************************************************************

---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to