1 28 package net.sf.jasperreports.j2ee.servlets; 29 30 import java.awt.Dimension ; 31 import java.io.IOException ; 32 import java.util.List ; 33 34 import javax.servlet.ServletException ; 35 import javax.servlet.ServletOutputStream ; 36 import javax.servlet.http.HttpServletRequest ; 37 import javax.servlet.http.HttpServletResponse ; 38 39 import net.sf.jasperreports.engine.JRElement; 40 import net.sf.jasperreports.engine.JRException; 41 import net.sf.jasperreports.engine.JRImage; 42 import net.sf.jasperreports.engine.JRImageRenderer; 43 import net.sf.jasperreports.engine.JRPrintImage; 44 import net.sf.jasperreports.engine.JRRenderable; 45 import net.sf.jasperreports.engine.JRWrappingSvgRenderer; 46 import net.sf.jasperreports.engine.export.JRHtmlExporter; 47 import net.sf.jasperreports.engine.util.JRTypeSniffer; 48 49 50 54 public class ImageServlet extends BaseHttpServlet 55 { 56 57 58 61 public static final String IMAGE_NAME_REQUEST_PARAMETER = "image"; 62 63 64 67 public void service( 68 HttpServletRequest request, 69 HttpServletResponse response 70 ) throws IOException , ServletException 71 { 72 byte[] imageData = null; 73 String imageMimeType = null; 74 75 String imageName = request.getParameter(IMAGE_NAME_REQUEST_PARAMETER); 76 if ("px".equals(imageName)) 77 { 78 try 79 { 80 JRRenderable pxRenderer = 81 JRImageRenderer.getInstance( 82 "net/sf/jasperreports/engine/images/pixel.GIF", 83 JRImage.ON_ERROR_TYPE_ERROR 84 ); 85 imageData = pxRenderer.getImageData(); 86 } 87 catch (JRException e) 88 { 89 throw new ServletException (e); 90 } 91 } 92 else 93 { 94 List jasperPrintList = BaseHttpServlet.getJasperPrintList(request); 95 96 if (jasperPrintList == null) 97 { 98 throw new ServletException ("No JasperPrint documents found on the HTTP session."); 99 } 100 101 JRPrintImage image = JRHtmlExporter.getImage(jasperPrintList, imageName); 102 103 JRRenderable renderer = image.getRenderer(); 104 if (renderer.getType() == JRRenderable.TYPE_SVG) 105 { 106 renderer = 107 new JRWrappingSvgRenderer( 108 renderer, 109 new Dimension (image.getWidth(), image.getHeight()), 110 JRElement.MODE_OPAQUE == image.getMode() ? image.getBackcolor() : null 111 ); 112 } 113 114 imageMimeType = JRTypeSniffer.getImageMimeType(renderer.getImageType()); 115 116 try 117 { 118 imageData = renderer.getImageData(); 119 } 120 catch (JRException e) 121 { 122 throw new ServletException (e); 123 } 124 } 125 126 if (imageData != null && imageData.length > 0) 127 { 128 if (imageMimeType != null) 129 { 130 response.setHeader("Content-Type", imageMimeType); 131 } 132 response.setContentLength(imageData.length); 133 ServletOutputStream ouputStream = response.getOutputStream(); 134 ouputStream.write(imageData, 0, imageData.length); 135 ouputStream.flush(); 136 ouputStream.close(); 137 } 138 } 139 140 141 } 142 | Popular Tags |