Now, when the objects, data source class and the report design are ready, it is very easy to generate the report and save it to pdf, html or display on the screen:
01public static void pilotsReport() { 02
03
// obtain a list of objects for the report 04
List<Pilot> pilots = database().query(new Predicate<Pilot>() { 05
public boolean match(Pilot pilot) { 06
// each Pilot is included in the result 07
return true; 08
} 09
}); 10
11
// pass parameters to the report 12
Map parameters = new HashMap(); 13
parameters.put("Title", "The Pilot Report"); 14
15
try { 16
// compile report design 17
JasperReport jasperReport = JasperCompileManager 18
.compileReport("reports/the-pilot-report.jrxml"); 19
20
// create an object datasourse from the pilots list 21
ObjectDataSource dataSource = new ObjectDataSource(pilots); 22
23
// fill the report 24
JasperPrint jasperPrint = JasperFillManager.fillReport( 25
jasperReport, parameters, dataSource); 26
27
// export result to the *.pdf 28
JasperExportManager.exportReportToPdfFile(jasperPrint, 29
"reports/the-pilot-report.pdf"); 30
31
// or export to *.html 32
JasperExportManager.exportReportToHtmlFile(jasperPrint, 33
"reports/the-pilot-report.html"); 34
35
// or view it immediately in the Jasper Viewer 36
JasperViewer.viewReport(jasperPrint); 37
} catch (JRException e) { 38
e.printStackTrace(); 39
} 40
}