Boa tarde!
(acidotherwise) segue ai um código que utilizo para converter e exportar os relatórios para PDF, HTML, etc… , enviar por email os relatórios e também te mostra como utilizar o HashMap para passar os parametros, contem alguns comentários de problemas que podem ocorrer na interação entre os ireport e as demais linguagens e plataformas e entre as diferentes versões do ireport, é só implementar seus controles(botão) e chamar esse método.
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.sql.Connection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.imageio.ImageIO;
import javax.mail.internet.InternetAddress;
import javax.naming.NamingException;
import javax.sql.DataSource;
import mm.util.DateUtil;
import mm.util.FileUtil;
import mm.util.JasperUtil;
import mm.util.Mail;
import mm.util.NamedFileDataSource;
import mm.util.StrUtil;
import mm.util.Util;
import mm.util.web.ReportService;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.fill.JRSwapFileVirtualizer;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.util.JRSwapFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Report extends BaseReport implements ReportResponder
{
private static final Logger log = LoggerFactory.getLogger(Report.class);
private static final int SWAP_WHEN = 2;
private static final int SWAP_BLOCK_SIZE = 1000;
private static final int SWAP_GROW = 500;
private ReportManager manager;
private DataSource dataSource;
private HashMap<String, Object> parametros = new HashMap<String, Object>();
private String encoding = "UTF-8";
private String hash;
private String host;
private String port;
private String sistema;
private String funcao;
private String remetente;
private String destinatario;
private String observacoes;
public Report(ReportManager manager, Map<String, String[]> parameters) throws NamingException
{
this.manager = manager;
this.dataSource = manager.lookupDataSource();
for (Iterator<String> i = parameters.keySet().iterator(); i.hasNext(); )
{
String name = i.next();
Object value = parameters.get(name)[0];
if (name.startsWith("DATA_") || name.equals("DATA"))
value = new Date(Long.parseLong((String) value));
if (ReportService.PARAM_FORMATO.equals(name))
formato = (String) value;
else if (ReportService.PARAM_ENCODING.equals(name))
encoding = (String) value;
else if (ReportService.PARAM_HASH.equals(name))
hash = (String) value;
else if (ReportService.PARAM_HOST.equals(name))
host = (String) value;
else if (ReportService.PARAM_PORT.equals(name))
port = (String) value;
else if (ReportService.PARAM_SISTEMA.equals(name))
sistema = (String) value;
else if (ReportService.PARAM_FUNCAO.equals(name))
funcao = (String) value;
else if (ReportService.PARAM_REMETENTE.equals(name))
remetente = (String) value;
else if (ReportService.PARAM_DESTINATARIO.equals(name))
destinatario = (String) value;
else if (ReportService.PARAM_OBSERVACOES.equals(name))
observacoes = (String) value;
else if (value != null)
parametros.put(name, value);
}
}
@Override
public void run()
{
try
{
log.info("Iniciando execução do relatório " + funcao);
File jrxmlFile = new File(
manager.getJasperReportsPath(sistema), funcao + ".jrxml");
File jasperFile = new File(
manager.getJasperReportsPath(sistema), funcao + ".jasper");
File tempFile0;
if (jrxmlFile.exists() || jasperFile.exists())
tempFile0 = genJasper(dataSource, parametros);
else
tempFile0 = genOracle(parametros);
tempFile = tempFile0;
if (destinatario != null)
{
// Obs.: Apenas relatórios em PDF serão enviados corretamente por e-mail.
if (observacoes == null)
observacoes = "Relatório em anexo.";
try
{
Mail mail = new Mail();
mail.setFrom(new InternetAddress(remetente));
InternetAddress[] destAddress = Mail.parseAddressList(destinatario);
if (Util.getConfig() == Util.Config.PRODUCAO)
mail.setToRecipients(destAddress);
else
{
// Envia para o mesmo email do remetente, mas com o nome do destinatário.
mail.setToRecipient(new InternetAddress(
mail.getFrom().getAddress(), destAddress[0].getPersonal()));
}
mail.setSubject("Relatório " + funcao);
mail.setBody(observacoes);
mail.getAttachments().add(new NamedFileDataSource(tempFile,
funcao + "." + formato));
mail.send();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
finally
{
tempFile.delete();
}
}
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public void close()
{
if (!StrUtil.isEmpty(hash))
return;
try
{
if (tempFile != null)
tempFile.delete();
if (tempDir != null)
FileUtil.deleteDir(tempDir);
}
catch (Exception e)
{
log.error("Erro finalizando relatório", e);
}
}
@Override
protected boolean deleteMainFileAfterRespond()
{
return StrUtil.isEmpty(hash);
}
private File genJasper(DataSource dataSource, HashMap<String, Object> parametros)
throws Exception
{
String s = manager.getJasperReportsPath(null).getAbsolutePath();
if (!s.endsWith(File.separator))
s += File.separator;
parametros.put("SUBREPORT_DIR", s);
File reportFile = JasperUtil.getReport(manager.getJasperReportsPath(sistema),
funcao, false);
// Cria um virtualizador, para evitar uso excessivo de memória.
JRSwapFileVirtualizer virtualizer = new JRSwapFileVirtualizer(SWAP_WHEN,
new JRSwapFile(System.getProperty("java.io.tmpdir"), SWAP_BLOCK_SIZE, SWAP_GROW));
parametros.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
try
{
Connection conn = dataSource.getConnection();
try
{
JasperReport jasperReport;
// Alguns relatórios salvos com o iReport 3.0 apresentam problema de
// carregamento com o JasperReports 3.6.x Tentamos recompilar para contornar.
try
{
jasperReport = (JasperReport) JRLoader.loadObject(reportFile.getPath());
}
catch (JRException e)
{
log.info("Erro ao carregar relatório. Tentando recompilá-lo.", e);
reportFile = JasperUtil.getReport(manager.getJasperReportsPath(sistema),
funcao, true);
jasperReport = (JasperReport) JRLoader.loadObject(reportFile.getPath());
}
for (JRParameter param : jasperReport.getParameters())
{
Object value = parametros.get(param.getName());
if (value != null)
{
if (param.getValueClass() == Integer.class)
parametros.put(param.getName(), Integer.valueOf((String) value));
else if (param.getValueClass() == Long.class)
parametros.put(param.getName(), Long.valueOf((String) value));
else if (param.getValueClass() == BigDecimal.class)
parametros.put(param.getName(), new BigDecimal((String) value));
else if (param.getValueClass() == Boolean.class)
parametros.put(param.getName(), Boolean.parseBoolean((String) value));
}
}
parametros.put(JRParameter.REPORT_LOCALE, Util.getLocale());
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,
parametros, conn);
File tempFile = null;
try
{
JRExporter exporter;
if ("pdf".equals(formato))
{
exporter = new JRPdfExporter();
tempFile = File.createTempFile("tmprel", "." + formato);
}
else if ("html".equals(formato))
{
String imagesUri = "";
if (host != null && port != null)
imagesUri = "http://" + host + ":" + port;
exporter = new JRHtmlExporter();
tempDir = new File(manager.getReportCachePath(),
manager.getReportCachePrefix() + hash);
if (!tempDir.mkdir())
{
throw new Exception("Diretório " + tempDir.getAbsolutePath() +
" já existia");
}
tempFile = new File(tempDir, HTML_FILENAME);
exporter.setParameter(JRHtmlExporterParameter.IMAGES_DIR, tempDir);
exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI,
imagesUri + "/ExecRelatorios/ReportCached/" + hash + "/");
exporter.setParameter(JRHtmlExporterParameter.SIZE_UNIT,
JRHtmlExporterParameter.SIZE_UNIT_PIXEL);
exporter.setParameter(JRHtmlExporterParameter.HTML_HEADER,
"<center><table cellpadding=\"1\" cellspacing=\"0\"><tr><td>");
exporter.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, "");
exporter.setParameter(JRHtmlExporterParameter.HTML_FOOTER,
"</td></tr></table></center>");
exporter.setParameter(
JRHtmlExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,
Boolean.TRUE);
exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, encoding);
}
else
throw new Exception("Formato de relatório inválido");
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_FILE, tempFile);
exporter.exportReport();
if (tempDir != null)
{
// Converte imagem para GIF, pois o Internet Explorer 6 não exibe arquivos
// PNG corretamente.
for (String name : tempDir.list())
{
if (tempFile.equals(new File(tempDir, name)))
continue;
File file = new File(tempDir, name);
BufferedImage image = ImageIO.read(file);
BufferedImage imageCopy = new BufferedImage(
image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
imageCopy.getGraphics().drawImage(image, 0, 0, Color.WHITE, null);
image = imageCopy;
ImageIO.write(image, "gif", file);
}
}
return tempFile;
}
catch (Exception e)
{
if (tempFile != null)
tempFile.delete();
throw e;
}
}
finally
{
conn.close();
}
}
finally
{
virtualizer.cleanup();
}
}
private File genOracle(HashMap<String, Object> parametros) throws Exception
{
File tempFile = File.createTempFile("tmprel", ".pdf");
File reportPath = new File(manager.getOracleReportsPath(sistema), funcao + ".rdf");
String cmd = manager.getOracleReportsCmd();
cmd += " Destype=file paramform=no desformat=PDF";
cmd += " module=" + reportPath.getAbsolutePath();
cmd += " desname=" + tempFile.getAbsolutePath();
for (Entry<String, Object> param : parametros.entrySet())
{
Object value = param.getValue();
if (value instanceof Date)
value = DateUtil.formatDMA((Date) value);
/*** Colocar os parâmetros entre aspas causa erros no servidor Unix.
else
value = value.toString().replace('"', '\'');
cmd += " \"p_" + param.getKey() + "=" + value + "\"";
***/
cmd += " p_" + param.getKey() + "=" + value;
}
log.debug("cmd: " + cmd);
Process process = Runtime.getRuntime().exec(cmd);
if (process.waitFor() != 0)
{
tempFile.delete();
StringBuilder sb = new StringBuilder();
String s;
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getErrorStream()));
sb.append("--- stderr ---\n");
while ((s = reader.readLine()) != null)
sb.append(s + "\n");
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
sb.append("\n--- stdout ---\n");
while ((s = reader.readLine()) != null)
sb.append(s + "\n");
throw new Exception("Erro ao gerar relatório. Cmd: " + cmd + "\n" +
sb.toString());
}
return tempFile;
}
}
Att.