Passing an image in Parameter Map to Jasper Report


In this tutorial I am going to explain how to pass an image in Parameter Map to Jasper Reports from the Java Servlet.
  1. Create the Table in MySQL Database:

    CREATE TABLE image (             
           id int(5) NOT NULL auto_increment,  
           firstname varchar(25) default NULL,      
           lastname varchar(20) default NULL,      
           image blob,                         
           email varchar(50) default NULL,     
           PRIMARY KEY  (`id`)                   
     );
    
  2. Insert the row into Table in MySQL Database:

    insert into image(firstname, lastname, image, email)  values('Sumanth', 'Garakarajula', 'C:/image.jpg', 'sumanth@codesuggestions,com');
    
  3. To connect MySQL database from Java/ JSP we need to have the MySQL JDBC Drivers. Download the jar from the following link: http://dev.mysql.com/downloads/connector/j/5.0.html. In this tutorial we are using the mysql-connector-java-5.0.8-bin.jar file.
  4. Create the Jasper Template in iReport. In the report create a parameter and its type is java.awt.Image. You can drag an Image element from the report palette, and the Image property expression is the Parameter name. ${ParameterName}

    ImageReport.jrxml
    
    <?xml version="1.0" encoding="UTF-8"?>
    <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="report name" pageWidth="595" pageHeight="842" columnWidth="535" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
     <property name="ireport.zoom" value="1.0"/>
     <property name="ireport.x" value="0"/>
     <property name="ireport.y" value="0"/>
     <parameter name="CLIENT_IMAGE" class="java.awt.Image" isForPrompting="false">
      <defaultValueExpression><![CDATA[]]></defaultValueExpression>
     </parameter>
     <queryString>
      <![CDATA[]]>
     </queryString>
     <background>
      <band splitType="Stretch"/>
     </background>
     <title>
      <band height="79" splitType="Stretch">
       <staticText>
        <reportElement x="75" y="20" width="462" height="42"/>
        <textElement>
         <font size="16" isBold="true"/>
        </textElement>
        <text><![CDATA[Displaying the Image from the Database using Property]]></text>
       </staticText>
      </band>
     </title>
     <pageHeader>
      <band height="35" splitType="Stretch"/>
     </pageHeader>
     <columnHeader>
      <band height="61" splitType="Stretch"/>
     </columnHeader>
     <detail>
      <band height="125" splitType="Stretch">
       <image isUsingCache="false">
        <reportElement x="185" y="14" width="100" height="89"/>
        <imageExpression><![CDATA[$P{CLIENT_IMAGE}]]></imageExpression>
       </image>
      </band>
     </detail>
     <columnFooter>
      <band height="45" splitType="Stretch"/>
     </columnFooter>
     <pageFooter>
      <band height="54" splitType="Stretch"/>
     </pageFooter>
     <summary>
      <band height="42" splitType="Stretch"/>
     </summary>
    </jasperReport>
    
    
  5. Create a Servlet class to read the image from the database and pass the image as a parameter to the ImageReport Parameter Map object. Here is the code to compile the JRXML file and generating the report as a PDF file. Compiling the JRXML file using JasperCompileManager.compileReport() and passing the empty datasource instead of the Database connection to the report.

    ImageServlet.java
    
    
    import java.awt.image.BufferedImage;
    import java.io.ByteArrayOutputStream;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.util.HashMap;
    import java.util.Map;
    import javax.imageio.ImageIO;
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import net.sf.jasperreports.engine.JREmptyDataSource;
    import net.sf.jasperreports.engine.JasperCompileManager;
    import net.sf.jasperreports.engine.JasperExportManager;
    import net.sf.jasperreports.engine.JasperFillManager;
    import net.sf.jasperreports.engine.JasperPrint;
    import net.sf.jasperreports.engine.JasperReport;
    
    @WebServlet(urlPatterns = {"/ImageServlet"})
    public class ImageServlet extends HttpServlet {
    
        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("application/pdf");
            ServletOutputStream servletOutputStream = null;
            Connection conn = null;
            PreparedStatement pstmt = null;
            ResultSet rs = null;
            ByteArrayOutputStream baos = null;
            FileInputStream fis = null;
            String url = "jdbc:mysql://localhost:3306/test";
    
            try {
                servletOutputStream = response.getOutputStream();
                baos = new ByteArrayOutputStream();
                Map map = new HashMap();
                
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                conn = DriverManager.getConnection(url, "root", "");
                pstmt = conn.prepareStatement("SELECT image FROM image WHERE id = 1");
                rs = pstmt.executeQuery();
                InputStream imageStream = null;
                BufferedImage image = null;
                while(rs.next()){
                    imageStream = rs.getBinaryStream(1);
                    image = ImageIO.read(imageStream);
                }   
                System.out.println("image..." + image);
                map.put("CLIENT_IMAGE", image);
                
                String reportLocation = getServletContext().getRealPath("WEB-INF/reports");
                fis = new FileInputStream(reportLocation + "/ImageReport.jrxml");
                JasperReport jasperReport = JasperCompileManager.compileReport(fis);
                JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map, new JREmptyDataSource());
                JasperExportManager.exportReportToPdfStream(jasperPrint, baos);
                response.setContentLength(baos.size());
                baos.writeTo(servletOutputStream);
    
                fis.close();
                servletOutputStream.flush();
                servletOutputStream.close();            
                baos.close();
                
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try{
                    if(rs != null){
                        rs.close();
                    }
                    if(pstmt != null){
                        pstmt.close();
                    }
                    if(conn != null){
                        conn.close();
                    }
                }catch(Exception ex){
                    ex.printStackTrace();
                }
            }
        }
    }
    
    

No comments

Powered by Blogger.