Appel de Jasper Report à l'aide de l'application Java

View more categories:

1- Télécharger la bibliothèque JasperReport pour Java

Résultats:
Décompressez le fichier  zip que vous venez de télécharger:

2- Télécharger des pilotes JDBC

Si le rapport est connecté à une base de données, vous devez disposer des pilotes JDBC (JDBC Driver Library).
Vous pouvez voir l'instruction de téléchargement de  JDBC Driver à:
  • TODO Link!

3- Préparer des rapports (Report)

Vous avez besoin d'un fichier  JasperReport. Nous allons exécuter ce rapport- là sur  Java. Vous pouvez télécharger un exemple d'un fichier de rapport à:
Décompressez le fichier que vous venez de télécharger, nous allons avoir le fichier  jrxml.

4- Créer un projet Java & déclarer une bibliothèque

Créer un projet Java ordinaire.
  • JavaCallJasperReportTutorial
Créer un dossier  libs et copier les bibliothèques vitales dans ce dossier, y compris:
  • commons-beanutils-*.jar
  • commons-collections-*.jar
  • commons-digester-*.jar
  • commons-logging-*.jar
  • groovy-all-*.jar
  • itextpdf-*.jar
  • itext-pdfa-*.jar
  • jasperreports-*.jar
Ensuite, copiez  JDBC Driver au dossier  libs, ici je copie tous les trois types de  JDBC Driver qui contrôlent des types de la base de données, y compris  Oracle, MySQL, SQLServer.
Pour déclarer la bibliothèque, cliquez sur le bouton droit du projet et sélectionnez  Properties
Sélectionnez tous le fichiers  jar dans le dossier  libs:

5- Créer le fichier PDF du JasperReport

Voici est un exemple simple, Java av appeler pour rapporter  JasperReport et générer le fichier  PDF.  Le simple exemple n'a pas la participation de  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!");
   }
}
Résultats de l'exécution de l'exemple:

6- Les classs utilitaires pour se connecter à certains types de la base de données

  • 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- Passer la source de données et les paramètres

L'exemple suivant sera plus complexe que l'exemple précédent. Nous passerons les paramètres et la connexion à la base de données dans un rapport de 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!");
    }
}

View more categories: