Quello che utilizzeremo per la produzione di tale file è Ireports.
Ireports consente la visualizzazione dei file di tipo jrxml in tre diverse modalità:
- Designer
- XML
- Anteprima
Nel secondo caso potremmo modificare il codice xml della pagina.
Infine ,nella modalità anteprima , se la compilazione del file non ha avuto problemi verrà prodotto il nostro PDF e mostrata quindi l'anteprima.
Nel nostro esempio visualizzeremo tre campi ID,RAGIONESOCIALE,CITTA all'interno del Report utilizzando come sorgente dati un DB oracle, nel quale creiamo una tabella chiamata SOCIETA con il seguente script:
CREATE TABLE SOCIETA
(
ID NUMBER,
RAGIONESOCIALE VARCHAR2(20 BYTE),
CITTA VARCHAR2(20 BYTE)
)
Ricordiamoci di impostare dal pulsante Report Datasources il nuovo Datasource che utilizzeremo in questo Report tramite il pulsante New.
I dati da definire per creare una nuova connessione con il vostro DB sono i soliti:
Nome: Oracle_prova
JDBC Driver : Oracle (oracle.jdbc.driver.OracleDriver)
JDBC URL : jdbc:oracle:thin:@LOCALHOST:1521:DBPROVA
UTENTE: PROVA
PASSWORD:PROVA
A questo punto proviamo la connessione che abbiamo impostato,in caso positivo avremo il messaggio :"Test Successfull".
Procediamo con la creazione del nostro jrxml.
Dal menu file Nuovo, potremmo scegliere tra diversi template, ma una volta scelto quello che consiglio è di utilizzare l'opzione launch template wizard, che consente una rapida creazione del report.
In questo modo possiamo definire la sorgente dati precedentemente creata, la query che utilizzeremo per estrarre i dati ;a questo scopo è possibile utilizzare lo strumento Design query,che consente di costruire la nostra query gradualmente.
Per la corretta compilazione del nostro file jrxml ricordiamo che deve essere presente nel file la riga <!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd"> ,che non sempre viene inserita nel file generato automaticamente.
Il codice del mio file report1Java.jrxml è il seguente:
<?xml version="1.0" encoding="UTF-8" ?>
<!-- Created with iReport - A designer for JasperReports -->
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport
name="report1Java"
columnCount="1"
printOrder="Vertical"
orientation="Landscape"
pageWidth="1190"
pageHeight="842"
columnWidth="1174"
columnSpacing="0"
leftMargin="8"
rightMargin="8"
topMargin="20"
bottomMargin="20"
whenNoDataType="NoPages"
isTitleNewPage="false"
isSummaryNewPage="false">
<property name="ireport.scriptlethandling" value="0" />
<property name="ireport.encoding" value="UTF-8" />
<import value="java.util.*" />
<import value="net.sf.jasperreports.engine.*" />
<import value="net.sf.jasperreports.engine.data.*" />
<queryString>
<![CDATA[select * from societa]]>
</queryString>
<field name="ID" class="java.math.BigDecimal"/>
<field name="RAGIONESOCIALE" class="java.lang.String"/>
<field name="CITTA" class="java.lang.String"/>
<columnHeader>
<band height="28" isSplitAllowed="true">
<staticText>
<reportElement key="staticText-1" x="40" y="11" width="193" height="15"/>
<textElement/>
<text><![CDATA[
Item Name
]]></text>
</staticText>
<staticText>
<reportElement key="staticText-2" x="330" y="11" width="193" height="15"/>
<textElement/>
<text><![CDATA[
Item Amount
]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height="27" isSplitAllowed="true">
<textField>
<reportElement x="54" y="4" width="100" height="20"/>
<textElement/>
<textFieldExpression class="java.math.BigDecimal"><![CDATA[$F{ID}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="300" y="4" width="100" height="20"/>
<textElement/>
<textFieldExpression class="java.lang.String"><![CDATA[$F{RAGIONESOCIALE}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="562" y="4" width="100" height="20"/>
<textElement/>
<textFieldExpression class="java.lang.String"><![CDATA[$F{CITTA}]]></textFieldExpression>
</textField>
</band>
</detail>
</jasperReport>
Una volta creato il file e aperto con Ireport il risultato nella sezione Design sarà il seguente:
A questo punto rimane solamente scrivere i metodi java che utilizzeranno le librerie jasper ( jasperreports-3.7.3.jar).
public static Connection establishConnection() throws ClassNotFoundException
{
Connection connection = null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
String oracleURL = "jdbc:oracle:thin:@localhost:1521:DBPROVA";
connection = DriverManager.getConnection(oracleURL,"PROVA","PROVA");
connection.setAutoCommit(false);
}
catch(SQLException exception)
{
exception.printStackTrace();
}
return connection;
}
public static void print() throws Exception {
HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpServletResponse resp = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
String path = req.getRealPath("/");
// connection is the data source we used to fetch the data from
Connection connection = establishConnection();
// jasperParameter is a Hashmap contains the parameters
// passed from application to the jrxml layout
HashMap jasperParameter = new HashMap();
/* JasperPrint is the object contains
report after result filling process */
JasperPrint jasperPrint;
JasperReport jasperReportNew;
// jrxml compiling process
jasperReportNew = JasperCompileManager.compileReport(path.concat("WEB-INF/jasper/pdf/report1Java.jrxml"));
jasperPrint = JasperFillManager.fillReport(jasperReportNew,jasperParameter, connection);
if (jasperPrint!=null)
JasperExport.exportToStreamByType(resp,jasperPrint, 1);
resp.getOutputStream().flush();
resp.getOutputStream().close();
FacesContext.getCurrentInstance().responseComplete();
}
Abbiamo collocato il nostro file report1Java in WEB-INF/jasper/pdf/report1Java.jrxml.