KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > FopPrintServlet


1 /*
2  * $Id: FopPrintServlet.java,v 1.1.2.2 2003/02/25 16:06:45 jeremias Exp $
3  * ============================================================================
4  * The Apache Software License, Version 1.1
5  * ============================================================================
6  *
7  * Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without modifica-
10  * tion, are permitted provided that the following conditions are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * 3. The end-user documentation included with the redistribution, if any, must
20  * include the following acknowledgment: "This product includes software
21  * developed by the Apache Software Foundation (http://www.apache.org/)."
22  * Alternately, this acknowledgment may appear in the software itself, if
23  * and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. The names "FOP" and "Apache Software Foundation" must not be used to
26  * endorse or promote products derived from this software without prior
27  * written permission. For written permission, please contact
28  * apache@apache.org.
29  *
30  * 5. Products derived from this software may not be called "Apache", nor may
31  * "Apache" appear in their name, without prior written permission of the
32  * Apache Software Foundation.
33  *
34  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
35  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
36  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
37  * APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
38  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
39  * DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
40  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
41  * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
42  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
43  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44  * ============================================================================
45  *
46  * This software consists of voluntary contributions made by many individuals
47  * on behalf of the Apache Software Foundation and was originally created by
48  * James Tauber <jtauber@jtauber.com>. For more information on the Apache
49  * Software Foundation, please see <http://www.apache.org/>.
50  */

51 import java.io.*;
52 import java.util.Vector JavaDoc ;
53
54 import java.awt.print.PrinterJob JavaDoc ;
55 import java.awt.print.PrinterException JavaDoc ;
56
57 import javax.servlet.*;
58 import javax.servlet.http.*;
59
60 import org.xml.sax.InputSource JavaDoc;
61
62 import org.apache.fop.apps.Driver;
63 import org.apache.fop.layout.Page;
64 import org.apache.fop.apps.XSLTInputHandler;
65 import org.apache.fop.messaging.MessageHandler;
66
67 import org.apache.fop.render.awt.AWTRenderer ;
68
69 import org.apache.avalon.framework.logger.ConsoleLogger;
70 import org.apache.avalon.framework.logger.Logger;
71
72 /**
73  * Example servlet to generate a fop printout from a servlet.
74  * Printing goes to the default printer on host where the servlet executes.
75  * Servlet param is:
76  * <ul>
77  * <li>fo: the path to a formatting object file to render
78  * </ul>
79  *
80  * Example URL: http://servername/fop/servlet/FopPrintServlet?fo=readme.fo
81  * Example URL: http://servername/fop/servlet/FopPrintServlet?xml=data.xml&xsl=format.xsl
82  * Compiling: you will need
83  * - servlet_2_2.jar
84  * - fop.jar
85  * - sax api
86  * - avalon-framework-x.jar (where x is the version found the FOP lib dir)
87  *
88  * Running: you will need in the WEB-INF/lib/ directory:
89  * - fop.jar
90  * - batik.jar
91  * - avalon-framework-x.jar (where x is the version found the FOP lib dir)
92  * - xalan-2.0.0.jar
93  */

