Jasper Reports - Example

Jasper Reports is one of the best 'Business Intelligence (BI)' tools/frameworks, which can be used for generating reports for Java/Groovy applications. It is just partly 'Open Source', but if you can practice or have good enough work experience in Java, you can easily build basic/complex reports.

'Jasper Reports' framework can handle different kinds of data sources, but in this post I will show how to generate a basic report, just by passing a collection of Java data objects (Java beans), to the Jasper Report Engine. Below is the code for the data object (Java bean):

package com.chetty.reporting.beans;

public class DataBean {
private String name;
private String occupation;
private String place;
private String country;

public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setOccupation(String occupation) {
this.occupation = occupation;
}

public String getOccupation() {
return occupation;
}

public void setPlace(String place) {
this.place = place;
}

public String getPlace() {
return place;
}

public void setCountry(String country) {
this.country = country;
}

public String getCountry() {
return country;
}
}


And below is the code for the class file with business logic to generate a collection of java bean objects, which is further passed to the Jasper report engine, to generate the report:

package com.chetty.reporting.business;

import java.util.ArrayList;

import com.chetty.reporting.beans.DataBean;

public class DataBeanMaker {
public ArrayList getDataBeanList() {
ArrayList dataBeanList = new ArrayList();

//dataBeanList.add(produce("Babji, Chetty", "Engineer", "Nuremberg", "Germany"));
dataBeanList.add(produce("Albert Einstein", "Engineer", "Ulm", "Germany"));
dataBeanList.add(produce("Alfred Hitchcock", "Movie Director", "London", "UK"));
dataBeanList.add(produce("Wernher Von Braun", "Rocket Scientist", "Wyrzysk",                                               "Poland (Previously Germany)"));
dataBeanList.add(produce("Sigmund Freud", "Neurologist", "Pribor", "Czech Republic (Previously Austria)"));
dataBeanList.add(produce("Mahatma Gandhi", "Lawyer", "Gujarat", "India"));
dataBeanList.add(produce("Sachin Tendulkar", "Cricket Player", "Mumbai", "India"));
dataBeanList.add(produce("Michael Schumacher", "F1 Racer", "Cologne", "Germany"));

return dataBeanList;
}

private DataBean produce(String name, String occupation, String place, String country) {
DataBean dataBean = new DataBean();

dataBean.setName(name);
dataBean.setOccupation(occupation);
dataBean.setPlace(place);
dataBean.setCountry(country);

return dataBean;
}
}


And below is the main class file, which gets the java bean collection from the class (with business logic) and passes it to the Jasper report engine, to generate the report:

package com.chetty.reporting.engine;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.chetty.reporting.beans.DataBean;
import com.chetty.reporting.business.DataBeanMaker;
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;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

public class Reporter {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
InputStream inputStream = new FileInputStream ("reports/test_jasper.jrxml");

DataBeanMaker dataBeanMaker = new DataBeanMaker();
ArrayList dataBeanList = dataBeanMaker.getDataBeanList();

JRBeanCollectionDataSource beanColDataSource = new 
JRBeanCollectionDataSource(dataBeanList);

Map parameters = new HashMap();

JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);
JasperExportManager.exportReportToPdfFile(jasperPrint, "c:/reports/test_jasper.pdf"); 
}
}


To design the jasper report design file, you can either use iReport or the JasperAssistant Plugin for Eclipse. I used iReport, as it has more features and options. You can find the jasper report design file here: test_jasper.jrxml

When you run the 'Reporter' class, the following pdf file is generated:

Test Jasper

You can find all the source files here: jaspertest

