CREATING JASPER REPORTS WITH DYNAMIC IMAGES

This is a tutorial on how to embed images stored in a database (javaDB, MySQL,etc) into a jasper repors at runtime. This tutorial uses EJBs for creating an object for the table and its fields from the database. I’m also using Collection (List) of objects as the data source for the jasper reports. It is assumed the reader knows how to create reports using jasper reports.

The image field in the database table can be of data type blob, medium blob or long blob. In our entity class for the table, the datatype of the image (photo) field will be of the type byte [].Note that the image that will be sent to the report will be a type of java.awt.image, so therefore we create one additional field of type image in our class. In your code, create a method that converts a blob to image. (This can easily be done using image icon, as it accept blob and you can get image from it as well)

We will be using ireport 3.0, Netbeans 6.5 , Sun Application Server( because of me using session beans, but will not be necessary when creating desktop applications) as the development environment. Make sure to add the jasper report libraries to your projects.

Design your report by creating the necessary fields in the ireport.  Make sure the names of the field are the same as they appear in the entity class (the datasource) including capitalization as shown below

report1

In creating the fields, the image (photo) field should be of the type Object. After creating the image field, insert an image into your report from the ireport toolbar.  Then bind the image to the image (photo) field then you are done with the design of your report.

report3

Save your report. Note that the file type of your report can be .jrxml or .jasper. I’m using the .jasper as it removes the overhead of compiling it in your code in case it is .jrxml

Then you go to netbeans to do some small coding.

Write the code below under an actionevent

generateReports("StudentDetail", reportFactory.returnStudentsBySchool(s.getSchID()), param);

the “studentdetail” is the name of the report file, “param” is a map object which is used  incase you are filling part of your report with parameters (usually user imput). Parameters are also created the same way as creating fields but under the parameters section

Exxample of creating a map object in java

Map<String, Object> param = new HashMap<String, Object>();

param.put("school", “Abakrampa”); //school is the name of the parameter as it in the report inteface

