Vishal Zanzrukia
Vishal Zanzrukia

Reputation: 4973

Dynamic Alignment based on cell value (Content) in Jasper Reports

I am using DynamicJasper (3.0.13) API for generating PDF.

Is it possible to keep field value alignment center if value is "-" otherwise horizontal. My current jrxml field is as given follow.

<textField>
    <reportElement uuid="105ab8ed-5b63" x="0" y="0" width="200" height="20"/>
        <textElement>
            <font size="15"/>
        </textElement>
        <textFieldExpression>
            <![CDATA[$F{firstName}]]>
        </textFieldExpression>
</textField>

Upvotes: 2

Views: 2398

Answers (2)

Vishal Zanzrukia
Vishal Zanzrukia

Reputation: 4973

finally I got answer as per my structure for creating dynamic jasper template.

/**----------START------setting up conditional style and adding it in jasper design---------------*/
String expressionText = "$F{firstName}.trim().equals("-")";
JRDesignExpression cellExpression = new JRDesignExpression();
cellExpression.setText(expressionText);

JRDesignConditionalStyle conditionalCellStyle = new JRDesignConditionalStyle();
JRDesignStyle baseStyle = new JRDesignStyle();


conditionalCellStyle.setParentStyle(baseStyle);
conditionalCellStyle.setConditionExpression(cellExpression);
conditionalCellStyle.setHorizontalAlignment(HorizontalAlignEnum.CENTER);

baseStyle.setName("CONDITIONAL_STYLE");
baseStyle.setHorizontalAlignment(HorizontalAlignEnum.LEFT);
baseStyle.setBold(Boolean.FALSE);
baseStyle.setItalic(Boolean.FALSE);
baseStyle.setStrikeThrough(Boolean.FALSE);
baseStyle.setUnderline(Boolean.FALSE);
baseStyle.addConditionalStyle(conditionalCellStyle);

getJasperDesign().addStyle(baseStyle); //(here getJasperDesign() is a object of JasperDesign)
/**---------END-------setting up conditional style and adding it in jasper design---------------*/


/**----------START------setting up my text field---------------*/
JRDesignTextField cellTextField = new JRDesignTextField();
/**---------------------setting all other properties of textField--------------------*/
cellTextField.setStyle(getJasperDesign().getStylesMap().get("CONDITIONAL_STYLE")); //(here getJasperDesign() is a object of JasperDesign)
/**----------END------setting up my text field---------------*/

Upvotes: 0

Alex K
Alex K

Reputation: 22857

Yes, it is possible.

1) You can one of this methods: ColumnBuilder.addConditionalStyles or ColumnBuilder.addConditionalStyle

2) You should implement your own ConditionStyleExpression


The working sample

The code

The code of implementation ConditionStyleExpression:

public class FieldComparator extends ConditionStyleExpression implements CustomExpression {

    private String fieldName;
    private String valueToCheck;

    public FieldComparator(String fieldName, String valueToCheck) {
        this.fieldName = fieldName;
        this.valueToCheck = valueToCheck;
    }

    @Override
    public Object evaluate(Map fields, Map variables, Map parameters) {
        Object value = getCurrentValue();
        if (value == null)
            return null;

        if (!fields.containsKey(fieldName)) {
            return Boolean.FALSE;
        }

        if (valueToCheck == null) {
            return Boolean.FALSE;
        }

        return Boolean.valueOf(valueToCheck.equals(fields.get(fieldName)));
    }

    @Override
    public String getClassName() {
        return Boolean.class.getName();
    }
}

I've compared the field's value with string passed via the parameter.

The code for building report:

public class ConditionalStylesTest extends BaseDjReportTest {

    public static void main(String[] args) throws Exception {
        ConditionalStylesTest test = new ConditionalStylesTest();
        test.testReport();
        test.exportToJRXML();
        JasperViewer.viewReport(test.jp);
    }

    @Override
    public DynamicReport buildReport() throws Exception {
        DynamicReportBuilder drb = new DynamicReportBuilder();
        Integer margin = 20;
        drb.setTitle("NBA Players")
                .setTitleHeight(30)
                .setDetailHeight(15)
                .setLeftMargin(margin)
                .setRightMargin(margin)
                .setTopMargin(margin)
                .setBottomMargin(margin)
                .setPrintBackgroundOnOddRows(true)
                .setColumnsPerPage(1)
                .setColumnSpace(1);

        drb.addColumn(ColumnBuilder.getNew().setColumnProperty("age", Integer.class.getName())
                .setTitle("Age").setWidth(30).setFixedWidth(true).build());
        drb.addColumn(ColumnBuilder.getNew().setColumnProperty("name", String.class.getName())
                .setTitle("Name").setWidth(100).setFixedWidth(true).build());
        drb.addColumn(ColumnBuilder.getNew().setColumnProperty("currentTeam", String.class.getName())
                .setTitle("Team").setWidth(120).addConditionalStyle(createConditionalStyle()).setFixedWidth(true).build());

        drb.setUseFullPageWidth(true);

        return drb.build();
    }

    private ConditionalStyle createConditionalStyle() {
        Style style = new Style();
        style.setHorizontalAlign(HorizontalAlign.CENTER);

        ConditionStyleExpression expression = new FieldComparator("currentTeam", "-");

        return new ConditionalStyle(expression, style);
    }

    @Override
    protected JRDataSource getDataSource() {
        return new JRBeanCollectionDataSource(Players.get());
    }
}

In this sample I've used the JavaBean datasource. And I've use conditional style for currentTeam field.

The bean Player:

public class Player {

    private Integer age;
    private String name;
    private String currentTeam;

    public Player(Integer age, String name, String team) {
        this.age = age;
        this.name = name;
        this.currentTeam = team;
    }

    public Integer getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    public String getCurrentTeam() {
        return currentTeam;
    }
}

The result

The result generated in JasperViewer:

enter image description here

As you can see the string "-" has Center alignment.

Upvotes: 2

Related Questions