45 comments:

  1. naveed ahmad khanApril 10, 2010 at 3:48 AM

    t was preeti good site then other when i visited last month
    and got good information about work from home


    work from home

    ReplyDelete
  2. thk u very much....... this code is really useful
    by jamuna

    ReplyDelete
  3. Thanks for the example.
    I have a more complex example:
    My report have a main JavaBean object Person that display properties in the header section and a collection of addresses that should be displayed in the details section.
    Please help me deal with this situation.

    ReplyDelete
    Replies
    1. for the header, you can define parameters in the report like:

      < parameter name="Name" class="java.lang.String" />

      in the class where you create the report, instead of sending empty HashMap send a Map with the parameters you need.

      Map< String, Object> parameters = new HashMap< String, Object>();
      parameters.put("Name", user.getFullname());

      and provide the parameters object to the method fillReport.

      Delete
  4. Excellent code, to start with. Very nice and simple.Thanks

    ReplyDelete
  5. Thanks for sharing, But I am getting error that

    Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/digester/Digester at Reporter.main(Reporter.java:38)
    Caused by: java.lang.ClassNotFoundException: org.apache.commons.digester.Digester

    in "JasperDesign jasperDesign = JRXmlLoader.load(inputStream)" line do you have any idea about this error? thanks for reply.

    ReplyDelete
    Replies
    1. It is clear from the exception message that the apache's common's digester library is missing. Check out jasper report library's dependencies and include all of 'em in your project.

      Delete
  6. This comment has been removed by the author.

    ReplyDelete
  7. Wonderful and so simple :) :)
    thnx very much ;)

    ReplyDelete
  8. When i have run this code than one problem occur :
    Exception in thread "main" java.lang.NoClassDefFoundError: org/codehaus/groovy/control/CompilationFailedException

    Please help me and also give the suggestion for grouping in report.

    ReplyDelete
    Replies
    1. Open the jrxml file in iReport designer and change the language property from "Groovy" to "JAVA". If you aren't using the iReport designer, just edit that 'language' property directly in the jrxml file.

      Delete
  9. The following links were supplementary to the material above and were useful to me apart from the good tutorial.

    http://www.installationwiki.org/JasperReports#JDT_Compiler

    Use any missing jars based on errors from JasperReports.zip from the lib folder inside.

    ReplyDelete
  10. What version of JasperReport do you use in this sample?

    ReplyDelete
    Replies
    1. I guess, it was 3.5 version. Its been a while..huh! :)

      Delete
  11. This comment has been removed by the author.

    ReplyDelete
  12. Nice article and well explained. I have small query though. How can we have alternate shading for the table rows?

    ReplyDelete
    Replies
    1. You can find my answer here: http://stackoverflow.com/questions/8980439/alternating-row-color-for-jasperreports/8995472#8995472

      Delete
  13. hi,
    if we are using table instead of grid,then what would be the datasource expression in jrxml file?

    for example in java,
    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, new JRBeanCollectionDataSource(Person.getReportData()));

    ReplyDelete
  14. please help me in this error I have done as the code above
    but it can't load file
    here is line caused error:
    JasperDesign design= JRXmlLoader.load(input);
    and this error
    java.lang.NoClassDefFoundError: org/apache/commons/digester/Digester
    at testjasper.FiilingReportWithData.main(FiilingReportWithData.java:37)


    ReplyDelete
    Replies
    1. Please check the comment from 'gltknbtn', above. It was already discussed.

      Delete
  15. Excellent code, to start with. Very nice and simple.Thanks

    ReplyDelete
  16. Does anyone know of a way to pass parameters from iReport to the Java Bean that is creating the Java Collection returned to the report?

    ReplyDelete
  17. I am getting error message as below.Please help me

    Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/collections/ArrayStack
    at org.apache.commons.digester.Digester.(Digester.java:142)
    at net.sf.jasperreports.engine.xml.JRXmlDigester.(JRXmlDigester.java:62)
    at net.sf.jasperreports.engine.xml.JRXmlDigesterFactory.createDigester(JRXmlDigesterFactory.java:957)
    at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:203)
    at com.Reporter.main(Reporter.java:32)
    Caused by: java.lang.ClassNotFoundException: org.apache.commons.collections.ArrayStack
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 5 more


    ReplyDelete
  18. getting below error...
    org.apache.commons.digester.Digester error
    SEVERE: Parse Error at line 13 column 12: cvc-complex-type.2.3: Element 'field' cannot have character [children], because the type's content type is element-only.
    org.xml.sax.SAXParseException: cvc-complex-type.2.3: Element 'field' cannot have character [children], because the type's content type is element-only.

    Could you help how to resolve, i had added the commons-digester-2.1.jar file on path.

    ReplyDelete
  19. Thanks a lot for the code. I had difficulties to find the necessary Jars but once I found them, code worked perfectly!

    Once again thanks!
    Selin

    ReplyDelete
  20. Can any one enter the jar file required for this example......

    ReplyDelete
    Replies
    1. Add below jar files in the buildpath.

      jasperreports-5.0.4.jar
      jasperreports-javaflow-5.0.4.jar
      itext-2.1.7.jar
      commons-beanutils-1.8.3.jar
      commons-collections-3.2.jar
      commons-digester-2.1.jar
      commons-logging-1.1.jar

      Delete
  21. Exception in thread "main" java.lang.AbstractMethodError: org.codehaus.groovy.control.CompilationUnit$ClassgenCallback.call(Lorg/objectweb/asm/ClassVisitor;Lorg/codehaus/groovy/ast/ClassNode;)V
    at org.codehaus.groovy.control.CompilationUnit$10.call(CompilationUnit.java:728)
    at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:925)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:462)
    at net.sf.jasperreports.compilers.JRGroovyCompiler.compileUnits(JRGroovyCompiler.java:109)
    at net.sf.jasperreports.engine.design.JRAbstractCompiler.compileReport(JRAbstractCompiler.java:201)
    at net.sf.jasperreports.engine.JasperCompileManager.compile(JasperCompileManager.java:240)
    at net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:490)
    at com.chetty.reporting.engine.Reporter.main(Reporter.java:41)
    Java Result: 1

    could you help me ??

    ReplyDelete
  22. no data will be displayed.... what is the reason. plz tell me.

    ReplyDelete
  23. no data will be displayed what is reason plz tell me.

    ReplyDelete
  24. Exception in thread "main" net.sf.jasperreports.engine.JRException: Error compiling report java source files : D:\WorkSpace\Mar01\JasperBean\scriptlet_1369744667126_499485.java
    at net.sf.jasperreports.engine.design.JRJavacCompiler.compileClasses(JRJavacCompiler.java:89)
    at net.sf.jasperreports.engine.design.JRAbstractClassCompiler.compileUnits(JRAbstractClassCompiler.java:63)
    at net.sf.jasperreports.engine.design.JRAbstractCompiler.compileReport(JRAbstractCompiler.java:188)
    at net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:215)
    at com.chetty.reporting.engine.Reporter.main(Reporter.java:33)
    Caused by: java.io.IOException: Cannot run program "javac": CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at net.sf.jasperreports.engine.design.JRJavacCompiler.compileClasses(JRJavacCompiler.java:58)
    ... 4 more
    Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)
    ... 8 more

    ReplyDelete
  25. Thank you very much, this is helpful for Beginners :D

    ReplyDelete
  26. Thank for this tutorial
    You can invoke jasper reports in two ways

    http://www.javatips.net/blog/2011/09/call-jasper-report-ireport-from-java-application

    ReplyDelete
  27. Thank U for This Example plz help me how to make this file and which jar file download to this net.sf.jasperreports.engine.JasperCompileManager;

    ReplyDelete
  28. Thanks mate, this really help me get up and running.

    ReplyDelete
  29. You can also design the jasper report using DynamicReports. This tool allows to create dynamic report designs at runtime.
    http://www.dynamicreports.org

    ReplyDelete
  30. When I run your code, I received the following error. Could you tell me why..

    log4j:WARN No appenders could be found for logger (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
    log4j:WARN Please initialize the log4j system properly.

    ReplyDelete
  31. HTML tutorial for beginners with examples

    Free online HTML tutorial for beginners with examples - HTML tutorial will help you in creating website, after study the tutorial you will just one step ahead of creating your own website. HTML is easy to understand and you will enjoy it to learn. HTML tutorial contains hundreds of examples to better understand.

    http://www.willvick.com/
    http://www.willvick.com/HTML-tutorial-for-beginners-with-examples/HTML-tutorial-for-beginners-with-examples.aspx

    ReplyDelete
  32. Thank a lot .....:0

    ReplyDelete
  33. when i try this example i am getting Could not find or load main clas Reporter

    ReplyDelete
  34. Hi Prashanth,

    Please upload the jar files and share path.

    I am trying your example am getting following error


    java.lang.NoSuchMethodError: com.lowagie.text.pdf.PdfWriter.setRgbTransparencyBlending(Z)V
    at net.sf.jasperreports.engine.export.JRPdfExporter.exportReportToStream(JRPdfExporter.java:484)
    at net.sf.jasperreports.engine.export.JRPdfExporter.exportReport(JRPdfExporter.java:383)
    at net.sf.jasperreports.engine.JasperExportManager.exportReportToPdfFile(JasperExportManager.java:126)
    at com.chetty.reporting.engine.Reporter.main(Reporter.java:41)

    Please help me

    ReplyDelete
  35. I was very new to jasper , even new to Reporting.....WOW it worked like a magic :)

    Akhilesh

    ReplyDelete
  36. This blog provides the basic fundamental of JAVA and also provides the important functions of java concept.The interested candidate can use this site...
    Tutorial In Noida

    ReplyDelete
  37. Exception in thread "main" java.lang.NoSuchMethodError: com.lowagie.text.pdf.PdfWriter.setRgbTransparencyBlending(Z)V

    ReplyDelete
  38. Hi it is a nice article. I am new for reports. I understand everything in here but I didnt get the file "test_jasper.jrxml", what is it? How design design file? can you please tell about that.

    ReplyDelete