>The FopServlet reads a .fo file.  This is of no use to me.  I will
>dyamically generate XML contianing only data.  This XML will be in a
>StringBuffer.  I first need to apply an XSL sytle sheet to this
>StringBuffer, generating a new XML stream (IN MEMORY).  This new (IN MEMORY)
>XML stream then needs to be ran through FOP to generate a PDF stream which
>will be sent back to the browser.  The embed sample also shows how to
>process .FO files.  This is not what I want!!!!  The ONLY file that can be
>on disk is the XSL file which contains the FO tags to apply to the XML data.

Applying XSL to your XML in memory should be fairly easy. The
transformation APIs in JAXP handle this. then just edit the servlet code to
handle something other than a file stream. I got this to work without much
problem a while ago. My code is appended below -- I think it worked with
0.17, haven't checked it in a while. It differs only slightly from the
original. The fo data comes in an HTTP parameter called "fo", though you
can change the name. It loads this all into the String called fo. Then when
it sets up the driver, instead of passing it a FileInputSource, it passes
it a StringInputSource derived from the fo String.

I dimly recollect that the Driver interface changed a lot in 0.18 so some
of these methods may now be hidden, i.e. not called directly in the
servlet, but if you manually configure your driver, changing the type of
input source you hand it should not be hard.

-- sgl

/*-- $Id: FopServlet.java,v 1.2 2001/03/03 07:06:03 kellyc Exp $ --

 ============================================================================
                   The Apache Software License, Version 1.1
 ============================================================================

    Copyright (C) 1999 The Apache Software Foundation. All rights reserved.

 Redistribution and use in source and binary forms, with or without modifica-
 tion, are permitted provided that the following conditions are met:

 1. Redistributions of  source code must  retain the above copyright  notice,
    this list of conditions and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. The end-user documentation included with the redistribution, if any, must
    include  the following  acknowledgment:  "This product includes  software
    developed  by the  Apache Software Foundation  (http://www.apache.org/)."
    Alternately, this  acknowledgment may  appear in the software itself,  if
    and wherever such third-party acknowledgments normally appear.

 4. The names "Fop" and  "Apache Software Foundation"  must not be used to
    endorse  or promote  products derived  from this  software without  prior
    written permission. For written permission, please contact
    [EMAIL PROTECTED]

 5. Products  derived from this software may not  be called "Apache", nor may
    "Apache" appear  in their name,  without prior written permission  of the
    Apache Software Foundation.

 THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
 APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
 INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
 DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
 OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
 ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
 (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 This software  consists of voluntary contributions made  by many individuals
 on  behalf of the Apache Software  Foundation and was  originally created by
 James Tauber <[EMAIL PROTECTED]>. For more  information on the Apache
 Software Foundation, please see <http://www.apache.org/>.

 */



// Java
import java.io.*;
import java.net.URL;
import java.util.Date;

import javax.servlet.*;
import javax.servlet.http.*;

// SAX
import org.xml.sax.XMLReader;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;


// FOP
import org.apache.fop.messaging.MessageHandler;
import org.apache.fop.configuration.Configuration;
import org.apache.fop.apps.Driver;
import org.apache.fop.apps.Version;


/**
 * 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/servlet/FopServlet?fo=/home/fop/example/readme.fo
 *
 */

public class FopStream extends HttpServlet
{
    public static final String FO_REQUEST_PARAM = "fo";

        /** show a full dump on error */
    private static boolean errorDump = false;

    public void doPost(HttpServletRequest request,
                      HttpServletResponse response)
        throws ServletException, IOException {

        //String foFile = request.getParameter(FO_REQUEST_PARAM );
        String fo = request.getParameter(FO_REQUEST_PARAM );

        response.setContentType( "text/pdf" );
        OutputStream outBin = response.getOutputStream();

        try {
            if (fo != null) {



                        Date date1 = new Date();

                        this.run( fo, outBin );

                        Date date2 = new Date();
                        long elapsed = date2.getTime() - date1.getTime();



          }
          else {
                PrintWriter outPrint = response.getWriter();

                outPrint.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);
        }
   }

