1 28 package net.sf.jasperreports.j2ee.servlets; 29 30 import java.io.ByteArrayOutputStream ; 31 import java.io.IOException ; 32 import java.io.OutputStream ; 33 import java.util.List ; 34 35 import javax.servlet.ServletException ; 36 import javax.servlet.ServletOutputStream ; 37 import javax.servlet.http.HttpServletRequest ; 38 import javax.servlet.http.HttpServletResponse ; 39 40 import net.sf.jasperreports.engine.JRException; 41 import net.sf.jasperreports.engine.JRExporterParameter; 42 import net.sf.jasperreports.engine.export.JRPdfExporter; 43 44 45 49 public class PdfServlet extends BaseHttpServlet 50 { 51 52 53 56 public void service( 57 HttpServletRequest request, 58 HttpServletResponse response 59 ) throws IOException , ServletException 60 { 61 List jasperPrintList = BaseHttpServlet.getJasperPrintList(request); 62 63 if (jasperPrintList == null) 64 { 65 throw new ServletException ("No JasperPrint documents found on the HTTP session."); 66 } 67 68 Boolean isBuffered = Boolean.valueOf(request.getParameter(BaseHttpServlet.BUFFERED_OUTPUT_REQUEST_PARAMETER)); 69 if (isBuffered.booleanValue()) 70 { 71 JRPdfExporter exporter = new JRPdfExporter(); 72 exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST, jasperPrintList); 73 74 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 75 exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos); 76 77 try 78 { 79 exporter.exportReport(); 80 } 81 catch (JRException e) 82 { 83 throw new ServletException (e); 84 } 85 86 byte[] bytes = baos.toByteArray(); 87 88 if (bytes != null && bytes.length > 0) 89 { 90 response.setContentType("application/pdf"); 91 response.setContentLength(bytes.length); 92 ServletOutputStream ouputStream = response.getOutputStream(); 93 94 try 95 { 96 ouputStream.write(bytes, 0, bytes.length); 97 ouputStream.flush(); 98 } 99 finally 100 { 101 if (ouputStream != null) 102 { 103 try 104 { 105 ouputStream.close(); 106 } 107 catch (IOException ex) 108 { 109 } 110 } 111 } 112 } 113 } 124 else 125 { 126 response.setContentType("application/pdf"); 127 128 JRPdfExporter exporter = new JRPdfExporter(); 129 exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST, jasperPrintList); 130 131 OutputStream ouputStream = response.getOutputStream(); 132 exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream); 133 134 try 135 { 136 exporter.exportReport(); 137 } 138 catch (JRException e) 139 { 140 throw new ServletException (e); 141 } 142 finally 143 { 144 if (ouputStream != null) 145 { 146 try 147 { 148 ouputStream.close(); 149 } 150 catch (IOException ex) 151 { 152 } 153 } 154 } 155 } 156 } 157 158 159 } 160 | Popular Tags |