Printing reports with Java, with jasperReports and iReoprts
Just few years ago, printing in Java was a painful task, but now with Java 2 and several (open source) tools you can create professional reports that can bring your software into higher level.
In this example, I will show you how to print simple report, but before that how to prepare report and setup your system to print properly.
We will use JasperReports, great open source software, you can download from http://jasperreports.sourceforge.net/, and we will also use iReport, intuitive, GUI tool for generating files (reports) that JasperReports will print for you. iReport is available from http://ireport.sourceforge.net/cap3.html.
Also, you need java Application server, with Tomcat. You can download it from Sun's site (http://java.sun.com/javaee/downloads/).
iReport generates XML files, and using Java you will call JasperReports to compile it and print them, or you even create HTML, PDF, or some other file. You can create XML file by yourself, but they have to be in proper format, and it is better to use iReport for you. You can add text, tables, images, even a charts, and all of elements that you can imagine.
A typical file that JasperReport uses, contains the following elements:
1. - the root element.
2. - its contents are printed only once at the beginning of the report
3. - its contents are printed at the beginning of every page in the report.
4. - contains the body of the report.
5. - its contents are printed at the bottom of every page in the report.
6. - defines a report section, all of the above elements contain a band element as its only child element.
All of those are optional, except for the root jasperReport element.
Here is a development screen of iReport.
iReport development screen
When you finish designing your report in iReport, just save it as XML file on hard drive (ie. in root of C partition, to be easy accessable).
Now, before we create Java code to print this report, it is important to include several jar files into classpath of your application server, and those are:
All of those libraries, you will find in JasperReports Project file. It is not good idea to include them from JDeveloper, due to version dependencies.
Finally, code that will print your report, file printMyReport.java:
public class printMyReport
public static void main(String args)
jasperReport = JasperCompileManager.compileReport("c:\\myFirstReport.xml");
jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap(), new JREmptyDataSource());
JasperPrintManager.printPage(jasperPrint, 0, true);
catch (Exception e)
This is only a basic example of how to create and print reports. In a while I will explain how to create reports using data from databases.