Luiz:
Permita-me passar algo que fizemos no meu trabalho. Trata-se de um relatório que é constituído de um cabeçalho e um rodapé que são impressos em todas as páginas mais o texto propriamente dito. Se o texto do cabeçalho e/ou do rodapé forem nulos, eles não aparecerão. Está configurado para uma página A4. Segue-se o código do XML deconfiguração:
<?xml version="1.0"?>
<!DOCTYPE jasperReport PUBLIC "-//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport
name="impressao"
pageWidth="595"
pageHeight="842"
columnWidth="515"
columnSpacing="0"
leftMargin="40"
rightMargin="40"
topMargin="50"
bottomMargin="50">
<parameter name="titulo" class="java.lang.String"/>
<parameter name="cabecalho" class="java.lang.String"/>
<parameter name="texto" class="java.lang.String"/>
<parameter name="rodape" class="java.lang.String"/>
<!--
<title>
<band height="70">
<textField isBlankWhenNull="true" isStretchWithOverflow="true">
<reportElement x="0" y="10" width="515" height="30"/>
<textElement textAlignment="Center">
<font fontName="Arial" size="22" pdfFontName="Helvetica" isPdfEmbedded="false"/>
</textElement>
<textFieldExpression>$P{titulo}</textFieldExpression>
</textField>
</band>
</title>
-->
<pageHeader>
<band height="70">
<textField isBlankWhenNull="true" isStretchWithOverflow="true">
<reportElement x="0" y="0" width="515" height="60"/>
<textElement textAlignment="Center"/>
<textFieldExpression>$P{cabecalho}</textFieldExpression>
</textField>
</band>
</pageHeader>
<detail>
<band height="20">
<textField isBlankWhenNull="true" isStretchWithOverflow="true">
<reportElement x="0" y="4" width="515" height="15"/>
<textElement>
<font fontName="monospaced" size="10" pdfFontName="Courier"/>
</textElement>
<textFieldExpression>$P{texto}</textFieldExpression>
</textField>
</band>
</detail>
<pageFooter>
<band height="70">
<textField isBlankWhenNull="true" isStretchWithOverflow="true">
<reportElement x="0" y="4" width="515" height="60"/>
<textElement textAlignment="Center"/>
<textFieldExpression>$P{rodape}</textFieldExpression>
</textField>
</band>
</pageFooter>
</jasperReport>
A classe abaixo lê o arquivo impressao.xml acima e pode gerar um PDF, um HTML e um arquivo para impressão. A seguir o código da classe:
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import dori.jasper.engine.*;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2002</p>
* <p>Company: </p>
* @author unascribed
* @version 1.0
*/
public class ServicoImpressaoTexto {
private String titulo;
private String cabecalho;
private String rodape;
private String texto;
private static JasperReport jrImpressao;
/**Construtor Padrão. */
public ServicoImpressaoTexto() {
}
private JasperReport getJasperReportImpressao() throws JRException, IOException {
if(jrImpressao == null) {
jrImpressao = JasperCompileManager.compileReport(new
BufferedInputStream(getClass().
getResourceAsStream("impressao.xml"))); // Localizacao do arquivo XML exibido acima.
}
return jrImpressao;
}
private JasperPrint gerarConteudo() throws JRException, IOException {
Map parameters = new HashMap(4);
parameters.put("titulo", this.titulo);
parameters.put("cabecalho", this.cabecalho);
parameters.put("texto", this.texto);
parameters.put("rodape", this.rodape);
return JasperFillManager.fillReport(this.getJasperReportImpressao(),
parameters, new JREmptyDataSource());
}
private String lerHTML(OutputStream osHTML, File fileHTML,
String fileName) throws IOException, JRException {
fileHTML = new File(fileName);
JasperExportManager.exportReportToHtmlFile(this.gerarConteudo(),
fileName);
BufferedReader rd = new BufferedReader(
new InputStreamReader(new FileInputStream(fileHTML)));
String s;
StringBuffer sbHTML = new StringBuffer();
while((s = rd.readLine()) != null) {
sbHTML.append(s + "
");
}
rd.close();
return sbHTML.toString();
}
private void fecharStreams(OutputStream osHTML, File fileHTML,
String fileName) throws IOException {
if(osHTML != null) {
osHTML.flush();
osHTML.close();
}
if((fileHTML != null) && fileHTML.exists()) {
fileHTML.delete();
}
fileHTML = new File(fileName + "_files");
if((fileHTML != null) && fileHTML.exists() && fileHTML.isDirectory()) {
fileHTML.delete();
}
}
/**Determina o Título do Relatório. Método sem Efeito
*
* @param strTitulo Título do Relatório.
*/
public void setTitulo(String strTitulo) {
this.titulo = strTitulo;
}
/**Determina o Cabeçalho das páginas do Relatório.
*
* @param strCabecalho Cabeçalho das páginas do Relatório.
*/
public void setCabecalho(String strCabecalho) {
this.cabecalho = strCabecalho;
}
/**Determina o Rodapé das páginas do Relatório.
*
* @param strRodape Rodapé das páginas do Relatório.
*/
public void setRodape(String strRodape) {
this.rodape = strRodape;
}
/**Determina o Conteúdo do Relatório.
*
* @param strTexto Conteúdo do Relatório.
*/
public void setTexto(String strTexto) {
this.texto = strTexto;
}
/**Gera um relatorio para a Impressão
*
* @param verDialogoDeImpressao Se quer ver o diálogo de impressão.
* @exception IOException SE ocorrer algum problema de I/O, ou na geração
* de conteúdo ou quando enviar o relatório a impressora.
*/
public void gerarImpressao(boolean verDialogoDeImpressao) throws IOException {
try {
JasperPrintManager.printReport(this.gerarConteudo(),
verDialogoDeImpressao);
} catch(JRException jrex) {
throw new IOException(jrex.getMessage());
}
}
/**Gera versao HTML do Relatório.
*
* @return String com o conteudo HTML do Relatório.
*/
public String gerarHTML() {
String strHTML = null;
OutputStream osHTML = null;
File fileHTML = null;
String fileName = System.currentTimeMillis() + ".html";
try {
strHTML = this.lerHTML(osHTML, fileHTML, fileName);
} catch(IOException ioex) {
throw new RuntimeException(ioex);
} catch(JRException jrex) {
throw new RuntimeException(jrex);
} finally {
try {
this.fecharStreams(osHTML, fileHTML, fileName);
} catch(IOException ioex) {
throw new RuntimeException(ioex);
}
}
return strHTML;
}
/**
*
* @return Stream com o versao PDF do Relatório.
* @throws IOException Se ocorrer um problema de I/O ou na criacao do
* Conteudo.
*/
public OutputStream gerarStreamPDF() throws IOException {
byte[] bytePDF = this.gerarPDF();
OutputStream osPDF = new
BufferedOutputStream(new ByteArrayOutputStream(bytePDF.length));
osPDF.write(bytePDF);
osPDF.flush();
return osPDF;
}
/**
*
* @return Vetor de bytes com a versao PDF do Relatório.
* @throws IOException Se ocorrer um problema de I/O.
*/
public byte[] gerarPDF() throws IOException {
byte[] bytePDF = null;
try {
bytePDF = JasperExportManager.exportReportToPdf(this.gerarConteudo());
} catch(JRException jrex) {
throw new IOException(jrex.getMessage());
}
return bytePDF;
}
}
A seguir está um programa de teste que fiz para testar a classe acima é um JFrame com 3 JtextAreas (para o cabeçalho, texto e rodapé) mais botões para gerar os tipos de relatório. Está um pouco desatualizado e provavelmente deverá ser modificado.
ackage jasperteste;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import dori.jasper.engine.*;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: </p>
* @author unascribed
* @version 1.0
*/
public class FrameJasper extends JFrame {
private static final String FILE_NAME = "DataSourceReport";
JPanel pnlCentral = new JPanel();
GridBagLayout gridBagLayout1 = new GridBagLayout();
JScrollPane scpTexto = new JScrollPane();
JTextArea txaTexto = new JTextArea();
JButton btnPdf = new JButton();
JButton btnImpressao = new JButton();
JScrollPane scpResultado = new JScrollPane();
JTextArea txaResultado = new JTextArea();
JButton btnLimpar = new JButton();
JButton btnCompilar = new JButton();
JButton btnPreencher = new JButton();
public FrameJasper() {
super("Teste do Jasper Reports");
try {
jbInit();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(450, 300);
}
catch(Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
pnlCentral.setLayout(gridBagLayout1);
btnPdf.setText("Gerar PDF");
btnPdf.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
btnPdf_actionPerformed(e);
}
});
btnImpressao.setText("Gerar Impressão");
btnImpressao.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
btnImpressao_actionPerformed(e);
}
});
btnLimpar.setText("Limpar Resultados");
btnLimpar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
btnLimpar_actionPerformed(e);
}
});
txaResultado.setEditable(false);
btnCompilar.setText("Compilar");
btnCompilar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
btnCompilar_actionPerformed(e);
}
});
btnPreencher.setText("Gerar Preenchimento");
btnPreencher.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
btnPreencher_actionPerformed(e);
}
});
this.getContentPane().add(pnlCentral, BorderLayout.CENTER);
pnlCentral.add(scpTexto, new GridBagConstraints(0, 0, 1, 3, 1.0, 2.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 0), 0, 0));
scpTexto.getViewport().add(txaTexto, null);
pnlCentral.add(btnPdf, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
pnlCentral.add(btnImpressao, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
pnlCentral.add(scpResultado, new GridBagConstraints(0, 3, 1, 2, 1.0, 1.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 0), 0, 0));
scpResultado.getViewport().add(txaResultado, null);
pnlCentral.add(btnCompilar, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
pnlCentral.add(btnLimpar, new GridBagConstraints(1, 4, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
pnlCentral.add(btnPreencher, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
}
void btnPdf_actionPerformed(ActionEvent e) {
if((txaTexto.getText() != null) || (!"".equals(txaTexto.getText().trim()))) {
txaResultado.append("-------------------------|n");
try {
txaResultado.append("Iniciando geração de PDF |n");
File jasperFile = new File(FILE_NAME + ".jasper");
if(!jasperFile.exists()) {
txaResultado.append("Compilando XML|n");
this.compilar();
}
txaResultado.append("Gerando Conteudo|n");
long start = System.currentTimeMillis();
InputStream ipsJasper = new BufferedInputStream(new
FileInputStream(jasperFile));
JasperPrint jp = this.gerarConteudo(ipsJasper);
txaResultado.append("Conteudo Gerado. Tempo: " +
(System.currentTimeMillis() - start) + "|n");
txaResultado.append("Gerando PDF|n");
start = System.currentTimeMillis();
JasperExportManager.exportReportToPdfFile(jp, "teste.pdf");
txaResultado.append("Terminando geração de PDF. Tempo: " +
(System.currentTimeMillis() - start) + "|n");
} catch(Exception ex) {
txaResultado.append(ex.getMessage() + "|n");
}
txaResultado.append("-----------------------|n");
}
}
void btnImpressao_actionPerformed(ActionEvent e) {
if((txaTexto.getText() != null) || (!"".equals(txaTexto.getText().trim()))) {
txaResultado.append("-------------------------|n");
try {
txaResultado.append("Iniciando geração de Impressão |n");
File jasperFile = new File(FILE_NAME + ".jasper");
if(!jasperFile.exists()) {
txaResultado.append("Compilando XML|n");
this.compilar();
}
txaResultado.append("Gerando Conteudo|n");
long start = System.currentTimeMillis();
InputStream ipsJasper = new BufferedInputStream(new
FileInputStream(jasperFile));
JasperPrint jp = this.gerarConteudo(ipsJasper);
txaResultado.append("Conteudo Gerado. Tempo: " +
(System.currentTimeMillis() - start) + "|n");
txaResultado.append("Gerando Impressão|n");
start = System.currentTimeMillis();
JasperPrintManager.printReport(jp, false);
txaResultado.append("Terminando geração de Impressão. Tempo: " +
(System.currentTimeMillis() - start) + "|n");
} catch(Exception ex) {
txaResultado.append(ex.getMessage() + "|n");
}
txaResultado.append("-----------------------|n");
}
}
void btnLimpar_actionPerformed(ActionEvent e) {
txaResultado.setText(null);
}
void btnCompilar_actionPerformed(ActionEvent e) {
try {
this.compilar();
} catch(Exception ex) {
txaResultado.append(ex.getMessage() + "|n");
}
}
private void compilar() throws JRException {
txaResultado.append("-----------------------|n");
txaResultado.append("Iniciando Compliação ..." + "|n");
long start = System.currentTimeMillis();
JasperCompileManager.compileReportToFile(FILE_NAME + ".xml");
txaResultado.append("Compilação Concluida - Tempo = " +
(System.currentTimeMillis() - start) + " ms|n");
txaResultado.append("-----------------------|n");
}
public static void main(String[] args) {
FrameJasper frameJasper = new FrameJasper();
frameJasper.show();
}
void btnPreencher_actionPerformed(ActionEvent e) {
if((txaTexto.getText() != null) || (!"".equals(txaTexto.getText().trim()))) {
txaResultado.append("-----------------------|n");
try {
File jasperFile = new File(FILE_NAME + ".jasper");
if(!jasperFile.exists()) {
txaResultado.append("Compilando XML|n");
this.compilar();
}
InputStream ipsJasper = new BufferedInputStream(new
FileInputStream(jasperFile));
JasperPrint jp = this.gerarConteudo(ipsJasper);
} catch(Exception ex) {
txaResultado.append(ex.getMessage() + "|n");
}
txaResultado.append("-----------------------|n");
}
}
private JasperPrint gerarConteudo(InputStream ipsJasper) throws JRException{
Map parameters = new HashMap(1);
System.out.print(txaTexto.getText() + "|n");
parameters.put("Texto", txaTexto.getText());
return JasperFillManager.fillReport(ipsJasper, parameters,
new JREmptyDataSource());
}
}
Onde “|n” sinifica "
".
Reconheço que não é exatamente um “Pequeno exemplo” mas espero que sirva para te esclarecer. Para mais detalhes dê uma olhada na API do Jasper e na documentação a respeito do XML de configuração.
Boa Sorte,