Search code examples
javajasper-reports

Soft hyphen support in JasperReports


Problem: an existing system which prints user entered content (in many different languages) in a PDF report in some cases ends up breaking words incorrectly, for example "exampl-e".

Soft hyphen, is a special invisible symbol which is put in between words and when a word is not fitting and must be broken that symbol will hint the system where it makes sense to do the break.

If the user entered "exam<theMagicSymbol>ple" then if the word was to be broken it would be like "examp-ple".

Question: Are there any existing solutions for this in jasperReprots?

Note I'm new to this library, but I couldn't find anything close to soft wraps support...


Solution

  • The easiest way is to use the directly the textFieldExpression (in your example use regex "<[^>]*>" before printing text) es.

    <textFieldExpression><![CDATA[$F{field1}.replaceAll("<[^>]*>", "")]]></textFieldExpression>
    

    Other solutions are:

    On the jasper textField you specify markup="html"

    Example:

    <textField>
       <reportElement x="0" y="4" width="100" height="20" uuid="2cfd9640-f7ce-4bbe-a024-7b1b53d3b72b"/>
        <textElement markup="html">
          <paragraph lineSpacing="Single"/>
        </textElement>
        <textFieldExpression><![CDATA[$F{field1}]]></textFieldExpression>
    </textField>
    

    This will process the text as if it was html, all text formatting code will work as es. <b>Test</b> will result it Test and all none text formatting code will be removed (es. table, img ecc).

    Final solution

    If you still are not happy, you need more advanced code to format your text, the solution is your own class that format the text.

    Simple example:

    <textField>
        <reportElement x="0" y="4" width="100" height="20" uuid="2cfd9640-f7ce-4bbe-a024-7b1b53d3b72b"/>
        <textElement markup="none">
         <paragraph lineSpacing="Single"/>
        </textElement>
        <textFieldExpression><![CDATA[com.my.package.JasperReportTextHandler.format($F{field1})]]></textFieldExpression>
    </textField>
    

    Create the java class JasperReportTextHandler in package com.my.package with static method:

    class JasperReportTextHandler{
      public static String format(String value){
       //... do your stuff regEx, split...
       return value;
      }
    }
    

    Just be sure that the JasperReportTextHandler is in class path when you execute the report.

    Have Fun