o7planning

Call JasperReport from Java Application

  1. Download JasperReport library for Java
  2. Download JDBC Drivers
  3. Prepare reports
  4. Create a Java project and declare library
  5. Generate PDF
  6. The utility classes to connect some kind of Database
  7. Pass Datasource and Parameters

1. Download JasperReport library for Java

Results:
Unzip the downloaded file:

2. Download JDBC Drivers

If the report connected to a database, you need to have the JDBC drivers:
You can see the guide to download JDBC Driver at:

3. Prepare reports

You need a JasperReport file. We will run that report on Java. You can download an example of a report file at:
Unzip the downloaded file, we will have jrxml file.

4. Create a Java project and declare library

Create Java Project:
  • JavaCallJasperReportTutorial
Create a libs folder and copy the most vital libraries into this folder, including:
  • commons-beanutils-*.jar
  • commons-collections-*.jar
  • commons-digester-*.jar
  • commons-logging-*.jar
  • groovy-all-*.jar
  • itextpdf-*.jar
  • itext-pdfa-*.jar
  • jasperreports-*.jar
Next, copy JDBC Drivers into libs folder. Here I copy all of three JDBC Driver into Database types including Oracle, MySQL, SQLServer.
To declare the library, right-click Project and select Properties
Select all the jar files in the libs folder:

5. Generate PDF

Here is a simple example, Java will call to report JasperReport and generate PDF file. This simple example does not have the participation of the Database.
PdfFromXmlFile.java
package org.o7planning.tutorial.javajasperreport;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;

public class PdfFromXmlFile {

   public static void main(String[] args) throws JRException, IOException {

        // Compile jrxml file.
       JasperReport jasperReport = JasperCompileManager
               .compileReport("C:/jasperreport/StyledTextReport/StyledTextReport.jrxml");

       // Parameters for report
       Map<String, Object> parameters = new HashMap<String, Object>();

       // DataSource
       // This is simple example, no database.
       // then using empty datasource.
       JRDataSource dataSource = new JREmptyDataSource();

       JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,
               parameters, dataSource);

   
       // Make sure the output directory exists.
       File outDir = new File("C:/jasperoutput");
       outDir.mkdirs();

       // Export to PDF.
       JasperExportManager.exportReportToPdfFile(jasperPrint,
               "C:/jasperoutput/StyledTextReport.pdf");
       
       System.out.println("Done!");
   }
}
Results of running the example:

6. The utility classes to connect some kind of Database

  • Oracle
  • MySQL
  • SQLServer
