Question

I'm using JasperReports 5.5.1 to generate reports from Java. I designed the reports using Jaspersoft Studio. The report has several charts of different types and I have some problems when trying to localize the report using a ResourceBundle passed in the REPORT_RESOURCE_BUNDLE parameter. All the texts in the report are translated correctly except for the ones in the charts. I filled the keyExpression, labelExpression and seriesExpression with $R{STRING_KEY}, but the report is filled with the STRING_KEY instead of its value in the properties file. The title of the charts though is correctly translated.

Can anyone help me with this issue?

Was it helpful?

Solution

I found a solution.

First create a class responsible for getting the localized string from a specific resource bundle.

public class ReportLocalizer {

    private static String resourceBundleBaseName = "com.company.package.boundle_name";

    public static String getLocalizedString(Locale locale, String key) {
        ResourceBundle resourceBundle = ResourceBundle.getBundle(resourceBundleBaseName, locale);
        return resourceBundle.getString(key);
    }
}

Set the desired locale using JasperReports' parameters:

Map<String, Object> parameters = new HashMap<String, Object>();
...
parameters.put(JRParameter.REPORT_LOCALE, locale);
...
final JasperPrint print = JasperFillManager.fillReport(report, parameters, datasource);

To translate a string in a chart, pass it together with the report's locale to ReportLocalizer's getLocalizedString method.

[CDATA[com.company.package.ReportLocalizer.getLocalizedString($P{REPORT_LOCALE}, "string_key")]]>

For example, we can localize a pie chart showing the amount of men and women this way:

<pieChart>
    <chart>
    ...
    </chart>
    <pieDataset>
        <dataset>
        ...
        </dataset>
        <keyExpression><![CDATA[com.company.package.ReportLocalizer.getLocalizedString($P{REPORT_LOCALE}, $F{gender}.toString())]]></keyExpression>
        <valueExpression><![CDATA[$F{amount}]]></valueExpression>
        <labelExpression><![CDATA[String.valueOf($F{amount})]]></labelExpression>
    </pieDataset>
    <piePlot>
    ...
    </piePlot>
</pieChart>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top