Search code examples
javajasper-reports

dynamic column width with jasper report


I have a quite basic template in .jrxml which contains crosstab element with header and one cell.

I am using crosstab, because i have dynamic number of columns. I am giving datasource as parameter from bean so i know a number of columns right before report generation. I want columns of "dynamic" width.

I am trying to read existing jrxml and then repair column width based on number of columns right before report generation.

Until now i found out how to load file and and i am getting right band(i know it's always second) and right element(dynamicCrosstab). I can't find out how to set column width.

My current code:

JasperDesign template = JRXmlLoader.load("C:\\repos\\templateFile.jrxml");
JRBand[] bands = template.getAllBands();
//getting crosstab
JRElement element = bands[1].getElementByKey("dynamicCrosstab");
if (element instanceof JRCrosstab) {
    //missing code to get cells and set width
}
//compiling template before using it to generate report
JasperCompileManager.compileReportToFile(template, "C:\\repos\\templateFile.jasper");

Tnx for any help in advance.


Solution

  • it's not nice solution but it works.

        if (element instanceof JRDesignCrosstab) {
            //repair cells
            List<JRCrosstabCell> celice = ((JRDesignCrosstab) element).getCellsList();
            //repair content in cells
            ((JRDesignCrosstabCell) celice.get(0)).setWidth(newWidth);
            for (JRChild child : ((JRDesignCrosstabCell) celice.get(0)).getContents().getChildren()) {
                if(child instanceof JRDesignTextField){
                    ((JRDesignTextField) child).setWidth(newWidth);
                }
            }
            //repair content in header
            List<JRCrosstabColumnGroup> headerji = ((JRDesignCrosstab) element).getColumnGroupsList();
            for (JRChild child : ((JRDesignCellContents) headerji.get(0).getHeader()).getChildren()) {
                ((JRDesignTextField) child).setWidth(newWidth);
            }
        }