OracleConnUtils.java
package org.o7planning.tutorial.javajasperreport.conn;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class OracleConnUtils {

    public static Connection getOracleConnection()
            throws ClassNotFoundException, SQLException {
        String hostName = "localhost";
        String sid = "db11g";
        String userName = "learningsql";
        String password = "12345";

        return getOracleConnection(hostName, sid, userName, password);
    }

    public static Connection getOracleConnection(String hostName, String sid,
            String userName, String password) throws ClassNotFoundException,
            SQLException {

     
        // Declare the class Driver for ORACLE DB
        // This is necessary with Java 5 (or older)
        // Java6 (or newer) automatically find the appropriate driver.
        // If you use Java> 5, then this line is not needed.    
        Class.forName("oracle.jdbc.driver.OracleDriver");


        // Example: jdbc:oracle:thin:@localhost:1521:db11g
        String connectionURL = "jdbc:oracle:thin:@" + hostName + ":1521:" + sid;

        Connection conn = DriverManager.getConnection(connectionURL, userName,
                password);
        return conn;
    }
}
MySQLConnUtils.java
package org.o7planning.tutorial.javajasperreport.conn;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class MySQLConnUtils {

    public static Connection getMySQLConnection()
            throws ClassNotFoundException, SQLException {
        String hostName = "localhost";
        String dbName = "learningsql";
        String userName = "root";
        String password = "12345";
        return getMySQLConnection(hostName, dbName, userName, password);
    }

    public static Connection getMySQLConnection(String hostName, String dbName,
            String userName, String password) throws SQLException,
            ClassNotFoundException {

        // Declare the class Driver for MySQL DB
        // This is necessary with Java 5 (or older)
        // Java6 (or newer) automatically find the appropriate driver.
        // If you use Java> 5, then this line is not needed.
        Class.forName("com.mysql.jdbc.Driver");

        // Cấu trúc URL Connection dành cho Oracle
        // Ví dụ: jdbc:mysql://localhost:3306/simplehr
        String connectionURL = "jdbc:mysql://" + hostName + ":3306/" + dbName;

        Connection conn = DriverManager.getConnection(connectionURL, userName,
                password);
        return conn;
    }
}
SQLServerConnUtils.java
package org.o7planning.tutorial.javajasperreport.conn;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class SQLServerConnUtils {
    
    // Connect to SQLServer
    // (Using JDBC Driver: SQLJDBC)
    public static Connection getSQLServerConnection_SQLJDBC()
            throws ClassNotFoundException, SQLException {
        String hostName = "localhost";
        String sqlInstanceName = "SQLEXPRESS";
        String database = "learningsql";
        String userName = "sa";
        String password = "12345";

        return getSQLServerConnection_SQLJDBC(hostName, sqlInstanceName,
                database, userName, password);
    }

   
    // Connect to SQLServer & using JTDS library
    public static Connection getSQLServerConnection_JTDS() throws SQLException,
            ClassNotFoundException {
        String hostName = "learningsql";
        String sqlInstanceName = "SQLEXPRESS";
        String database = "simplehr";
        String userName = "sa";
        String password = "12345";

        return getSQLServerConnection_JTDS(hostName, sqlInstanceName, database,
                userName, password);
    }
   
    // Connect to SQLServer
    // (Using JDBC Driver: SQLJDBC)
    private static Connection getSQLServerConnection_SQLJDBC(String hostName,
            String sqlInstanceName, String database, String userName,
            String password) throws ClassNotFoundException, SQLException {

        // Declare the class Driver for SQLServer DB
        // This is necessary with Java 5 (or older)
        // Java6 (or newer) automatically find the appropriate driver.
        // If you use Java> 5, then this line is not needed.
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

        // jdbc:sqlserver://ServerIp:1433/SQLEXPRESS;databaseName=simplehr
        String connectionURL = "jdbc:sqlserver://" + hostName + ":1433"
                + ";instance=" + sqlInstanceName + ";databaseName=" + database;

        Connection conn = DriverManager.getConnection(connectionURL, userName,
                password);
        return conn;
    }
   
    // Connect to SQLServer & using JTDS library
    private static Connection getSQLServerConnection_JTDS(String hostName,
            String sqlInstanceName, String database, String userName,
            String password) throws ClassNotFoundException, SQLException {

        // Declare the class Driver for SQLServer DB
        // This is necessary with Java 5 (or older)
        // Java6 (or newer) automatically find the appropriate driver.
        // If you use Java> 5, then this line is not needed.    
        Class.forName("net.sourceforge.jtds.jdbc.Driver");

        // jdbc:jtds:sqlserver://localhost:1433/simplehr;instance=SQLEXPRESS
        String connectionURL = "jdbc:jtds:sqlserver://" + hostName + ":1433/"
                + database + ";instance=" + sqlInstanceName;

        Connection conn = DriverManager.getConnection(connectionURL, userName,
                password);
        return conn;
    }

}
ConnectionUtils.java
package org.o7planning.tutorial.javajasperreport.conn;

import java.sql.Connection;
import java.sql.SQLException;

public class ConnectionUtils {

    public static Connection getConnection() throws SQLException,
            ClassNotFoundException {

        // Using Oracle
        // You may be replaced by other Database.
        return OracleConnUtils.getOracleConnection();
    }

    //
    // Test Connection ...
    //
    public static void main(String[] args) throws SQLException,
            ClassNotFoundException {

        System.out.println("Get connection ... ");

        // Get a Connection object
        Connection conn = ConnectionUtils.getConnection();

        System.out.println("Get connection " + conn);

        System.out.println("Done!");
    }
}

7. Pass Datasource and Parameters

The following example will be more complex than the previous example. We will pass parameters and database connection into report from Java.
JavaCallJasperReport.java
package org.o7planning.tutorial.javajasperreport;

import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.export.ExporterInput;
import net.sf.jasperreports.export.OutputStreamExporterOutput;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
import net.sf.jasperreports.export.SimplePdfExporterConfiguration;

import org.o7planning.tutorial.javajasperreport.conn.ConnectionUtils;

public class JavaCallJasperReport {

    public static void main(String[] args) throws JRException,
            ClassNotFoundException, SQLException {

        String reportSrcFile = "F:/ECLIPSE_TUTORIAL/JASPERREPORT/HelloJasperReport/FirstJasperReport.jrxml";
        
        // First, compile jrxml file.
        JasperReport jasperReport =    JasperCompileManager.compileReport(reportSrcFile);

        Connection conn = ConnectionUtils.getConnection();

        // Parameters for report
        Map<String, Object> parameters = new HashMap<String, Object>();

        JasperPrint print = JasperFillManager.fillReport(jasperReport,
                parameters, conn);

        // Make sure the output directory exists.
        File outDir = new File("C:/jasperoutput");
        outDir.mkdirs();

        // PDF Exportor.
        JRPdfExporter exporter = new JRPdfExporter();

        ExporterInput exporterInput = new SimpleExporterInput(print);
        // ExporterInput
        exporter.setExporterInput(exporterInput);

        // ExporterOutput
        OutputStreamExporterOutput exporterOutput = new SimpleOutputStreamExporterOutput(
                "C:/jasperoutput/FirstJasperReport.pdf");
        // Output
        exporter.setExporterOutput(exporterOutput);

        //
        SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
        exporter.setConfiguration(configuration);
        exporter.exportReport();

        System.out.print("Done!");
    }
}