JasperReports Tutorial
Jasper Report is an open source java reporting engine, is Java based and doesn't have its own expression syntax.
As JasperReports is a Java class library, and is not meant for end users, but rather is targeted towards Java developers who need to add reporting capabilities to their applications
Report template
Generally the following report layout is followed to generate reports by many of the commercial report generating tools.
Following is the description of each element mentioned in the diagram.
Element | Description |
---|---|
title | Title contains the title of the report. It appears only once at the very beginning of the report, for example, "Tutorials Point Report". |
pageHeader | PageHeader may contain date and time information and/or organization name. This appears at top of each page. |
columnHeader | ColumnHeader lists the names of those specific fields which you want to display in the report, for example, "Author Name", "Starting Hour", "Finishing Hour", "Hours Worked" and "Date" etc. |
detail | Detail is the part where entries of the specific fields (listed in columnHeader) are shown, for example "Manisha", "9:00", "18:00", "9", "10.02.2013". |
columnFooter | ColumnFooter may display summation of any of the fields, for example, "Total Hours Worked: 180" |
pageFooter | PageFooter may contain page count information. It appears at the bottom of each page, for example, "1/23". |
summary | Summary contains information inferred from "detail" part, for example, After the number listing of worked hours for each author, total hours worked for each author can be put in visual chart like pie chart, graph, etc for better comparison. |
Jasper Report
Common troubles faced during report development are summarized in the points below:
-
Core changes: To reflect the business changes or enhancements it usual to change the core logic of the report.
-
Results exporting: There are a wide range of formats which your report can be exported to, such as: HTML, text, PDF, MS Excel, RTF, ODT, Comma-separated values, XML or image.
-
Complicated reports: sub-reports and cross-tabs reports are good example.
Charts reports: Visual chart for example. Graph, Pie,XY Line, Bar, Meter and Time series
- Download and
install iReports from http://jasperforge.org/projects/ireport (We use this to create
the report template/layout) and this website will give you a very very clear idea on how to design a
report template. Trust me, its easy. It’s easy to understand it from their own
website rather me trying to explain it in words.
- Download and
install MySQL
- Have the following
jar files in your classpath
Core changes: To reflect the business changes or enhancements it usual to change the core logic of the report.
Results exporting: There are a wide range of formats which your report can be exported to, such as: HTML, text, PDF, MS Excel, RTF, ODT, Comma-separated values, XML or image.
Complicated reports: sub-reports and cross-tabs reports are good example.
- commons-beanutils-1.7.jar
- commons-collections-3.1.jar
- commons-digester-1.8.jar
- commons-lang-2.1.jar
- commons-logging-1.1.jar
- iText-2.1.1.jar
- jasperreports-1.0.3.jar
- mysql-connector-java-5.0.4-bin.jar
Note: The
template that we create using iReport tool will be saved with extension .jrxml
Create a
folder jrxml in your project and save/copy the template you designed here.
Create a
folder report in your project and this is where your PDF/EXCEL report will be
saved
Step 1: Define a Person.java POJO class as defined below. This is the Java bean data source that is going to provide the data to the report.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.mycompany.app.jasper;
public
class
Person
{
private
String firstName;
private
String surname;
private
Integer age;
public
String getFirstName()
{
return
firstName;
}
public
void
setFirstName(String firstName)
{
this
.firstName = firstName;
}
public
String getSurname()
{
return
surname;
}
public
void
setSurname(String surname)
{
this
.surname = surname;
}
public
Integer getAge()
{
return
age;
}
public
void
setAge(Integer age)
{
this
.age = age;
}
@Override
public
String toString()
{
return
"Person [firstName="
+ firstName +
", surname="
+ surname +
", age="
+ age +
"]"
;
}
}
Step 2: Download Jaspersoft iReport 5.0.0, and execute the ireport.exe from the iReport folder (e.g. C:\ireport\5.0.0\iReport-5.0.0\bin). You need to design the template now using iReport 5.0.0 and generate theperson-template.jrxml, which will be used in Java as the template to generate the report.
Step 3: Tell iReport where to find the classes by defining the class path via Tools --> Option, and then select the "Classpath" tab.
Step 4: Create a new report via File --> New.
provide the name and path where you want to generate the template jrxml file.
Click on "Next" and then "Finish" to get the designer screen where you can add labels and text fields for the report.
Step 5: Add the column header for the report by dragging and dropping the "Static Text" for the column headers.
Step 6: Before you can map the Text Field with bean data source values, you need to bring in the Person java class we created in Step 1.Click on the little data source icon as shown below to get the pop up that allows you to define the com.mycompany.app.jasper.Person bean and select the firstName, surname, and age and select on "Add selected fields" and then click on "OK".
Step 7: Now you can map these fields to the new "Text Field" that you drag and drop as shown below. This will be done in the "detail1" section.
Step 8: Now, you need to map each Text Field to the corresponding fields of Person.java. You do this by Right-clicking and selecting "Edit expression" on the field.
Step 9: In the "expression editor", you can map the field. Remove the default $F{Field} and "double-click" on "firstName" to get $F{firstName} and click on "Apply" as shown below.
Step 10: Map all the fields as shown below, and click on the icon that compiles the design to generate the person-template.jrxml (text) and person-template.jasper (binary) files. If there are any compile errors, you need to fix it and re-compile. You only need the jrxml file to generate report in Java.
Step 11: Finally the Main.java that generates the report by combining the layout template person-template.jrxmland the data by executing the Main class.
package com.mycompany.app.jasper; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.LinkedList; import java.util.List; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperCompileManager; 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;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import net.sf.jasperreports.view.JasperViewer;
public
class
Main
{
public
static
JasperDesign jasperDesign;
public
static
JasperPrint jasperPrint;
public
static
JasperReport jasperReport;
public
static
String reportTemplateUrl =
"person-template.jrxml"
;
public
static
void
main(String[] args) throws IOException
{
try
{
InputStream resourceAsStream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(reportTemplateUrl);
//get report file and then load into jasperDesign
jasperDesign = JRXmlLoader.load(resourceAsStream);
//compile the jasperDesign
jasperReport = JasperCompileManager.compileReport(jasperDesign);
//fill the ready report with data and parameter
jasperPrint = JasperFillManager.fillReport(jasperReport,
null
,
new
JRBeanCollectionDataSource(
findReportData()));
//view the report using JasperViewer
JasperViewer.viewReport(jasperPrint);
}
catch
(JRException e)
{
e.printStackTrace();
}
}
private
static
Collection findReportData()
{
//declare a list of object
List<Person> data =
new
LinkedList<Person>();
Person p1 =
new
Person();
p1.setFirstName(
"John"
);
p1.setSurname(
"Smith"
);
p1.setAge(Integer.valueOf(5));
data.add(p1);
return
data;
}
}
Finally, the report produced looks like
Note: iText jar is required to generate PDF reports. If you want to generate excel report, you need additional dependency jar like POI.
Step 12: For creating .txt file use this code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
| package com.mycompany.app.jasper; public class Person { private String firstName; private String surname; private Integer age; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this .firstName = firstName; } public String getSurname() { return surname; } public void setSurname(String surname) { this .surname = surname; } public Integer getAge() { return age; } public void setAge(Integer age) { this .age = age; } @Override public String toString() { return "Person [firstName=" + firstName + ", surname=" + surname + ", age=" + age + "]" ; } } |
Step 2: Download Jaspersoft iReport 5.0.0, and execute the ireport.exe from the iReport folder (e.g. C:\ireport\5.0.0\iReport-5.0.0\bin). You need to design the template now using iReport 5.0.0 and generate theperson-template.jrxml, which will be used in Java as the template to generate the report.
Step 5: Add the column header for the report by dragging and dropping the "Static Text" for the column headers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
| import net.sf.jasperreports.view.JasperViewer; public class Main { public static JasperDesign jasperDesign; public static JasperPrint jasperPrint; public static JasperReport jasperReport; public static String reportTemplateUrl = "person-template.jrxml" ; public static void main(String[] args) throws IOException { try { InputStream resourceAsStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(reportTemplateUrl); //get report file and then load into jasperDesign jasperDesign = JRXmlLoader.load(resourceAsStream); //compile the jasperDesign jasperReport = JasperCompileManager.compileReport(jasperDesign); //fill the ready report with data and parameter jasperPrint = JasperFillManager.fillReport(jasperReport, null , new JRBeanCollectionDataSource( findReportData())); //view the report using JasperViewer JasperViewer.viewReport(jasperPrint); } catch (JRException e) { e.printStackTrace(); } } private static Collection findReportData() { //declare a list of object List<Person> data = new LinkedList<Person>(); Person p1 = new Person(); p1.setFirstName( "John" ); p1.setSurname( "Smith" ); p1.setAge(Integer.valueOf(5)); data.add(p1); return data; } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.imlog.report;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.Map;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRTextExporter;
import net.sf.jasperreports.engine.export.JRTextExporterParameter;
public class TextFileOutPut {
public static void main(String[] args) throws Exception {
String sourceFileName ="D://sw//jrxml//imLogReport.jasper";
Map<String, Object> parameters = new HashMap<String, Object>();
/**
* Passing ReportTitle and Author as parameters
*/
parameters.put("userId", "anand");
parameters.put("cmpyName", "ABCD Company");
parameters.put("imagePath", "C:\\Users\\Anand\\Pictures\\2013-06\\green_forest.jpg");
parameters.put("with1", 111);
parameters.put("with2", "info");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "password");
JasperPrint jasperPrint = JasperFillManager.fillReport(sourceFileName, parameters,conn);
JRTextExporter exporter = new JRTextExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRTextExporterParameter.BETWEEN_PAGES_TEXT,"\\f");
/*CHAR_WIDTH = REPORT_WIDTH / MAX_CHAR_PER_ROW
CHAR_HEIGHT = REPORT_HEIGHT / MAX_CHAR_PER_COL
CHAR_WIDTH = 524 / 80 = 6.55
CHAR_HEIGHT = 524 / 44 = 11.9*/
exporter.setParameter(JRTextExporterParameter.CHARACTER_WIDTH,new Float(6.55));
exporter.setParameter(JRTextExporterParameter.CHARACTER_HEIGHT,new Float(11.9));
exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,"D://anand.txt");
exporter.exportReport();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
package com.imlog.report;
import java.sql.Connection; import java.sql.DriverManager; import java.util.HashMap; import java.util.Map; import net.sf.jasperreports.engine.JRExporterParameter; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.export.JRTextExporter; import net.sf.jasperreports.engine.export.JRTextExporterParameter; public class TextFileOutPut { public static void main(String[] args) throws Exception { String sourceFileName ="D://sw//jrxml//imLogReport.jasper"; Map<String, Object> parameters = new HashMap<String, Object>(); /** * Passing ReportTitle and Author as parameters */ parameters.put("userId", "anand"); parameters.put("cmpyName", "ABCD Company"); parameters.put("imagePath", "C:\\Users\\Anand\\Pictures\\2013-06\\green_forest.jpg"); parameters.put("with1", 111); parameters.put("with2", "info"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "password"); JasperPrint jasperPrint = JasperFillManager.fillReport(sourceFileName, parameters,conn); JRTextExporter exporter = new JRTextExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRTextExporterParameter.BETWEEN_PAGES_TEXT,"\\f"); /*CHAR_WIDTH = REPORT_WIDTH / MAX_CHAR_PER_ROW CHAR_HEIGHT = REPORT_HEIGHT / MAX_CHAR_PER_COL CHAR_WIDTH = 524 / 80 = 6.55 CHAR_HEIGHT = 524 / 44 = 11.9*/ exporter.setParameter(JRTextExporterParameter.CHARACTER_WIDTH,new Float(6.55)); exporter.setParameter(JRTextExporterParameter.CHARACTER_HEIGHT,new Float(11.9)); exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,"D://anand.txt"); exporter.exportReport(); } } |
Comments
Post a Comment