JasperReports: Font color problems in RTF

JasperReports can be used to provide reports in various formats like HTML, PDF and others based on a single XML template. You just need to call different exporters which get ReportPrint object and generate data in various formats. We have support of HTML, PDF, XLS, RTF and use version 3.0.1 of JasperReports in our application.

Today we have found a problem with the RTF exporter. In some cases the font colors are invalid in the RTF reports. In our case we had template which included the following components:

  1. Conditional style. It specifies the font color depending on the field content.
  2. CrossTab. It is used to display field data. This crosstab has cells which define textfields with the conditional style formatting

In this specific case all text was black in RTF while they were red/green/blue in the rest of the formats. Thank to Microsoft, RTF format is not binary. So strange… Small investigations of the RTF specification and the reason of the problem became vivid.

The table of colors in RTF looked like:
{colortbl ;red0green0blue0;red255green255blue255;red0green95blue179;red191green191blue191;}

And the text paragraph looked like:
{pardcb2 qlsl209 f0fs18cf5 GAP: 01 Jan, 2009 – 31 Dec, 2009plainpar}

“cf5” describes the reference to the fifth color in the colors table. But there are only four in the table of colors! Because of this invalid reference the appropriate color wasn’t used and displayed. The source of the problem is the implementation of RtfExporter. The table of colors is formed earlier than the conditional style color is applied.

I’m not really sure whether the latest version of JasperReports fixes this problem. In our case the application is in pre-production stage and using moving to the recent version is a bit risky. Creating a class which is inherited from RtfExporter and overrides parents behaviour might be a really good solution in this case but is not trivial. So we have detected a workaround which works for us.

Lets say you have three conditions which change font color. You’ll need to declare three additional styles which specify forecolor attributes with exactly the same colors and create 3 empty textfields with these styles for example in summary. This makes table of colors to be populated correctly and all the colors are displayed fine in RTF.