   public void run( String fo, OutputStream outBin) {
        Driver driver = new Driver();
        if (errorDump) {
            driver.setErrorDump(true);
        }
        /*if (userConfigFile != null) {
            driver.loadUserconfiguration(userConfigFile);
        }*/
        //driver.setBaseDir(fo);

        /*if (dumpConfiguration) {
            Configuration.dumpConfiguration();
            System.exit(0);
        }*/

        String version = Version.getVersion();
        MessageHandler.logln(version);

        XMLReader parser = createParser();

        if (parser == null) {
            MessageHandler.errorln("ERROR: Unable to create SAX parser");
            System.exit(1);
        }

        // setting the parser features
        try {
            parser.setFeature("http://xml.org/sax/features/namespace-prefixes";,
                              true);
        } catch (SAXException e) {
            MessageHandler.errorln("Error in setting up parser feature
namespace-prefixes");
            MessageHandler.errorln("You need a parser which supports SAX
version 2");
            if (errorDump) {
                e.printStackTrace();
            }
            System.exit(1);
        }

        try {
            driver.setRenderer("org.apache.fop.render.pdf.PDFRenderer",
                               Version.getVersion());

driver.addElementMapping("org.apache.fop.fo.StandardElementMapping");
            driver.addElementMapping("org.apache.fop.svg.SVGElementMapping");

driver.addElementMapping("org.apache.fop.extensions.ExtensionElementMapping");
driver.addPropertyList("org.apache.fop.fo.StandardPropertyListMapping");

driver.addPropertyList("org.apache.fop.svg.SVGPropertyListMapping");

driver.addPropertyList("org.apache.fop.extensions.ExtensionPropertyListMapping")
;
            //driver.buildFOTree(parser, fileInputSource(fo));
            driver.buildFOTree(parser, new InputSource( new StringReader(
fo ) ) );
            driver.format();
            driver.setOutputStream( outBin );
            driver.render();
        } catch (Exception e) {
            MessageHandler.errorln("FATAL ERROR: " + e.getMessage());
            if (errorDump) {
                e.printStackTrace();
            }
            System.exit(1);
        }
    }

   /**
       * creates a SAX parser, using the value of org.xml.sax.parser
       * defaulting to org.apache.xerces.parsers.SAXParser
       *
       * @return the created SAX parser
       */
    static XMLReader createParser() {
        String parserClassName = System.getProperty("org.xml.sax.parser");
        if (parserClassName == null) {
            parserClassName = "org.apache.xerces.parsers.SAXParser";
        }
        org.apache.fop.messaging.MessageHandler.logln(
          "using SAX parser " + parserClassName);

        try {
            return (XMLReader) Class.forName(
                     parserClassName).newInstance();
        } catch (ClassNotFoundException e) {
            org.apache.fop.messaging.MessageHandler.errorln(
              "Could not find " + parserClassName);
            if (errorDump) {
                e.printStackTrace();
            }
        }
        catch (InstantiationException e) {
            org.apache.fop.messaging.MessageHandler.errorln(
              "Could not instantiate " + parserClassName);
            if (errorDump) {
                e.printStackTrace();
            }
        }
        catch (IllegalAccessException e) {
            org.apache.fop.messaging.MessageHandler.errorln(
              "Could not access " + parserClassName);
            if (errorDump) {
                e.printStackTrace();
            }
        }
        catch (ClassCastException e) {
            org.apache.fop.messaging.MessageHandler.errorln(
              parserClassName + " is not a SAX driver");
            if (errorDump) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
       * create an InputSource from a file name
       *
       * @param filename the name of the file
       * @return the InputSource created
       */
    public static InputSource fileInputSource(String filename) {

        /* this code adapted from James Clark's in XT */
        File file = new File(filename);
        String path = file.getAbsolutePath();
        String fSep = System.getProperty("file.separator");
        if (fSep != null && fSep.length() == 1)
            path = path.replace(fSep.charAt(0), '/');
        if (path.length() > 0 && path.charAt(0) != '/')
            path = '/' + path;
        try {
            return new InputSource(new URL("file", null, path).toString());
        } catch (java.net.MalformedURLException e) {
            throw new Error("unexpected MalformedURLException");
        }
    }

}

----------
Steve Lane
Vice President
Chris Moyer Consulting, Inc.
833 West Chicago Ave Suite 203
(312) 433-2421
http://www.fmpro.com



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

Reply via email to