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 name Data type
id int
first_name varchar(50)
last_name varchar(50)
date date

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

About the Author

author image
Ricardo Mariaca
Founder of DynamicReports.

Comments

Leave a Reply

avatar
newest oldest most voted
ramakrishna
Guest
ramakrishna

good post

ram krish
Guest
ram krish

ram krish
Guest
ram krish
not able to write thai characters to jasper report ? package ram.krish; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRExporterParameter; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; import net.sf.jasperreports.engine.export.JRXlsExporter; public class JasperReportFill_Export { @SuppressWarnings(“unchecked”) public static void main(String[] args) { String sourceFileName = “F:\workspace\JasperTest\src\main\java\ram\krish\jasper_report_template.jasper”; String printFileName = null; DataBeanList DataBeanList = new DataBeanList(); ArrayList dataList = DataBeanList.getDataBeanList(); JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList); Map parameters = new HashMap(); /** * Passing ReportTitle and Author as parameters */ parameters.put(“ReportTitle”, “List of Contacts”); parameters.put(“Author”, “Prepared By Manisha”); try { printFileName = JasperFillManager.fillReportToFile(sourceFileName, parameters, beanColDataSource); if (printFileName != null) { /** * 1-… Read more »
ram krish
Guest
ram krish

Kevin
Guest
Kevin

Good post for beginners! Thanks!

ELONG
Guest
ELONG
MKYONG, Have you tried the above code on a google cloud platform? I have a code that I used to generate the pdf file is as below: JRPdfExporter exporter = new JRPdfExporter(); URL fileUrl = this.getClass().getResource(repName); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(fileUrl); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, connection); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos); exporter.exportReport(); baos.close(); return new String(Base64.encodeBase64(baos.toByteArray())); The returned string was bind to “” It can work in other server including Amazon AWS but it failed to display the pdf file in google cloud platform. I have tested the code on google cloud platform & it seems like the pdf file… Read more »
anthony
Guest
anthony

dynamicreports programming style is horrable!

Adolphus Ald
Guest
Adolphus Ald

Currently, I’m using wffweb framework to generate html report pages but it can not generate pdf / excel. Can you please post a tutorial for creating pdf / excel reports with html generated by wffweb framework?

Diego Nieto
Guest
Diego Nieto

I have a web application running on tomcat 7, the report is created successful, and is shown in the JasperViewer, but when I close the report it also stops my tomcat server (it seems that kills the JVM process), what I can do to avoid this problem?

Thanks a lot.

Nitin Singhal
Guest
Nitin Singhal

how to give dynamic name to the report

satish
Guest
satish
Lahiru Yahampath Silva
Guest
Lahiru Yahampath Silva

im using dynamic report adhoc template. but i do not have an idea how to change header and set diffrent background color to each cell, depend on cell value. please help me if you can

thnaks.

Angad Yadav
Guest
Angad Yadav

How to apply Bold and Italic style for partial text in Jasper? For example : This is Sample text to be printed

Aditya Bhardwaj
Guest
Aditya Bhardwaj
KodandaRamu
Guest
KodandaRamu

hi, please provide an article that takes the data from morethan one table and generates the report using Dynamic reports.

Pranesh Patil
Guest
Pranesh Patil

Hi Thanks for that simple code.

I am facing error when I compile using command prompt and run the code,The report shows up in Java swing pdf viewer.But I am unable to save the file to my desktop.Below is the part of error i got(from command prompt):

Exception in thread “main” java.lang.NoSuchMethodError: com.itextpdf.text.Document.setRole(Lcom/itextpdf/text/pdf/PdfName;)V
at net.sf.jasperreports.engine.export.JRPdfExporter.exportReportToStream
(JRPdfExporter.java:580)
at net.sf.jasperreports.engine.export.JRPdfExporter.exportReport(JRPdfEx
porter.java:519)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.export(Jaspe
rReportBuilder.java:630)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.toPdf(Jasper
ReportBuilder.java:532)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.toPdf(Jasper
ReportBuilder.java:528)
at SimpleReportExample.main(SimpleReportExample.java:53)

Anybody please let me know how to resolve this issue.Thanks in advance

Subodh
Guest
Subodh

I am facing problem in ‘report.show();’ statement. While as a description of error it is showing one note which is “This element neither has attached source nor attached Javadoc and hence no
Javadoc could be found.” Now what should I do? Does it require any other library?

Ahmed
Guest
Ahmed

I am also facing problem in report.show();
Please help me.

Guest
Guest
Guest

Thank you. I got what I wanted.

Prafulla Amrutkar
Guest
Prafulla Amrutkar
I m trying to call a jasper report file from java servlet api in eclipse luna and my error is……… net.sf.jasperreports.engine.JRException: java.io.FileNotFoundException: F:Eclipse Project Workspace.metadata.pluginsorg.eclipse.wst.server.coretmp0wtpwebapps ………………E:Eclipse project workspace………………………..WebContentreceipts.jasper at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:115) at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:104) at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:580) at net.sf.jasperreports.engine.JasperRunManager.runToPdf(JasperRunManager.java:456) at net.sf.jasperreports.engine.JasperRunManager.runReportToPdf(JasperRunManager.java:871) at api.receipts.doGet(receipts.java:70) at javax.servlet.http.HttpServlet.service(HttpServlet.java:620) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source) Caused by: java.io.FileNotFoundException: F:Eclipse Project Workspace.metadata.pluginsorg.eclipse.wst.server.coretmp0wtpwebapps……………E:Eclipse project workspace…………………………………….WebContentreceipts.jasper … 28 more . Please… Read more »
Shaunak J
Guest
Shaunak J

Hie, dats a great one… helped me alot to understand it….

Now only problm with this example with me is…. alignment of column id and date are right aligned…
as shwn in ur scrnshot its perfectly center aligned…

i have used the xactly same code as u have given….
possibly please help me wit this…

vvkkumar
Guest
vvkkumar

Exception in thread “AWT-EventQueue-0” java.lang.NoSuchMethodError: net.sf.jasperreports.engine.util.JRLoader.getLocationInputStream(Ljava/lang/String;)Ljava/io/InputStream;

karan
Guest
karan

hey,
I wan to use i-net crystal clear report with java(servlet/jsp).
Can u help me how to do it with java?

Sakti
Guest
Sakti

Thank you very much for the terrific explanation and sample code.

fazal khaliq
Guest
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.

Anony
Guest
Anony

Add commons lib jar in your lib folder.

Samarendra P
Guest
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
Guest
lewinskki nnkingz

add MySql driver to your classpath

Ali
Guest
Ali

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

Ankit
Guest
Ankit

good stuff, very helpful for me..

emad
Guest
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
Guest
emad

Please Help Me . :(

Steve
Guest
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
Guest
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