I wrote my own XML->PDF FOP servlet.  Here is the code.

Maris

----------------------------------
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;

import org.xml.sax.InputSource;
import org.apache.fop.apps.Driver;
import org.apache.fop.apps.Version;
import org.apache.fop.apps.XSLTInputHandler;
import org.apache.fop.messaging.MessageHandler;

import lv.datapro.lad.pri.utils.*;

/* this package is added to enable configuration of FOP
by adding Latvian fonts */
import org.apache.fop.configuration.*;
import org.apache.avalon.framework.logger.ConsoleLogger;
import org.apache.avalon.framework.logger.Logger;

/**
 * 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>
 */
public class FopServlet extends HttpServlet implements SingleThreadModel
{
    Logger log = null;
    org.apache.log4j.Category log4j = org.apache.log4j.Category.getInstance("LADPRI");

    DataAccessSingleton singleton = DataAccessSingleton.getInstance();
    String hostNameAndPath = "";

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    {
        XsltThread xsltThread = null;
        PipedOutputStream pipedOutput = null;
        PipedInputStream pipedInput = null;

        if(log == null)
        {
            log = new ConsoleLogger(ConsoleLogger.LEVEL_WARN);
            MessageHandler.setScreenLogger(log);
        }

        log4j.debug("FopServlet invoked");
        try
        {
            if (this.hostNameAndPath.equals(""))
            {
                this.hostNameAndPath = 
DataAccessSingleton.getEnviromentString("WEB.HOST_NAME_PATH");
            }

            String configParam = this.hostNameAndPath + request.getParameter("config");
            log4j.debug("FopServlet configParam " + configParam);
            String xmlParam = this.hostNameAndPath + request.getParameter("xhtml");
            log4j.debug("FopServlet xmlParam " + xmlParam);
            String xslParam = this.hostNameAndPath + request.getParameter("stils");
            log4j.debug("FopServlet xslParam " + xslParam);
            String sessionIdParam = 
request.getParameter(DataAccessSingleton.SESSION_ID_PARAM);
            log4j.debug("FopServlet sessionIdParam " + sessionIdParam);
            String jsessionIdParam = request.getParameter("jsessionid");
            log4j.debug("FopServlet jsessionIdParam " + jsessionIdParam);
            if (jsessionIdParam != null) {
                this.hostNameAndPath = 
DataAccessSingleton.getEnviromentString("WEB.HOST_NAME_PROXY");
            }


            ConfigurationReader reader = new ConfigurationReader(new 
InputSource(configParam));

            reader.start();

            if (Utility.stringIsNull(xmlParam) || Utility.stringIsNull(xslParam))
            {
                throw new ServletException("xmlParam or xslParam is NULL");
            }

            pipedOutput = new PipedOutputStream();
            pipedInput = new PipedInputStream(pipedOutput);

            if (jsessionIdParam != null) {
                xsltThread = new XsltThread(xslParam,
                    xmlParam + ";" + "jsessionid=" + jsessionIdParam, pipedOutput);
            }
            else
                xsltThread = new XsltThread(xslParam,
                    xmlParam + "?" + DataAccessSingleton.SESSION_ID_PARAM + "=" + 
sessionIdParam, pipedOutput);

            xsltThread.start();

            log4j.debug("rendering...");
            renderFO(new InputSource(pipedInput), response);
            log4j.debug("rendering done");
        }
        catch(Exception ex)
        {
            log4j.error("Exception in FopServlet ", ex);
            ex.printStackTrace();
            try
            {
                PrintWriter out = response.getWriter();
                
out.println("<html><head><title>Error</title></head>\n<body><h1>FopServlet Error</h1> 
<p> "+ex.getMessage()+" </p></body></html>");
                out.flush();
            } catch (IOException e)
            {
                log4j.error("Cant write output, IOException in FopServlet ", e);
            }
        } finally
        {
            try
            {
                if (xsltThread!=null)
                {
                    xsltThread.youAreDone();
                    xsltThread.join(1000);
                }
                if (pipedInput!=null)
                {
                    pipedInput.close();
                }
            } catch (Exception ex)
            {
                log.error("Exception in FOP servlet ",ex);
            }
        }
    }

    /**
     * renders an FO inputsource into a PDF file which is rendered
     * directly to the response object's OutputStream
     */
    public void renderFO(InputSource foFile, HttpServletResponse response) throws 
ServletException
    {
        try
        {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.setContentType("application/pdf");
            Driver driver = new Driver(foFile, out);
            driver.setLogger(log);
            driver.setRenderer(Driver.RENDER_PDF);
            driver.run();
            byte[] content = out.toByteArray();

            response.setHeader("Expires", "-1");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setContentLength(content.length);
            response.getOutputStream().write(content);
            response.getOutputStream().flush();
        }
        catch(Exception ex)
        {
            log4j.error("Exception in renderFO ", ex);
            ex.printStackTrace();
            throw new ServletException(ex);
        }
    }
}

------------------------------------------

import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import org.xml.sax.SAXException;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

public class XsltThread extends Thread
{
    org.apache.log4j.Category log = org.apache.log4j.Category.getInstance("LADPRI");
    private String xslLocationULR, xmlLocationURL;
    private java.io.OutputStream outStream;
    private boolean canStop = false;