“returnStudentsBySchool(s.getSchID())” is a method that returns a collection of the object (our datasource, and this is the detail

public static Collection returnStudentsBySchool(int schid) {

educationSSSSessionRemote session = lookupnewEducateFacadeBean();//session beans

List data = null;

List<StudentDetail> results = null;

data = session.findStudentBySchool(schid);// returns the students object with blob

ListIterator<StudentDetail> lstmb = data.listIterator();

results = new ArrayList<StudentDetail>();

// converting the byte[] to image type for all the student objects

ImageIcon n;

while (lstmb.hasNext()) {

StudentDetail s = lstmb.next();

if (s.getPicture() != null) {

n = new ImageIcon((byte[]) s.getPicture());

} else {

n = new ImageIcon();

}

s.setPhoto(n.getImage(),

results.add(s);

}

return results;

}

The generate report method

private void generateReports(String name, Collection data, Map param) {

try {

URL urlfilename = null;

String oSource = "reports/" + name;

String rSource = "reports/" + name + ".jasper";

urlfilename = getClass().getResource(rSource);

String reportfile = null;

if (urlfilename != null) {

reportfile = urlfilename.getPath();

} else {

return;

}

JRBeanCollectionDataSource jrbc = new JRBeanCollectionDataSource(data);

JasperPrint jasperPrint = JasperFillManager.fillReport(reportfile, param, jrbc);

JasperViewer.viewReport(jasperPrint, false);//"

// when the false is absent on closing the report it closes your java apllication

} catch (Exception e) {

e.printStackTrace();

System.out.println("reports Error  " + e.toString());

}   }

Below is a sample report when the app is run

report4

24 thoughts on “CREATING JASPER REPORTS WITH DYNAMIC IMAGES

  1. CREATING JASPER REPORTS WITH DYNAMIC IMAGES

    Please can you tell me how can i do this using mysql…
    i’m confused………..

    Please……..

    • the backed of this program is also mysql.
      for the image field the datatype should be blog.
      the java object of the table in the databse will be having imagebytes for the field with blog datatype. but in our jasper reports we want java.awt.image. So create additional field with type image

  2. I cannot understand this part please explain me or give me the mysql example..
    _________________________________________________
    ImageIcon n;

    while (lstmb.hasNext()) {

    StudentDetail s = lstmb.next();

    if (s.getPicture() != null) {

    n = new ImageIcon((byte[]) s.getPicture());

    } else {

    n = new ImageIcon();

    }

    s.setPhoto(n.getImage(),

    results.add(s);

    }

    return results;

    }

    _________________________________________________
    please this is urgent……..

    • In here we are converting the imagebytes to java.awt.image as i have explained in ur earlier comment
      In mysql we have a field picture with the datatype blog. so when converted to java object we get the data type byte[].
      but ireport is accepting image. so we create additional field image in our java object which will be pass to ireport. We then convert the imagebytes to image
      and pass it to our newly created field. StudentDetail is the class and out jasper report is accepting a collection of studentdetail which is the “result”

  3. Hi Gilbert,

    Thanks for reply soon..
    I can understand what you say,But the my point is
    what is this “s.getPicture()” and “s.setPhoto()”…

    Some times if i have that complete class i can understand.if you never mind please mail me(This is a request-I’m in very urgent)

    My email is – tozoysa@gmail.com

    Prasad
    SRILANKA,

  4. Gilbert Adjin, You are the man. This article is very helpful.

    You have mentioned “In creating the fields, the image (photo) field should be of the type Object.”. I think it should be java.awt.Image.

    Thanks again.

    • In creating the field by right clicking the field node “object” is the type you have to choose. But after you have created the field, draged a picture object and you are binding the picture to the field thus where you choose java.awt.Image

  5. hi Gilbert.
    When i fill the report I get a exception “java.lang.ClassCastException: sun.awt.image.ToolkitImage”. I think this heppens because the JREvaluator is to expect a text and receive an Image.
    Can you help me?

  6. Please can you tell me how to create a group. I have set more than five fields in a group. One field contains changes. how can i generate new groups so that the newly generated groups reflect the changes i made in one of the fields?

    thanks.

  7. Hi Gilbert!

    Very helpful article! I’ve tryed to implement this solution but I have a problem.

    I have a report including some subreport. The subreport that causes problems contains in the detail band an image, populated dinamically.

    Then I pass the image data from my java code.. and it works!

    With the given image size a page can contain 3 photos.

    But when the number of my photos requires a new page,the resultant pdf contains only the images of the last page and the previous pages contains no images (they are blank!)

    I’ve also noticed that the images are not all embedded in pdf, but only those displayed. The PDF with 4 images (resulting in the first page blank and the last page with 1 image) is smaller than PDF with 3 images (resulting in 1 page with 3 images).

    But the datasource contains the data of all the 4 images!!

    Have you got any solution? Thank you in advance!!!

    Marco

  8. Hi Gilbert,

    I am using netbeans IDE 6.9.1 and jasper report 3.7.4. i want to create dynamic report from the database for my project.

    help me.

    thanks in advance.

  9. Hi,

    I am using the jasperreport 4.0 for creating the pdf and jdk 1.5 for creating the pdf. I have make the changes according to your tutorial.

    Step 1. getting the image from the mysql data base.

    public Image getCustomer(){
    //byte customer_signature[] = null;
    Image customer_signature = null;

    FileInputStream fis = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
    Class.forName(“org.gjt.mm.mysql.Driver”);
    Connection conn = DriverManager.getConnection(“jdbc:mysql://susday888/erof”, “root”, “root”);
    String INSERT_PICTURE = “select cust_signature from table_name where country=?”;
    ps = conn.prepareStatement(INSERT_PICTURE);
    ps.setString(1, “China”);

    rs = ps.executeQuery();

    InputStream stream = rs.getBinaryStream(1);
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    int a1 = stream.read();
    while (a1 >= 0) {
    output.write((char) a1);
    a1 = stream.read();
    }
    Image myImage = Toolkit.getDefaultToolkit().createImage(output.toByteArray());
    output.close();
    customer_signature = myImage;

    }

    }catch(Exception e){
    e.printStackTrace();
    }

    finally {
    try{
    rs.close();
    }catch(Exception e){
    System.out.println(“exception in getting data”);
    }
    try{
    ps.close();
    }catch(Exception e){
    e.printStackTrace();
    }
    }
    return customer_signature;
    }

    Step 2. Object cust_signature_image = iptoMysql.getCustomer();
    or Image cust_signature_image = iptoMysql.getCustomer();

    STEP 3 put the cust_signature_image in
    Map jasperParameter = new HashMap();
    jasperParameter.put(“CUSTOMER_SIGNATURE_IMAGE”,cust_signature_image);

    STEP 4 In *jrxml i have made the corresponding changes
    in image expression —– $P{CUSTOMER_SIGNATURE_IMAGE}
    in Expression class ——- java.awt.Image

    But when i run the application for creating the pdf the following error is coming.

    net.sf.jasperreports.engine.JRException: Incompatible sun.awt.image.ToolkitImage value assigned to parameter CUSTOMER_SIGNATURE_IMAGE in the DSP dataset.
    at net.sf.jasperreports.engine.fill.JRFillDataset.setParameter(JRFillDataset.java:903)
    at net.sf.jasperreports.engine.fill.JRFillDataset.setFillParameterValues(JRFillDataset.java:642)
    at net.sf.jasperreports.engine.fill.JRFillDataset.setParameterValues(JRFillDataset.java:585)
    at net.sf.jasperreports.engine.fill.JRBaseFiller.setParameters(JRBaseFiller.java:1280)
    at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:901)
    at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:864)
    at net.sf.jasperreports.engine.fill.JRFiller.fillReport(JRFiller.java:84)
    at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:624)
    at com.ncr.eROF.report.DSP.main(DSP.java:315)

    Can any one suggest, where i have to make the changes. for displaying the image on the pdf.
    Thanks in advance.
    Chhote

  10. hi
    actully i want to get image on ireport and path of that image should be defined in backend(table)
    so hows it is possible
    please help..

  11. I like the valuable info you provide in your articles.
    I will bookmark your blog and check again here frequently.
    I am quite certain I’ll learn plenty of new stuff right here! Good luck for the next!

Leave a reply to Marco Cancel reply