Oppure

Loading
13/09/12 10:01
Bonny
Salve ragazzi sto provando la libreria jasper report per creare dei pdf con una semplice applicazione di esempio
Questa è la classe di esempio:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;


/**
 * @author Bonny
 *
 */
public class ReportTest {

   private Connection conn = null;
   private String jrxml = "ReportTest.jrxml";

   public ReportTest() {

      long start = System.currentTimeMillis();
      // compilazione del report (creazione del .jasper a partire dal .jrxml)
      try {
         JasperCompileManager.compileReportToFile(jrxml);
      } catch (Exception jre) {
         System.err.println("GeneralTest.createReport(): eccezione: " + jre.getMessage());
      }
      System.out.println("Compile time : " + (System.currentTimeMillis() - start));

      Map parametri = new HashMap();

      parametri.put("ReportTitle", "LucaBonaldo Report Example");
      // parametri.put( "FilterClause", "" );
      // parametri.put( "OrderClause", "" );
      try {
         conn = this.getConnection();
         this.createDB(conn);
         // creazione del report (file .jrprint)
         JasperFillManager.fillReportToFile("file.jrprint", parametri, conn);
         // export del report in PDF
         JasperExportManager.exportReportToPdfFile("file.jrprint", "report.pdf");
         System.out.println("GeneralTest.createReport(): PDF running time : " + (System.currentTimeMillis() - start));
         conn.close();
      } catch (ClassNotFoundException | SQLException | JRException ex) {
         System.err.println("Connessione a sqlite non riuscita\nErrore:" + ex.getMessage());
      }
   }

   private Connection getConnection() throws ClassNotFoundException, SQLException {

      String driver = "org.sqlite.JDBC";
      String connectString = "jdbc:odbc:jasper.db";
      String user = "";
      String psw = "";

      Class.forName(driver);
      Connection c = DriverManager.getConnection(connectString, user, psw);

      return c;
   }

   private void createDB(Connection c) {

      Statement stmt;
      PreparedStatement pstmt;
      ResultSet rs;

      try {
         // creo la tabella
         stmt = c.createStatement();
         stmt.executeUpdate("DROP TABLE IF EXISTS studenti");
         stmt.executeUpdate("CREATE TABLE studenti "
                 + "(id INTEGER PRIMARY KEY AUTOINCREMENT, "
                 + "nome VARCHAR(30) NOT NULL, "
                 + "cognome VARCHAR(30) NOT NULL, "
                 + "matricola VARCHAR(30) NOT NULL)");
         // inserisco due record
         pstmt = c.prepareStatement("INSERT INTO studenti (nome, cognome, matricola) values (?,?)");
         pstmt.setString(1, "Luca");
         pstmt.setString(2, "Bonaldo");
         pstmt.setString(3, "098345");
         pstmt.execute();
         pstmt.setString(1, "Mario");
         pstmt.setString(2, "Rossi");
         pstmt.setString(3, "098FA1");
         pstmt.execute();
         pstmt.setString(1, "Marco");
         pstmt.setString(2, "Bianchi");
         pstmt.setString(3, "112BB7");
         pstmt.execute();
      } catch (SQLException ex) {
         Logger.getLogger(ReportTest.class.getName()).log(Level.SEVERE, null, ex);
      }

   }

   public static void main(String[] args) {
      ReportTest rt = new ReportTest();

   }
}

file .jrxml
<?xml version="1.0"?>
<!DOCTYPE jasperReport PUBLIC "-//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd" [
  <!ENTITY reportFonts SYSTEM "./ReportFonts.ent">
]>

