JasperReports Tutorial: What is Jasper report for Java? Example
What is JasperReports for Java?
JasperReports is an open-source reporting tool for Java that is used for reporting of applications. This reporting tool helps in writing rich content onto the screen, to the printer, or into a variety of files like HTML, PDF, XLS, RTF, CSV, XML, ODT and TXT. JasperReports can also be used for Java-enabled applications like Java EE or web applications to generate dynamic content.
How to Install Jasper Reports- Environment Setup
Now in this Jaspersoft Studio tutorial, let’s learn the step by step process for JasperReports environment setup:
Step 1) Download jasper reports community edition Go to this Link and click on Download Now option to install Jasper Reports Community edition.
Step 2) Select Jaspersoft Studio CE From the community editions, Select Jaspersoft Studio CE
Step 3) Download Jaspersoft Studio Go to this link and click on Download button. open the download TIB_js-studiocomm_6.9.0_windows_x86_64.exe file.TIB_js-studiocomm_6.9.0_windows_x86_64.exe.
Step 4) Click on agree button Following screen will appear, select the I agree button.
Step 5) Choose location Select your installation location and click on Next button.
Step 6) Progress is running now You will see the progress on the next screen.
Step 7) Click on finish button In the next screen, click on the finish button.
Step 8) Progress is complete Following screen will appear in your window.
Step 9) Get Started Next, Click on Get started option.
Step 10) Start working with Jasper Reports studio Following screen will appear you can start working with Jasper Reports studio.
Why use Jasper Reports?
Here, are many reasons for using a Jasper report tool:
- It offers report generation performance and delivery to users.
- It helps you to represent your data in textual or graphical format.
- It is a standalone and embedded reporting server for reporting compilation and execution.
- It allows role-based access control to all reports in the repository.
- A spring security framework for integration with in-house authentication systems
- It offers secure, schedule, and automatic delivery interactive reporting engine.
- You can embed reports into Java or non-Java Application.
- Various formats of reports can be exported.
- Developers can supply data in multiple ways.
- It can generate watermarks that are laid over the primary image.
- It offers a complete set of SOAP , REST, and Web Services.
- It allows you to use single report data from multiple data sources.
Lifecycle of JasperReports
Now in this JasperReports tutorial, we will learn about Lifecycle of JasperReports.
Following are General flow of Life cycle of Jasper Reports:
Designing the report:
This will be the first step where we create the JRXML file. It is the file is a simple XML document which defines the report layout. You can develop this file using any text editor, or report designer.
However, if you are using the report designer, we can visualize the layout of the report, and the real structure of the JRXML should be ignored.
Compiling the report:
In this life cycle stage, the JRXML which is built in the first stage is compiled, and a binary object called the Jasper file (file with jasper xtn) is generated.
This compilation is done to get better performance during execution. These generated Jasper files should be shipped along with your application to run the reports.
Executing the report:
In this stage, the data from the application is gathered and filled in the compiled report format. There is a class called net.sf.jasperreports.engine.JasperFillManager which offers functions to fill the data in the reports.
The output will be stored in Jasper print file (file with jprint xtn) which can be used to print or export the report.
Exporting the report to the desired format:
In this last stage, you need to export the Jasper print file which is created earlier into any format using the class JasperExportManager. As Jasper offers multiple formats of exports, we can use the same input to create various representations of the data.
Features of Jasper Reports
Now, we will cover the features of JasperReports in this JasperReports step by step tutorial.
Here, are Important Features of Jasper Reports tool:
- Offers flexible report layout.
- It allows you to accept data from multiple data sources.
- Watermarks can also be applied.
- Multiple data sources can be used to transfer data.
- You can generate subreports
- It can generate subreports.
- It helps you to export reports in a variety of formats like PDF , HTML, RTF, Microsoft Excel files.
- The engine allows report definitions to include charts.
Jasper vs. Pentaho
Now, we will learn about the difference between Jasper and Pentaho in this Jasper Reporting tutorial.
Here are major differences between Jasper and Pentaho:
Creating a Report Template Example
Now in this JasperReports tutorial, let’s learn how to create a Report template in JasperReports.
The report template file used in JasperReports is a simple XML file having jrxml extension. This file contains the tag as its root element. JasperReports framework can handle different types of data sources.
Report template is designed and created using the following two steps –
Step 1) Creating the JRXML file in Jaspersoft Studio.
- Go to file option.
- Select the New sub-menu
- Click on Jasper Report option.
Step 2) Selecting the desired template.
- Select your template, for example, cherry.
- Click on the “Next” button.
Step 3) Selecting a parent folder.
- Select MyReports folder.
- Enter the file name, for example, “Cherry Report.”
Step 4) In Data Source window , click on “New” button to create new data adapter.
Step 5) Selecting a data adapter.
- Select data adapter from the list box. For example, “Collection of JavaBeans.”
Step 6) Entering data adapter details and selecting factory class.
- Enter a name for your adapter.
- Select factory class by clicking on the “…” button.
Step 7) Entering prefix or pattern.
- Enter the name prefix or pattern.
- Click matching items.
- Click on the “OK” button.
Step 8) Defining factory class and adding the path to jar files.
- Enter the name of a static method in the factory class. In this Jasper reports example, this is createBeanCollection.
- If your JavaBeans definition has field descriptions, and you would like to use these as names in Jaspersoft Studio, check use field description checkbox.
- Add a path to your jar files.
- Click on “Finish” button.
Step 9) Click on the “Next” button.
Step 10) Congratulations! You have added all necessary report creation information successfully. Click on “Finish” button.
The report will be generated as shown in below screen.
The above file requires to compile into JasperReport Binary format, which is called the jasper file.
The Interface net.sf.jasperreports.engine.design.JRCompiler, which is part of the JasperReports library, plays an important role in the compilation of this report template file.
You can compile a JRXML file in the following two methods:
- Programmatic compilation.
- Compilation using Apache ANT task.
Understanding the different report bands
Following are standard report format adopted by most of the commercial report generating tools.
- Page header
- Column header
- Column footer
- Page footer
Let’s Learn each reporting bands in detail:
This band is shown at the starting of the report. It can be used as the first page by setting the attribute isTitleNewPage="true."
Page header reporting band shown at the beginning of each page. It excludes the first page if the title band is used and the last page if this summary band is used with setting isSummaryWithPageHeaderAndFooter="false.".
Column headers appear before the detail band on each page.
Detail section iterated for each record in data source supplied. It also allowed having multiple detail band ( 1, 2, etc.)
This section appears below the detail band on each page where detail band is present. The default setting is the end of the page, but this can be switch to under last detail band by setting the attribute isFloatColumnFooter=" true."
This section will be displayed at the end of each page excluding summary band, title band, the and last non-summary band.
Last Page Footer:
This section appears on the previous page (if not a summary band is given) in place of normal page Footer.
The summary section only appears at the end of the report on a new page. when isSummaryNewPage="true" is set and with page header and footer is set isSummaryWithPageHeaderAndFooter="true".
This section only appears when it is defined every time the group expression change before the detail band.
This section only displays if a group is defined every time before the group expression change after the detail band.
It is displayed on all the pages as background to all other reporting bands.
This band will appear when no data source was passed, or the data source is empty and whenNoDataType=”NoDataSection” is set.
Challenges faced while creating JasperReports
Here, are a few challenges you will face while creating Jasper Reports:
- Core changes – The business changes or enhancements. It is required to change the core logic of the report.
- Complicated reports – sub-reports and cross-tabs reports are good’ example.
- Charts reports or Visual charts, for example, Graph, XY line, Pie, Bar, Time series, and Meter charts.
Disadvantages of using Jasper Reports
Here, are drawbacks/cons of using Jasper Reports.
- Once you start making any change with parts of the package and removing features, it’s very difficult to get back to the default package setting.
- It’s too rigid, editing of lines and creation of cross tabs is a challenging task.
- Some common task, like specifying sub-totals for a grouped report is easier in the other two report designers.
- Jasper requires that you compile reports before running them. This means that report developers must have the entire Java SDK installed.
- Sometimes when you edit the report, it does not show the same preview as it is displayed on the web.
- JasperReports is an open-source Java reporting engine. This Java class library offers reporting capabilities for your application.
- Jasper Reports offers report generation performance and delivery to users.
- Jasper Reports life cycle include 1) designing reports, 2) Compiling reports, 3) Executing the report, and 4) Exporting the report to the desired format.
- In Jasper Reports, you can create multiple data sources to transfer data.
- The major difference between Jasper and Pentaho is that Jasper reports uses a report for designing the reports while Pentaho uses the Pentaho Report Designer.
- The report template file used in JasperReports is a simple XML file having jrxml extension.
- Important Reports bands are: 1)Title 2) Page header 3) Column header 4) Detail 5) Column footer 6) Page footer and, 7) Summary.
- The biggest challenge of using Jasper Reports is that you need to change the core logic of the report if the business logic change.
- The biggest drawback of Jasper Reports is that when you make any change with parts of the package, it’s tough to get back to the default package setting.
- Program to Print Prime Number From 1 to 100 in Java
- Selection Sorting in Java Program with Example
- Abstract Class vs Interface in Java – Difference Between Them
- 100+ Java Interview Questions and Answers (2023)
- JAVA Tutorial PDF: Basics for Beginners (Download Now)
Java | Simple Jasper Report Example
JasperReports library is an open source reporting library written in Java. The library can export documents in different formats e.g. PDF, HTML, CSV…etc. This post shows a simple example of how to export PDF document using JasperReports.
Environment, Tools & Libraries used in this post
- Maven (build tool)
- jasperreports 6.10.0
- spring core 5.2.3.RELEASE
In order to generate a report we need to following inputs to be passed to Jasper exporting functions:
- Jasper Report Template: Jasper template is an XML .jrxml file that can be created using JasperSoft Studio .
- Parameters: This is a Java Map object containing a set of values passed from the application requesting the report. They can be used for runtime configuration or to pass additional custom data that is not part of the data source.
- Datasource: JasperReport engines expect an object of type JRDataSource as a data source. There several implementations of JRDataSource that allow to fetch data from different data source types such as databases, XML file, CSV file or Java beans.
In this post will export a PDF file using a List of Java bean Country as a data source. The template we are going to use report.jrxml is created using JasperSoft Studio.
Java bean country.java.
- We have one simple Java class Country that holds country’s code, name and URL to an image of the contry’s flag.
- The App.java class contains the main() method.
- getJasperReport() read & compiles .jrxml file.
- getParameters() returns the set of parameters.
- getDataSource() builds the data source .
Source Code @ GitHub
© 2018 hmkcode. All rights reserved.
- Enterprise Java
- Web-based Java
- Data & Java
- Project Management
- Visual Basic
- Ruby / Rails
- Java Mobile
- Architecture & Design
- Open Source
- Web Services
Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More .
Most commercial applications dealing with any form of data provide a way to publish reports from the application in some form or manner. And when this application uses data from the back-end database, JasperReport is ideal to publish them in variety of formats (PDF, Excel, XML etc.). How do we program them is the real question? If you want to hand design the report go for iReport and design a JRXML template otherwise you can go dynamic with DynamicJasper as we shall see down the line.
JasperReport library provides primarily two different usages to generate database reports.
1. Embedding SQL queries into a JRXML template.
2. Database reporting via data source.
Embedding SQL Queries into a JRXML Template
We can use the <queryString…> element to embed SQL queries into a JRXML file. The XML code for the report is as follows:
Listing 1: report1.jrxml
The java class to fill the report from the database and to view it is as follows
Listing 2: DataReport.java
Database Reporting via Data Source
Suppose we want to feed the SQL statement from Java code and not from a JRXML template. In that case remove the <queryString…> element from JRXML as shown in Listing 1 and write the code given in Listing 3 .
Listing 3: DataReport2.java
A Little Deviation
In our next application we are going to deviate a little while fiddling with – DynamicJasper , JasperReport , and Hibernate Library and integrate them to bring out the chemistry dynamic database reporting.
Listing 4: Entity bean Employee.java
Listing 5: Utility class for configuring Hibernate, HibernateUtil.java
Listing 6: Data Access object, EmployeeDao.java
Listing 7: Dynamic reporting class, EmployeeReport.java
Listing 8: main class to feed data into the database and show report, JavaDBReport2.java
The three sample applications demonstrate a few of the ways a report can be generated using the JasperReport library. The last application shows the unison of three important frameworks altogether and how to create a dynamic report from the database as well. Creating dynamic reports has one disadvantage. It is not possible to preview the looks of the report whereas we can see the preview to JRXML template at design time. Both ways are great; choose according to your requirement and preference.
Get the Free Newsletter!
Subscribe to Developer Insider for top news, trends & analysis
Understanding memory consistency in java threads, 5 best online courses for agile project managers in 2023, 6 best online courses for agile developers in 2023, 11 top icagile certifications for 2023, synchronization in java: a comprehensive guide, related stories, 11 java debugging best practices for 2023.
- JasperReports - Home
- JasperReports - Getting Started
- JasperReports - Environment Setup
- JasperReports - Life Cycle
- JasperReports - Designs
- JasperReports - Compiling Design
- JasperReports - Fillings
- JasperReports - View & Print
- JasperReports - Exporting
- JasperReports - Parameters
- JasperReports - Data Sources
- JasperReports - Fields
- JasperReports - Expression
- JasperReports - Variables
- JasperReports - Sections
- JasperReports - Groups
- JasperReports - Fonts
- JasperReports - Unicode Support
- JasperReports - Styles
- JasperReports - Scriptlets
- JasperReports - Create Subreports
- JasperReports - Creating Charts
- JasperReports - Crosstabs
- JasperReports - Internationalization
- JasperReports Resources
- JasperReports - Quick Guide
- JasperReports - Useful Resources
- JasperReports - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
JasperReports is an open source java reporting engine. JasperReports is a Java class library, and it is meant for those Java developers who need to add reporting capabilities to their applications. This simple and user-friendly tutorial covers almost all the basics of JasperReports that a beginner should know.
This tutorial is designed for Software Professionals as well as for all those beginners who would like to learn the concepts of JasperReports.
Before proceeding with this tutorial, it is expected that you have a basic understanding of Java programming language. A basic understanding of Java and other associated programming will be an additional advantage to understand the topic.
Kickstart Your Career
Get certified by completing the course
How to Generate Reports in a Spring Boot App Leveraging Jaspersoft
January 5, 2022.
We use reports in our day-to-day activities. We may use them when we are purchasing products, services, or managing transactions. This includes summary reports, financial reports, inventory reports, and budget reports.
These reports help in generating insights into an organization and making the right decision based on the knowledge generated from them. For example, an inventory report helps to decide on the appropriate reorder level.
In this tutorial, the reader will learn how to design an inventory report and how to integrate it into a Spring Boot application. The reader will use custom products to generate a standard report for use by an organization.
Table of contents
Prerequisites, create a spring boot application, add database configuration properties.
- Create a products model
Create a products repository to find all products by date
Create a report service to filter products by type.
- Design a report using jaspersoft template
Add the design to our spring boot application
- Add the jaspersoft dependency to our spring boot app
- Load and compile the Jaspersoft design
Create a folder to store the report
- Create a resource handler to display the generated pdf
Generate a report with the filtered products
Create a report controller, create a products page with date and file type fields, add a post mapping, test the application.
To follow along the reader will need:
- Knowledge in Spring Boot .
- Knowledge in Thymeleaf .
- Intellij IDEA installed on your computer.
- Jaspersoft Studio installed on your computer.
- A MySQL connector jar file.
On your browser, go to the spring initializr and create a new application. Add the dependencies: Spring Web , MySQL Driver , Thymeleaf , Lombok , and Spring Data JPA .
Extract the zip file to the desired folder and import the application in Intellij. Maven will download all our dependencies from the internet.
Add the following properties in the application.properties file. The main properties include the database URL, username, and password:
The spring.jpa.hibernate.ddl-auto property influences how the database tables are created and managed. The value create-drop tells Spring to create the tables on startup but drop them when the app terminates. The spring.jpa.show-sql property prints the queries generated by Hibernate so we know when errors occur.
The spring.jpa.properties.hibernate.format_sql property formats the SQL statements for readability. The spring.jpa.properties.hibernate.dialect property tells the application which SQL dialect to use.
Create a Products model
Create a class named Product with fields name , description , productType , price , and createdAt . The price is a BigDecimal , productType is an enum, and createdAt is a LocalDate .
The @Data annotation generates the getter and setter methods. This ensures we can display the list of products on our Thymeleaf page. The @NoArgsConstructor generates an empty constructor.
Create an interface named ProductRepository that extends JpaRepository . Then, create a method that returns a collection of products queried by date in the interface:
Create an interface named ReportService and add two methods. The first method returns the report link, given the date and the file format. The other method returns a collection of products from the database.
The JRException comes from the net.sf.jasperreports library which is added later in the application. This class will be thrown when there is an error when compiling or filling the report with our data from the database.
Design a report using Jaspersoft template
Let’s open JasperSoft studio. Before we create a design of the report, we will add the MySQL connector to the classpath. This will ensure we can connect to our database and generate the desired fields from our table.
In Jaspersoft studio, click on help , install new software , manage . Once you click manage a new panel named preferences opens. Use the search field provided by the panel to search for java . The search will return different results but in our case click on build path .
Under build path , click on classpath variables . The classpath variables provide us with the capability to add, edit, and remove variables using the new , edit , and remove buttons. Click on new and add the jar file on the window that opens with the desired name as shown below:
Add the MySQL connector and run the spring boot app. The spring boot app will generate the tables required by Jaspersoft studio. Create a design for our report from existing templates. On the Jaspersoft toolbar click on file , new , jasper report .
A window opens with a list of templates to choose from. For this tutorial, select the template named simple blue and click next. Add a new .jrxml file using the window that opens up. This is an extension for Jaspersoft report files. For our case name the file as products.jrxml and click next.
There are situations where Jaspersoft studio does not connect to the database by only adding the MySQL connector using the above steps. A ClassNotFoundException is caused by the software not being able to locate the MySQL driver class. To fix this error, we should add the MySQL connector in the driver classpath menu provided on the next window.
The window that opens next requires us to provide our data source. The data source is our database URL, username, and password to connect to our database. Click on new and on the data adapters window select database JDBC connection and click next. A window then opens where we need to fill the database connection properties as shown below:
Connect and write a query on the next window to select all the fields on the products table and click next:
The new window that appears displays all the fields from our database table. Add all the fields we want to appear in the report. Add from the data fields on the left side to the fields section on the right side. You can do this using the button with the greater-than symbol:
Click the Finish button to generate the final report. The report has our fields from the products entity as shown below. Edit the title and the description on the design header where necessary:
The design we have created generates XML describing the report structure. Get the code for it by clicking the source button on the bottom of the Jaspersoft design window:
Remove the properties in the field tags in the source file. Ensure the class and name properties of the field tag are the same as that of our product model:
The productType is an enum and it will throw a ClassCastException when we try to cast it to a string. To avoid this add a getter method in the products class that returns the string value of the enum.
Also, ensure that the text field expression in the details section is of the same name as that of our product fields.
Copy the entire source code in our Spring Boot application. Name the file products.jrxml in the resources package.
Add the Jaspersoft dependency to our spring boot app
The Jaspersoft dependency will help us in adding the functionalities. These functionalities include loading, compiling, filling, and generating the document. Add this dependency in the pom.xml file. Maven will download it for us and add it to the classpath where we can invoke its methods:
This dependency can be found from the maven central repository
Load and compile the Jaspersoft design source file in the report service
Create a class named ReportServiceImpl that implements the ReportService interface. Implement the generateReport() and findAllProducts() methods. The getJasperPrint() method handles the functionality of compiling the jasper report file.
This method accepts the collection of data that we use to fill the report and a string. The string indicates the location of the Jasper report source file. When run, the function returns an instance of JasperPrint :
In the ReportServiceImpl class create a method named getUploadPath() . Add the file format, a JasperPrint returned from the above method, and a file name as parameters. This method creates the specified directory if it does not exist. It also creates the generated PDF file in the folder with the file name passed to it.
We will also add a method named getPdfFileLink() that returns the link to our generated report. This method will take the file path returned by the getUploadPath() method as a string argument. We will use the two methods getJasperPrint() and getUploadPath() in the generateReport() method which currently returns null to generate our report.
Create a resource handler to display the generated PDF
Create a class named AppWebConfig that implements MvcConfigurer and override the addResourceHandlers() method. Create a method named uploadPath() that returns the absolute path. The application should allow requests to our PDF links using the string /generated-reports/** . Pass the absolute path returned by the method to the addResourceLocations() method:
We implement this functionality using the generateReport() method in the ReportServiceImpl class. This method accepts two parameters of type LocalDate and String . To implement it, first, inject the ProductsRepository bean. We will use it to search for products created on that specific day. Create a string containing the resource location of our source file, i.e, products.jrxml .
Then call the getJasperPrint() method and pass the collection of products. Create a string containing the name of the PDF report to generate i.e, products.pdf . Next, call the getUploadPath() method with the fileFormat parameter provided by the generateReport() method.
Now, return the value from the getFilePdfLink() method, passing the value returned by the call to getUploadPath() as a string. This method returns a link containing the path of our generated PDF file to our controller.
Our products page will display the list of products in the database. Ensure that the findAllProducts() method calls the findAll() method instead of returning null .
Allow any request to the root path and iterate through the list of products using a products model. Set the value of this model to be the return value of the findAllProducts() method of the ReportService :
The products page contains two sections. One has a form where we enter the date and select the document type to generate (which in our case is) a PDF document. These two values are request parameters. Leverage the th:name property as shown on the input and option tags of the form below:
When we press the generate report button of the above form a post request goes to the /report path. This URL corresponds to the generateReport() method of the controller. The @RequestParam annotation retrieves the date and the file format from the request.
It passes the values to the generateReport() method of our ReportService . Return a string containing the path to our generated PDF as we discussed earlier. We then issue a new request to the path by redirecting to it in the controller. The redirect allows us to display the report in our browser. Note that the resource handler must be available for this to work.
We need to populate our products table with dummy data for testing purposes. Add a CommandLineRunner with a list of products to create when our application starts up:
Run the Spring Boot application and visit the page at localhost 8080. Our page displays a form and a list of products:
Enter the current date, select PDF as the file type, and press the generate button. This redirects us to the generated PDF on a new browser tab as shown below.
Note that the dates will be different depending on the time you are reading this article.
We can play with the results using the current and previous dates. Some of the products created have LocalDate.now() to get the current date. Some of the products have LocalDate.now().minusDays(1) to get the date of the previous day.
In this tutorial, we have learned how to generate a PDF report using Jaspersoft studio. We have used an existing template and customized it to meet our needs. We have also learned how to load, compile, fill and generate the different types of documents.
Peer Review Contributions by: John Amiscaray
Creating a Nested Scroll Music Player App in Jetpack Compose
Integrating Razorpay in a React-Django Application
Implementing a Spring Query Language Spring Boot Search
- Data Warehouse & BI
- IT Architecture & Cloud Computing
- Reporting tools
- Run a Jasper Report from Java EE Application
This tutorial explains you how to Run a Jasper Report from Java Application using JSF (PrimeFaces).