SyntaxHighlighter

2012-10-25

Compile and Print reports in JasperReports 4

When I working my report with JasperReports 4.7(the latest version at the moment), I'm forced to face the truth: the documents on the net were too old to make the reports. They uses the JasperReports 3.x when it's in 2002~2005. I can't find the JasperManager class in the library in JasperReports 4.7.

You may see some examples which were written for JasperReport 3.x as below:
// First, load JasperDesign from XML and compile it into JasperReport
JasperDesign jasperDesign = JasperManager.loadXmlDesign("BasicReport.xml");
JasperReport jasperReport = JasperManager.compileReport(jasperDesign);
// Second, create a map of parameters to pass to the report.
Map parameters = new HashMap();
parameters.put("ReportTitle", "Basic JasperReport");
parameters.put("MaxSalary", new Double(25000.00));
// Third, get a database connection
Connection conn = Database.getConnection(); 
// Fourth, create JasperPrint using fillReport() method
JasperPrint jasperPrint = JasperManager.fillReport(jasperReport, parameters, conn);
// You can use JasperPrint to create PDF
JasperManager.printReportToPdfFile(jasperPrint, "BasicReport.pdf");
// Or to view report in the JasperViewer
JasperViewer.viewReport(jasperPrint);


In JasperReport 4.x, it will look like below:
// First, load JasperDesign from XML and compile it into JasperReport
JasperDesign jasperDesign = JRXmlLoader.load("BasicReport.xml");
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
// Second, create a map of parameters to pass to the report.
Map parameters = new HashMap();
parameters.put("ReportTitle", "Basic JasperReport");
parameters.put("MaxSalary", new Double(25000.00));
// Third, get a database connection
Connection conn = Database.getConnection(); 
// Fourth, create JasperPrint using fillReport() method
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);
// You can use JasperPrint to create PDF
JasperExportManager.exportReportToPdfFile(jasperPrint, "BasicReport.pdf");
// Or to view report in the JasperViewer
JasperViewer.viewReport(jasperPrint);


As you can see, there is some change between version 3.x to 4.x. In JasperReport 4.x, there are LOTS of class which sees to access to the same in-memory data. The classes becomes more easy to do things you want. Just try it.

0 件のコメント:

人気の投稿