<jasperReport 
   name="GeneralTest" 
   pageWidth="595" 
   pageHeight="842" 
   columnWidth="515" 
   columnSpacing="0" 
   leftMargin="40" 
   rightMargin="40" 
   topMargin="50" 
   bottomMargin="50"
   whenNoDataType="AllSectionsNoDetail"
   isTitleNewPage="false"
   isSummaryNewPage="false">

	&reportFonts;

   <parameter name="ReportTitle" class="java.lang.String"/>
   <parameter name="FilterClause" class="java.lang.String"/>
   <parameter name="OrderClause" class="java.lang.String"/>
   <queryString><![CDATA[SELECT * FROM studenti]]>
   </queryString>
   <field name="id" class="java.lang.Integer"/>
   <field name="nome" class="java.lang.String"/>
   <field name="cognome" class="java.lang.String"/>
   <field name="matricola" class="java.lang.String"/>

   <variable name="Count" class="java.lang.Integer" resetType="Group" resetGroup="CountGroup" calculation="System">
      <initialValueExpression>($V{Count} != null)?(new Integer($V{Count}.intValue() + 1)):(new Integer(1))</initialValueExpression>
   </variable>
   <group name="CountGroup" minHeightToStartNewPage="60">
      <groupExpression>
         $F{count}
      </groupExpression>
      <groupHeader>
         <band height="20">
            <rectangle>
               <reportElement x="0" y="4" width="515" height="15" forecolor="#C0C0C0" backcolor="#C0C0C0"/>
            </rectangle>
            <textField>
               <reportElement x="0" y="4" width="515" height="15" backcolor="#C0C0C0" mode="Opaque"/>
               <textElement textAlignment="Left">
                  <font reportFont="Arial_Bold"/>
               </textElement>
               <textFieldExpression class="java.lang.String">
                  "  " + String.valueOf($V{CountNumber})
               </textFieldExpression>
            </textField>
            <line>
               <reportElement x="0" y="19" width="515" height="0"/>
            </line>
         </band>
      </groupHeader>
      <groupFooter>
         <band height="20">
            <line>
               <reportElement x="0" y="-1" width="515" height="0"/>
            </line>
            <staticText>
               <reportElement x="400" y="0" width="60" height="15"/>
               <textElement textAlignment="Right" lineSpacing="Single">
                  <font reportFont="Arial_Bold"/>
               </textElement>
               <text>Count : </text>
            </staticText>
            <textField>
               <reportElement x="460" y="0" width="30" height="15"/>
               <textElement textAlignment="Right" lineSpacing="Single">
                  <font reportFont="Arial_Bold"/>
               </textElement>
               <textFieldExpression class="java.lang.Integer">
                  $V{CountGroup_COUNT}
               </textFieldExpression>
            </textField>
         </band>
      </groupFooter>
   </group>
   <title>
      <band height="50">
         <line>
            <reportElement x="0" y="0" width="515" height="0" forecolor="black"/>
         </line>
         <textField isBlankWhenNull="true">
            <reportElement x="0" y="10" width="515" height="30"/>
            <textElement textAlignment="Center" lineSpacing="Single">
               <font reportFont="Arial_Normal" size="22"/>
            </textElement>
            <textFieldExpression class="java.lang.String">$P{ReportTitle}</textFieldExpression>
         </textField>
      </band>
   </title>
   <pageHeader>
      <band height="20">
         <rectangle>
            <reportElement x="0" y="5" width="515" height="15" forecolor="#333333" backcolor="#333333"/>
         </rectangle>
         <staticText>
            <reportElement x="0" y="5" width="55" height="15" forecolor="white" backcolor="#333333" mode="Opaque"/>
            <textElement textAlignment="Center">
               <font reportFont="Arial_Bold"/>
            </textElement>
            <text>Nome</text>
         </staticText>
         <staticText>
            <reportElement x="55" y="5" width="205" height="15" forecolor="white" backcolor="#333333" mode="Opaque"/>
            <textElement>
               <font reportFont="Arial_Bold"/>
            </textElement>
            <text>Cognome</text>
         </staticText>
         <staticText>
            <reportElement x="260" y="5" width="255" height="15" forecolor="white" backcolor="#333333" mode="Opaque"/>
            <textElement>
               <font reportFont="Arial_Bold"/>
            </textElement>
            <text>Matricola</text>
         </staticText>
      </band>
   </pageHeader>
   <detail>
      <band height="20">
         <textField isStretchWithOverflow="true">
            <reportElement x="55" y="4" width="200" height="15" positionType="Float"/>
            <textFieldExpression class="java.lang.String">
               $F{nome} 
            </textFieldExpression>
         </textField>
         <textField isStretchWithOverflow="true">
            <reportElement x="260" y="4" width="255" height="15" positionType="Float"/>
            <textFieldExpression class="java.lang.String">
               $F{cognome}
            </textFieldExpression>
         </textField>
         <textField isStretchWithOverflow="true">
            <reportElement x="260" y="4" width="255" height="15" positionType="Float"/>
            <textFieldExpression class="java.lang.String">
               $F{matricola}
            </textFieldExpression>
         </textField>
         <line>
            <reportElement x="0" y="19" width="515" height="0" forecolor="#808080" positionType="Float"/>
         </line>
      </band>
   </detail>
   <pageFooter>
      <band height="40">
         <line>
            <reportElement x="0" y="10" width="515" height="0"/>
         </line>
         <textField>
            <reportElement x="200" y="20" width="80" height="15"/>
            <textElement textAlignment="Right"/>
            <textFieldExpression class="java.lang.String">
               "Page " + String.valueOf($V{PAGE_NUMBER}) + " of"
            </textFieldExpression>
         </textField>
         <textField evaluationTime="Report">
            <reportElement x="280" y="20" width="75" height="15"/>
            <textElement textAlignment="Left"/>
            <textFieldExpression class="java.lang.String">
               " " + String.valueOf($V{PAGE_NUMBER})
            </textFieldExpression>
         </textField>
      </band>
   </pageFooter>
   <summary>
      <band height="60">
         <textField isStretchWithOverflow="true">
            <reportElement x="175" y="20" width="165" height="15"/>
            <textElement textAlignment="Center">
               <font reportFont="Arial_Italic"/>
            </textElement>
            <textFieldExpression class="java.lang.String">
               "Ci sono " + 
               String.valueOf($V{REPORT_COUNT}) + 
               " studenti in questo report."
            </textFieldExpression>
         </textField>
      </band>
   </summary>
</jasperReport>

come vedete uso un db sqlite ma questo non è il problema..

Io uso Netbeans queste sono le librerie che ho aggiunto al progetto:

sqlite-jdbc.jar
jasperreport.jar
commons-degester.jar
commons-logging.jar

ovviamente aggiornate alle ultime versioni..

quando avvio il programma segue questa eccezione:

run:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/digester/Digester
    at net.sf.jasperreports.engine.JasperCompileManager.compileToFile(JasperCompileManager.java:110)
    at net.sf.jasperreports.engine.JasperCompileManager.compileReportToFile(JasperCompileManager.java:415)
    at provajasper.ReportTest.<init>(ReportTest.java:36)
    at provajasper.ReportTest.main(ReportTest.java:110)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.digester.Digester
    at java.net.URLClassLoader.run(URLClassLoader.java:366)
    at java.net.URLClassLoader.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    ... 4 more
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

ma come vedete io ho importato le librerie...

vi allego l'intero progetto, sto "smanettando" da ore e non ne vengo a capo, per favore se riuscite datemi un consiglio su come risolvere la questione..
Ultima modifica effettuata da Bonny 13/09/12 15:35
aaa
17/09/12 12:40
fraioveio
Avevo anch'io lo stesso problema...
JasperReport ha una cartella lib, devi includere anche le librerie in quella cartella :k:
aaa
17/09/12 18:22
Bonny
Grazie mille!!!!
aaa