Google

Monday, July 20, 2009

MySQL: How to embed JasperReports (.jasper) in your Java application

To embed Jasper Reports you need to use iReport
to create the .jasper file (eg "report.jasper").
I was not able to get Java
to compile a .jrxml directly. Besides even if it could,
it could slow down your Java application, because it
needs time to compile. So I opted to use iReport
to create a Report and snag the .jasper file right
out of the JasperReport folder and dump it into
my Java applications folder.

I'm using Netbeans 6.5.
In the Project Properties of your java application,
if you use the default JasperReport Library, it will create a
huge library folder in the dist folder which is
about 25MB and this is bad for Java WebStart
applications.

I have picked out the bare minimum libraries and
copied it out to another folder and use it to
add to the project library folder. The bare
minimum libraries needed for your java application to
read and display .jasper file:

This reduces the size of the lib to about 7 MB.

The source code
The source code that loads the .jasper file and displays it
is as below:

private void runReportJasperExtension(String reportFile) {
try{
Class.forName(JDBC_DRIVER).newInstance();
connection = DriverManager.getConnection(DATABASE_URL, "user", "password");
String jasperPrint = JasperFillManager.fillReportToFile(reportFile,null,connection);
JasperViewer.viewReport(jasperPrint,false,true);

}catch(Exception ex) {
String connectMsg = "Could not view " + ex.getMessage() + " " + ex.getLocalizedMessage();
System.out.println(connectMsg);
}finally {
try {
statement.close();
} catch (Exception e) {
}
}
}

My jasper file is "report.jasper". To call the method:

runReportJasperExtension("report.jasper") ;

Put "report.jasper" in the root folder of your Java
Project and create the following variables:


private Connection connection;
private String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private String DATABASE_URL = "jdbc:mysql://localhost/icomis";