    public XsltThread(String xslLocationULR, String 
xmlLocationURL,java.io.OutputStream outStream)
    {
        this.xslLocationULR = xslLocationULR;
        this.xmlLocationURL = xmlLocationURL;
        this.outStream = outStream;
        this.canStop = false;
    }

    public void run()
    {
        log.debug("XsltThread started");
        int time10nthSec = 50;              // timeout 5 sec.
        try
        {
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer(new 
StreamSource(this.xslLocationULR));
            transformer.transform(new StreamSource(this.xmlLocationURL), new 
StreamResult(this.outStream));
            while (!this.canStop && time10nthSec>0)
            {
                time10nthSec--;
                Thread.currentThread().sleep(100);
            }
        } catch (Exception ex)
        {
            log.error("Exception in XsltThread ",ex);
            ex.printStackTrace();
        } finally
        {
            try
            {
                outStream.flush();
                outStream.close();
            } catch (java.io.IOException ex)
            {
            }
        }
        log.debug("XsltThread stopped");
    }

    public void youAreDone()
    {
        this.canStop = true;
    }
}

> -----Original Message-----
> From: Pani, Gourav [mailto:[EMAIL PROTECTED]]
> Sent: Wednesday, January 22, 2003 3:17 PM
> To: 'Struts Users Mailing List'
> Subject: RE: XML to PDF(need sample servlet code...)
> 
> 
> i posted sample code on this thread yesterday.
> 
> -----Original Message-----
> From: [EMAIL PROTECTED]
> [mailto:[EMAIL PROTECTED]]
> Sent: Wednesday, January 22, 2003 3:32 AM
> To: [EMAIL PROTECTED]
> Subject: RE: XML to PDF(need sample servlet code...)
> 
> 
> Hi,
> Do u have any sample code of a servlet that does the same?I 
> tried to use the
> 
> FOP servlet given with FOP distribution..But i keep on 
> getting null pointer 
> exceptions...
> 
> Any help will be appreciated..
> 
> regards,
> Shirish.
> 
> -----Original Message-----
> From: madhavan [mailto:[EMAIL PROTECTED]]
> Sent: Wednesday, January 22, 2003 12:45 AM
> To: struts-user
> Cc: madhavan
> Subject: [OT}RE: XML to PDF
> 
> 
> Hi
> 
> I used Apache FOP and XSLT to convert XML to pdf.
> 
> Regards
> Madhavan
> 
> -----Original Message-----
> From: V. Cekvenich [mailto:[EMAIL PROTECTED]]
> Sent: Tuesday, January 21, 2003 2:27 PM
> To: [EMAIL PROTECTED]
> Subject: Re: XML to PDF
> 
> 
> Yet another alternative:
> JasperReports and iText.
> 
> Yan, Charlene wrote:
> > Hello all,
> > 
> > I just got assigned to convert XML to pdf to do reports.  
> Is any of you 
> working on it?  Any insights where I should get started my 
> research?  I am 
> looking at xmlmil and aparche xml home right now.
> > 
> > Thanks in advance for your help!
> > 
> > Charlene
> 
> 
> 
> --
> To unsubscribe, e-mail:
> <mailto:[EMAIL PROTECTED]>
> For additional commands, e-mail:
> <mailto:[EMAIL PROTECTED]>
> 
> 
> --
> To unsubscribe, e-mail:
> <mailto:[EMAIL PROTECTED]>
> For additional commands, e-mail:
> <mailto:[EMAIL PROTECTED]>
> 
> 
> 
> --
> To unsubscribe, e-mail:
> <mailto:[EMAIL PROTECTED]>
> For additional commands, e-mail:
> <mailto:[EMAIL PROTECTED]>
> 
> --
> To unsubscribe, e-mail:   
<mailto:[EMAIL PROTECTED]>
For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>


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

Reply via email to