Looking for a JavaEE Architect or Potential Tech Co-Founder?
Please don't hesitate to contact me.

How to generate a jasper report in java

This tutorial will guide you in generating a jasper report in java.

You need:
1.) Eclipse
2.) iReport - http://community.jaspersoft.com/project/ireport-designer

1.) First we need to create a model for our report. For example we have a Student model:

public class Student {
 private String name;
 private int age;
 private String address;

2.) We need to create the report in iReport.
  a.) Create a datasource:
    Factory class=com.czetsuya.jasper.edition.StudentReportBean
    Static method=createBeanCollection

3.) Drag a list component to the report designer and set the data source to our newly created one. You should see something like:

4.) Create the StudentReportBean class, the one that generates the data.

public class StudentReportBean {

 public StudentReportBean() {


 public static List<student> createBeanCollection() {
  List<student> students = new ArrayList<student>();

  Student a = new Student();
  a.setName("Tifa Lockheart");
  a.setAddress("Final Fantasy VII");

  Student b = new Student();
  b.setName("Rinoa Heartilly");
  b.setAddress("Final Fantasy VIII");

  return students;

5.) And in our case a managed bean that gets trigger from a command button in UI.

public void run() throws JRException, IOException {
 Collection<student> students = StudentReportBean.createBeanCollection();
 JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(
   students, false);

 String reportPath = FacesContext.getCurrentInstance().getExternalContext()

 JasperReport jasperReport;
 jasperReport = (JasperReport) JRLoader.loadObjectFromFile(reportPath);

 Map<string object=""> params = new HashMap<string object="">();
 JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params,

 HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance()
 ServletOutputStream out = response.getOutputStream();  

 response.setHeader("Content-disposition", "attachment; filename=student-report.pdf");
 JasperExportManager.exportReportToPdfStream(jasperPrint, out);



6.) You should be able to download the generated report from a browser.

*Note: You can download the project from my google code account:
How to generate a jasper report in java How to generate a jasper report in java Reviewed by Edward Legaspi on Monday, March 11, 2013 Rating: 5

No comments:

Powered by Blogger.