Thursday, January 23, 2014

Ireport chart from java

Even though it is simple to create chart from java code , lack of tutorial make it difficult to do ..

Here I use java map to pass values .

List<Map<String, Object>> chartMapList = null;

Inside looping
                chartMap = new HashMap<String, Object>();
                chartMap.put(FIELD_TYPE, key); //x axis
chartMap.put(FIELD_MONTH, monthKey); //y axis
chartMap.put(FIELD_DIRECT_HOURS, dataMap.get(FIELD_DIRECT_HOURS)); //values
chartMap.put(FIELD_AVAILABLE_HOURS, dataMap.get(FIELD_AVAILABLE_HOURS)); //values
chartMapList.add(chartMap);

Then add map list to the main map

parameters.put("ChartDS", new JRMapCollectionDataSource(chartMapList))

Pass to jasper
jasperPrint = JasperFillManager.fillReport(jasperReport,parameters,new JREmptyDataSource());

OK above is the java part .

Let us see iReport part
Step 1:
1a.Drag chart control into you ireport and select the type of chart you want

I take line chart.

1b.Add a parameter say "ChartDS"


1c.Give parameter class type : net.sf.jasperreports.engine.JRDataSource

1d.Default value expression : $P{REPORT_PARAMETERS_MAP}.get( "ChartDS" )



Step 2
2a. Create a sub dataset

2b.Create corresponding fields

3. Setting chart properties
3a.Take chart properties and select chart data tab.
3b. Clcik the tab Connection/Data Source Exp. Give the value $P{ChartDS}


4.Click the Detail section

4a . Select Add button to add the values

similarly give another axis too.

Once finish , compile and run ...Here you got your beautiful chart ...

Generate odt report with list input - iReport

                byte odtByte[] = (byte[])null;
ByteArrayOutputStream byArrOutputStr = null;
try
{

//pdfByte = JasperExportManager.exportReportToPdf(jasperprint);
byArrOutputStr = new ByteArrayOutputStream();

JROdtExporter exporter = new JROdtExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST,list);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, byArrOutputStr);
exporter.exportReport();
odtByte = byArrOutputStr.toByteArray();
} catch(JRException e) {
logger.error("Error in creating ODT file : "+e);
} catch(Exception e) {
logger.error("Error in creating ODT file : "+e);
} finally {
//to close resource
try {
byArrOutputStr.close();
} catch (IOException e) {
// Ignored;
}
}