Thursday, August 03, 2006

Java code to create Reports using jasper and text data

Copy paste the code below in Editplus to understand it. It is pretty straight forward to read and understand.
"generateLabels" is a function that will take a string which is really a txt datasource for your designed jrxml file. I used ireports to design the jrxml.

jrxml will return a byte array that can be displayed(response.write) as embeded pdf(or any other format) in the user browser.


public byte[] generateLabels(String dataSource)

{ byte[] pdfBytes=null;

JasperDesign jrDesign;

JasperReport jrReport;

JasperPrint jrPrint;

try{

ByteArrayInputStream dataSourceByteInputStream = new

ByteArrayInputStream(dataSource.getBytes());

JRCsvDataSource jrCsvDs = new

JRCsvDataSource(dataSourceByteInputStream);

String[] header={"label", "details"};

jrCsvDs.setFieldDelimiter(',');

jrCsvDs.setRecordDelimiter(";");

jrCsvDs.setColumnNames(header);

InputStream jrStream =

FileUtil.readConfigFileFromClassPath(this.getClass(),"etc/label.jrxml").getByteStream();

Map parameters = new HashMap();

parameters.put("ReportTitle", "Labels");

jrDesign = JRXmlLoader.load(jrStream);

jrReport =

JasperCompileManager.compileReport(jrDesign);

jrPrint =

JasperFillManager.fillReport(jrReport,parameters,jrCsvDs);

JasperExportManager.exportReportToPdfFile(

jrPrint,"labels.pdf");

pdfBytes =

JasperExportManager.exportReportToPdf(jrPrint);

PdfReader pdfr = new PdfReader(pdfBytes);

ByteArrayOutputStream baos = new

ByteArrayOutputStream();

PdfStamper stamp = new PdfStamper(pdfr, baos);

stamp.addJavaScript(

"this.print({bUI: false, bSilent: false});\r");

stamp.close();

pdfBytes = baos.toByteArray();

}

catch(Exception ex)

{

ex.printStackTrace();

}

return pdfBytes;

}

0 Comments:

Post a Comment

<< Home