Saturday, July 26, 2008

Struts2, JFreeChart - Transparent Charts

For my Struts 2 application I needed to create a chart using
JFreechart
that has a transparent background (rendered as png). Well, I thought
this would be trivial to do as Struts 2 ships with a
plugin
for it...

I created a simple action that creates a chart:

     public final String execute() throws Exception {

final DefaultCategoryDataset categorydataset = new DefaultCategoryDataset();

this.chart = ChartFactory.createLineChart("MyTitle",
"categoryLabel", "valueLabel", categorydataset,
PlotOrientation.VERTICAL, true, true, false);
chart.setBackgroundPaint(new Color(255,255,255,0));

return SUCCESS;
}



In my Struts XML file I put this:


<br /><action name="createChart"
class="com.hillert.sandbox.ChartAction"><br /> <result
name="success" type="chart"><br /> <param name="width">200</param><br /> <param
name="height">150</param><br /> </result><br /></action>



Well, the result is that my chart gets generated and rendered but
without transparency.


After asking the internet's oracle for guidance, Google returns a fews
results, e.g
this
one

that indicate that JFreeChart by default does not generate Alpha
Transparency for Pngs.


The solution however lies in customizing the jFreeChart Struts plugin.
In it's shipped version the plugin is calling:

ChartUtilities.writeChartAsPNG(os, chart, width, height);



For transparency you need to use the
extended
method call

. Simply change the method call above to:



ChartUtilities.writeChartAsPNG(os, chart, width, height, true, 0);



As a result aplha transparency is enabled and my chart is generated with
a transparent background.


Just for completeness, here is my action configuration using the
customized jFreeChart plugin:

<package name="chart"
extends="jfreechart-default" namespace="/chart"><br /><result-types><br /><result-type
name="customChart" class="org.jrecruiter.web.CustomChartResult"><br /></result-type><br /><br /><action
name="createChart" class="com.hillert.sandbox.ChartAction"><br /><result
name="success" type="customChart"><br /> <param name="width">200</param><br /> <param
name="height">150</param><br /></result><br /></action></result-types></package>

2 comments:

Anonymous said...

Please could we have the src code for download.

Anonymous said...

Please could the src code be downloaded.

Thanks for the Help.

Regards,
Ajay