Reporting in Java using DynamicReports and JasperReports

DynamicReports logo

This example shows how to generate a simple report using DynamicReports and JasperReports. DynamicReports is a Java reporting library that allows you to produce report documents that can be exported into many popular formats. It is based on the well-known JasperReports library.

Tools used in this article :

  1. DynamicReports 3.1.3
  2. JasperReports 5.0.4
  3. MySQL 5.5
  4. Maven 3
  5. JDK 1.6.0

1. Download DynamicReports

Download DynamicReports from official website. If you use Maven, you can download it from the Maven central repository. For Maven projects add the following configuration to pom.xml file:

pom.xml
<dependencies>
        <!-- DynamicReports -->
	<dependency>
		<groupId>net.sourceforge.dynamicreports</groupId>
		<artifactId>dynamicreports-core</artifactId>			
		<version>3.1.3</version>
	</dependency>
 
        <!-- MySQL database driver -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.25</version>
	</dependency>
</dependencies>

2. Report data source

Connect to a MySQL database using a JDBC driver.

Class.forName("com.mysql.jdbc.Driver");
Connection connection = 
  DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", "password");

3. Report builder

Let’s assume that the MySql server contains a database table customers and the customers table has the following structure:

Column nameData type
idint
first_namevarchar(50)
last_namevarchar(50)
datedate

We will create a report that will get all customers from the table and the data will be put into the report.

3.1 Create a new empty report object.

JasperReportBuilder report = DynamicReports.report();

3.2 Now create a report colum for each database column.

Columns.column("Customer Id", "id", DataTypes.integerType())

The first parameter is a column label that will be shown in the report header.
The second parameter is a column name, this name should be the same as the database column name.
The third parameter is a Java type of the column.

3.3 Add the report columns.

report
  .columns(
    Columns.column("Customer Id", "id", DataTypes.integerType()),
    Columns.column("First Name", "first_name", DataTypes.stringType()),
    Columns.column("Last Name", "last_name", DataTypes.stringType()),
    Columns.column("Date", "date", DataTypes.dateType()))

3.4 Add a title text and a page number to the report.

  .title(//title of the report
    Components.text("SimpleReportExample")
      .setHorizontalAlignment(HorizontalAlignment.CENTER))
  .pageFooter(Components.pageXofY())//show page number on the page footer

3.5 Finally set the data source query and connection.

  .setDataSource("SELECT id, first_name, last_name, date FROM customers ", connection);

4. Full Example

SimpleReportExample.java
package net.sf.dynamicreports.examples;
 
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 
import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.builder.DynamicReports;
import net.sf.dynamicreports.report.builder.column.Columns;
import net.sf.dynamicreports.report.builder.component.Components;
import net.sf.dynamicreports.report.builder.datatype.DataTypes;
import net.sf.dynamicreports.report.constant.HorizontalAlignment;
import net.sf.dynamicreports.report.exception.DRException;
 
public class SimpleReportExample {
 
  public static void main(String[] args) {
	Connection connection = null;
	try {
		Class.forName("com.mysql.jdbc.Driver");
		connection = DriverManager.getConnection(
                    "jdbc:mysql://hostname:port/dbname","username", "password");
	} catch (SQLException e) {
		e.printStackTrace();
		return;
	} catch (ClassNotFoundException e) {
		e.printStackTrace();
		return;
	}
 
	JasperReportBuilder report = DynamicReports.report();//a new report
	report
	  .columns(
	      Columns.column("Customer Id", "id", DataTypes.integerType()),
	      Columns.column("First Name", "first_name", DataTypes.stringType()),
	      Columns.column("Last Name", "last_name", DataTypes.stringType()),
	      Columns.column("Date", "date", DataTypes.dateType()))
	  .title(//title of the report
	      Components.text("SimpleReportExample")
		  .setHorizontalAlignment(HorizontalAlignment.CENTER))
		  .pageFooter(Components.pageXofY())//show page number on the page footer
		  .setDataSource("SELECT id, first_name, last_name, date FROM customers", 
                                  connection);
 
	try {
                //show the report
		report.show();
 
                //export the report to a pdf file
		report.toPdf(new FileOutputStream("c:/report.pdf"));
	} catch (DRException e) {
		e.printStackTrace();
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	}
  }
}

5. Run it

Run the SimpleReportExample class.

Figure : A pdf file will be created.

report

Download Source Code

Download it – JavaDynamicReports-Example.zip (11 KB)

References

  1. DynamicReports
  2. JasperReports
  3. DynamicReports – Getting started
  4. DynamicReports – Documentation
Tags :

About the Author

