JasperReports: Multiline labels on the bar charts

JasperReports: Multiline labels on the bar charts

Displaying bar charts in the limited space usually truncates category labels and it makes the chart not readable in some cases:

Not so beautiful, right? So lets fix this problem.

The template format of JasperReports is a bit limited and does not allow to pass some required attributes to jfreechart directly. However for every chart you can specify your own customizer class


<barChart>
<chart hyperlinkType=“None” customizerClass=“org.test.MyCustomizer”>

The main idea of the fix is to allow displaying bar chart labels in two lines. CategoryAxis class from jfreechart is used to render X-axis and its labels. It has method setMaximumCategoryLabelLines which allows to specify how much lines should be used to display labels.

So the full code looks like.

package org.test;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import net.sf.jasperreports.engine.JRChart;
import net.sf.jasperreports.engine.JRChartCustomizer;

public class MyCustomizer implements JRChartCustomizer {
 &nbsp@Override
  public void customize(JFreeChart chart, JRChart jasperChart) {
    if(chart == null) return;
    if(!(chart.getPlot() instanceof CategoryPlot)) return;
    CategoryPlot categoryPlot = (CategoryPlot) chart.getPlot();
    categoryPlot.getDomainAxis().setMaximumCategoryLabelLines(2);
  }
}

An now our chart looks like:

As you can see the labels in the chart are not truncated no more.