94
95 public class FopPrintServlet extends HttpServlet {
96     public static final String JavaDoc FO_REQUEST_PARAM = "fo";
97     public static final String JavaDoc XML_REQUEST_PARAM = "xml";
98     public static final String JavaDoc XSL_REQUEST_PARAM = "xsl";
99     Logger log = null;
100
101     public void doGet(HttpServletRequest request,
102                       HttpServletResponse response) throws ServletException {
103         if (log == null) {
104             log = new ConsoleLogger(ConsoleLogger.LEVEL_WARN);
105             MessageHandler.setScreenLogger(log);
106         }
107
108         try {
109             String JavaDoc foParam = request.getParameter(FO_REQUEST_PARAM);
110             String JavaDoc xmlParam = request.getParameter(XML_REQUEST_PARAM);
111             String JavaDoc xslParam = request.getParameter(XSL_REQUEST_PARAM);
112
113             if (foParam != null) {
114                 FileInputStream file = new FileInputStream(foParam);
115                 renderFO(new InputSource JavaDoc(file), response);
116             } else if ((xmlParam != null) && (xslParam != null)) {
117                 XSLTInputHandler input =
118                   new XSLTInputHandler(new File(xmlParam),
119                                        new File(xslParam));
120                 renderXML(input, response);
121             } else {
122                 response.setContentType ("text/html");
123
124                 PrintWriter out = response.getWriter();
125                 out.println("<html><title>Error</title>\n"+ "<body><h1>FopServlet Error</h1><h3>No 'fo' or 'xml/xsl' "+
126                             "request param given.</h3></body></html>");
127             }
128         } catch (ServletException ex) {
129             throw ex;
130         }
131         catch (Exception JavaDoc ex) {
132             throw new ServletException(ex);
133         }
134     }
135
136     /**
137      * Renders an FO inputsource to the default printer.
138      */

139     public void renderFO(InputSource JavaDoc foFile,
140                          HttpServletResponse response) throws ServletException {
141         try {
142             Driver driver = new Driver(foFile, null);
143             PrinterJob JavaDoc pj = PrinterJob.getPrinterJob();
144             PrintRenderer renderer = new PrintRenderer(pj);
145
146             driver.setLogger (log);
147             driver.setRenderer(renderer);
148             driver.run();
149
150             reportOK (response);
151         } catch (Exception JavaDoc ex) {
152             throw new ServletException(ex);
153         }
154     }
155
156     /**
157      * Renders an FO generated using an XML and a stylesheet to the default printer.
158      */

159     public void renderXML(XSLTInputHandler input,
160                           HttpServletResponse response) throws ServletException {
161         try {
162             Driver driver = new Driver();
163             PrinterJob JavaDoc pj = PrinterJob.getPrinterJob();
164             PrintRenderer renderer = new PrintRenderer(pj);
165
166             pj.setCopies(1);
167
168             driver.setLogger (log);
169             driver.setRenderer (renderer);
170             driver.render (input.getParser(), input.getInputSource());
171
172             reportOK (response);
173         } catch (Exception JavaDoc ex) {
174             throw new ServletException(ex);
175         }
176     }
177
178     // private helper, tell (browser) user that file printed
179
private void reportOK (HttpServletResponse response)
180     throws ServletException {
181         String JavaDoc sMsg =
182           "<html><title>Success</title>\n" + "<body><h1>FopPrintServlet: </h1>" +
183           "<h3>The requested data was printed</h3></body></html>" ;
184
185         response.setContentType ("text/html");
186         response.setContentLength (sMsg.length());
187
188         try {
189             PrintWriter out = response.getWriter();
190             out.println (sMsg);
191             out.flush();
192         } catch (Exception JavaDoc ex) {
193             throw new ServletException(ex);
194         }
195     }
196
197     // This is stolen from PrintStarter
198
class PrintRenderer extends AWTRenderer {
199
200         private static final int EVEN_AND_ALL = 0;
201         private static final int EVEN = 1;
202         private static final int ODD = 2;
203
204         private int startNumber;
205         private int endNumber;
206         private int mode = EVEN_AND_ALL;
207         private int copies = 1;
208         private PrinterJob JavaDoc printerJob;
209
210         PrintRenderer(PrinterJob JavaDoc printerJob) {
211             super(null);
212
213             this.printerJob = printerJob;
214             startNumber = 0 ;
215             endNumber = -1;
216
217             printerJob.setPageable(this);
218
219             mode = EVEN_AND_ALL;
220             String JavaDoc str = System.getProperty("even");
221             if (str != null) {
222                 try {
223                     mode = Boolean.valueOf(str).booleanValue() ? EVEN : ODD;
224                 } catch (Exception JavaDoc e) {}
225
226             }
227         }
228
229         public void stopRenderer(OutputStream outputStream)
230         throws IOException {
231             super.stopRenderer(outputStream);
232
233             if (endNumber == -1)
234                 endNumber = getPageCount();
235
236             Vector JavaDoc numbers = getInvalidPageNumbers();
237             for (int i = numbers.size() - 1; i > -1; i--)
238                 removePage(
239                   Integer.parseInt((String JavaDoc) numbers.elementAt(i)));
240
241             try {
242                 printerJob.print();
243             } catch (PrinterException JavaDoc e) {
244                 e.printStackTrace();
245                 throw new IOException("Unable to print: " +
246                                       e.getClass().getName() + ": " + e.getMessage());
247             }
248         }
249
250         public void renderPage(Page page) {
251             pageWidth = (int)((float) page.getWidth() / 1000f);
252             pageHeight = (int)((float) page.getHeight() / 1000f);
253             super.renderPage(page);
254         }
255
256
257         private Vector JavaDoc getInvalidPageNumbers() {
258
259             Vector JavaDoc vec = new Vector JavaDoc();
260             int max = getPageCount();
261             boolean isValid;
262             for (int i = 0; i < max; i++) {
263                 isValid = true;
264                 if (i < startNumber || i > endNumber) {
265                     isValid = false;
266                 } else if (mode != EVEN_AND_ALL) {
267                     if (mode == EVEN && ((i + 1) % 2 != 0))
268                         isValid = false;
269                     else if (mode == ODD && ((i + 1) % 2 != 1))
270                         isValid = false;
271                 }
272
273                 if (!isValid)
274                     vec.add(i + "");
275             }
276
277             return vec;
278         }
279     } // class PrintRenderer
280

281 }
282
283
Popular Tags