Ricardo Mariaca
Founder of DynamicReports.

Comments

  • fazal khaliq

    Exception in thread “main” java.lang.NoClassDefFoundError: org/apache/commons/collections/ReferenceMap
    at net.sf.jasperreports.extensions.DefaultExtensionsRegistry.(DefaultExtensionsRegistry.java:97)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
    at java.lang.Class.newInstance0(Class.java:372)
    at java.lang.Class.newInstance(Class.java:325)
    at net.sf.jasperreports.engine.util.ClassUtils.instantiateClass(ClassUtils.java:59)
    at net.sf.jasperreports.extensions.ExtensionsEnvironment.createDefaultRegistry(ExtensionsEnvironment.java:81)
    at net.sf.jasperreports.extensions.ExtensionsEnvironment.(ExtensionsEnvironment.java:69)
    at net.sf.jasperreports.engine.DefaultJasperReportsContext.getExtensions(DefaultJasperReportsContext.java:246)
    at net.sf.jasperreports.engine.fonts.FontUtil.getFontInfo(FontUtil.java:185)
    at net.sf.jasperreports.engine.fonts.FontUtil.getAwtFontFromBundles(FontUtil.java:245)
    at net.sf.dynamicreports.design.transformation.StyleResolver.getFont(StyleResolver.java:96)
    at net.sf.dynamicreports.design.transformation.StyleResolver.getFont(StyleResolver.java:71)
    at net.sf.dynamicreports.design.transformation.StyleResolver.getFontHeight(StyleResolver.java:52)
    at net.sf.dynamicreports.design.transformation.TemplateTransform.getTextFieldHeight(TemplateTransform.java:967)
    at net.sf.dynamicreports.design.transformation.ComponentTransform.textField(ComponentTransform.java:332)
    at net.sf.dynamicreports.design.transformation.ComponentTransform.component(ComponentTransform.java:152)
    at net.sf.dynamicreports.design.transformation.ComponentTransform.list(ComponentTransform.java:285)
    at net.sf.dynamicreports.design.transformation.BandTransform.band(BandTransform.java:184)
    at net.sf.dynamicreports.design.transformation.BandTransform.transform(BandTransform.java:74)
    at net.sf.dynamicreports.design.base.DRDesignReport.transform(DRDesignReport.java:135)
    at net.sf.dynamicreports.design.base.DRDesignReport.(DRDesignReport.java:107)
    at net.sf.dynamicreports.design.base.DRDesignReport.(DRDesignReport.java:99)
    at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.toJasperReportDesign(JasperReportBuilder.java:261)
    at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.getJasperParameters(JasperReportBuilder.java:288)
    at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.toJasperPrint(JasperReportBuilder.java:299)
    at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.show(JasperReportBuilder.java:328)
    at jasper.Jasper.main(Jasper.java:59)
    Caused by: java.lang.ClassNotFoundException: org.apache.commons.collections.ReferenceMap
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    … 30 more
    Java Result: 1

    -commons-collections-3.2.1.jar
    -commons-lang3-3.1.jar
    -commons-logging-1.1.1.jar
    -jasperreports-5.1.4.jar
    -dynamicReports 3.1.5.jar
    -MySQL 5.1.13

    please help me.

    thanks in advance.

  • Samarendra P

    ava.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:190)
    at pdfreport.Pdfreport.main(Pdfreport.java:24)

    This is my problem. Cant understand it.. Any Help ???

    • lewinskki nnkingz

      add MySql driver to your classpath

  • Ali

    Can we create reports in different formats like rich text document?

  • http://www.studytonight.com Ankit

    good stuff, very helpful for me..

  • emad

    use from your code . but show below errors :

    Exception in thread “main” java.lang.NoClassDefFoundError: net/sf/jasperreports/engine/JRException
    at net.sf.dynamicreports.report.builder.DynamicReports.report(DynamicReports.java:120)
    at SimpleReportExample.main(SimpleReportExample.java:39)
    Caused by: java.lang.ClassNotFoundException: net.sf.jasperreports.engine.JRException
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    … 2 more
    Java Result: 1

    • emad

      Please Help Me . :(

    • http://steveperkins.info Steve

      The JasperReports jar is missing from your classpath. Since DynamicReports is really just an extension of JasperReports, you must have the JasperReports jar on your classpath when using DynamicReports.

    • lewinskki nnkingz

      Exception in thread “main” java.lang.NoClassDefFoundError: net/sf/jasperreports/engine/JRExceptio
      missing net/sf/jaspereports jar. Download http://mvnrepository.com/artifact/net.sf.jasperreports/jasperreports/3.7.5 and add it to you class path