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

Steps:
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.setAge(19);
  a.setAddress("Final Fantasy VII");
  students.add(a);

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

  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()
   .getRealPath("/WEB-INF/classes/StudentReport.jasper");

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

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

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

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

 out.flush();

 out.close();
}

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

*Note: You can download the project from my google code account:
https://code.google.com/p/czetsuya/source/browse/#svn%2Ftrunk%2Fjasper-demo
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.