Dynamic Jasper Report for beginners

June 29, 2009

Dynamic Jasper

In Jasper reports the creation of the Jrxml template is tedious and it takes some time to learn. You need to use some kind of tool like iReport to create the Jasper templates and then use them. Maintaining and modifying will not be easy till you master it. And using this for dynamic report become difficult and dynamically creating the Jrxml programmatically is a challenging task.

For such needs Dynamic Jasper is available for rescue. This reduces the complexity of creating Jrxml templates manually. We will be able to generate Jrxml programmatically using API. Also the reports can be generated on the fly by defining the columns at run time. This is so much flexible that the columns, column width, font, and styles every thing can be dynamic. Also it is flexible you will be able to reuse the existing Jrxml templates.

The Dynamic Jasper report support many output formats like Excel, CVS, XML, PDF, HTML , RTF, Text etc.. It supports many data sources like JDBC, Hibernate, EJB, Java Bean etc.,

Let us learn from examples. You may refer http://www.dynamicjasper.com to know more about this. Here I will try to give a simple example to begin with and understand.

Let us begin with a simple excel report.
We are generating Sales Report for November and December 2006.

Create DynamicDemoBean
We create a new Bean class DynamicDemoBean.java which we will be using to pass data for report generation.

package src;

public class DynamicDemoBean {
private String state;
private String branch;
private String productLine;
private String item;
private long itemCode;
private long quantity;
private float amount;
private String remarks;

public DynamicDemoBean(float amount, String branch, long itemCode,
String item, String line, long quantity, String state, String remarks) {
super();
this.amount = amount;
this.branch = branch;
this.itemCode = itemCode;
this.item = item;
productLine = line;
this.quantity = quantity;
this.state = state;
this.remarks = remarks;
}

public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public long getItemCode() {
return itemCode;
}
public void setItemCode(long itemCode) {
this.itemCode = itemCode;
}
public String getProductLine() {
return productLine;
}
public void setProductLine(String productLine) {
this.productLine = productLine;
}
public long getQuantity() {
return quantity;
}
public void setQuantity(long quantity) {
this.quantity = quantity;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}

public String getRemarks() {
return remarks;
}

public void setRemarks(String remarks) {
this.remarks = remarks;
}

}

Dynamically Create Report

Here we are planning to generate an Excel report. We generate JasperPrint object dynamically and using this we create the excel report.

You may refer the getFirstReport() method where the columns are dynamically created and added. As there are no jrxml files are used the styles need to be created and applied for columns, headers etc. Dynamically adding columns can be very easy too.

public class DynamicJasper {
/**
* @param args
*/
public static void main(String[] args) {

try{
//build report
JasperPrint jp = buildReport();

//export report
JExcelApiExporter exporter = new JExcelApiExporter();

exporter.setParameter(JExcelApiExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);

exporter.setParameter(JExcelApiExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);
exporter.setParameter(JExcelApiExporterParameter.JASPER_PRINT, jp);
exporter.setParameter(JExcelApiExporterParameter.OUTPUT_FILE_NAME, “e:/dynamicDemo.xls”);
exporter.setParameter(JExcelApiExporterParameter.IGNORE_PAGE_MARGINS,
Boolean.TRUE);
exporter.setParameter(JExcelApiExporterParameter.OFFSET_X, 0);
exporter.setParameter(JExcelApiExporterParameter.IS_IGNORE_CELL_BORDER, Boolean.FALSE);
exporter.setParameter(JRXlsExporterParameter.SHEET_NAMES, new String[]{“November”, “December”});
exporter.exportReport();

}catch(JRException je){
je.printStackTrace();
}catch(ColumnBuilderException ce){
ce.printStackTrace();
}catch(ClassNotFoundException cfe){
cfe.printStackTrace();
}

}

private static JasperPrint buildReport() throws ColumnBuilderException, JRException, ClassNotFoundException{
Style headerStyle = getHeaderStyle();
Style detailStyle = new Style();
detailStyle.setBorder(Border.THIN);

//build first report
FastReportBuilder firstReport = getFirstReport(headerStyle, detailStyle);
DynamicReport firstDynaRep = firstReport.build();

//build second report
FastReportBuilder secondReport = getSecondReport(headerStyle, detailStyle);
DynamicReport secondDynaRep = secondReport.build();

//Prepare data
Object[] obj = new Object[3];

obj[0]= new DynamicDemoBean(100.00f, “San Jose”, 200, “Tojo”, “Vintage 2000”, 50, “CA”, “Tojo is a finer veriety of wine produced from the California wine yards. It has been produced to the industy standards. Tojo is a finer veriety of wine produced from the California wine yards. It has been produced to the industy standards.”);

obj[1]= new DynamicDemoBean(110f, “San Jose”, 120, “Spinster”, “Vintage 2000”, 50, “CA”, “Spinster is a finer veriety of wine produced from the California wine yards. It has been produced to the industy standards.”);

obj[2]= new DynamicDemoBean(120.00f, “Down Town”, 220, “Royal”, “Vintage 2000”, 50, “CA”, “Royal is a finer veriety of wine produced from the California wine yards. It has been produced to the industy standards.”);

//generate jasper print dynamically
JasperPrint jp = DynamicJasperHelper.generateJasperPrint(firstDynaRep, new ClassicLayoutManager(), new JRBeanArrayDataSource(obj));

JasperPrint jp1 = DynamicJasperHelper.generateJasperPrint(secondDynaRep, new ClassicLayoutManager(), new JRBeanArrayDataSource(obj));
//Combine pages
List pages = new ArrayList(jp1.getPages());
int i=1;
for(int count=0;count<pages.size();count++){
jp.addPage(i, (JRPrintPage)pages.get(count));
i++;
}
return jp;
}

private static Style getHeaderStyle(){
Style headerStyle = new Style();
headerStyle.setFont(Font.ARIAL_MEDIUM_BOLD);
headerStyle.setBorderBottom(Border.PEN_2_POINT);
headerStyle.setHorizontalAlign(HorizontalAlign.CENTER);
headerStyle.setVerticalAlign(VerticalAlign.MIDDLE);
headerStyle.setBackgroundColor(Color.LIGHT_GRAY);
headerStyle.setTextColor(Color.BLUE);
headerStyle.setTransparency(Transparency.OPAQUE);
return headerStyle;
}

private static AbstractColumn getColumn(String property, Class type,
String title, int width, Style headerStyle, Style detailStyle)
throws ColumnBuilderException {
AbstractColumn columnState = ColumnBuilder.getInstance()
.setColumnProperty(property, type.getName()).setTitle(
title).setWidth(Integer.valueOf(width))
.setStyle(detailStyle).setHeaderStyle(headerStyle).build();
return columnState;
}

private static FastReportBuilder getFirstReport(Style headerStyle, Style detailStyle) throws ColumnBuilderException, ClassNotFoundException{
FastReportBuilder firstReport = new FastReportBuilder();

AbstractColumn columnState = getColumn("state", String.class,
"State", 30, headerStyle, detailStyle);
AbstractColumn columnBranch = getColumn("branch", String.class,
"Branch", 30, headerStyle, detailStyle);
AbstractColumn columnProductLine = getColumn("productLine", String.class,
"Product Line", 50, headerStyle, detailStyle);
AbstractColumn columnItem = getColumn("item", String.class,
"Item", 50, headerStyle, detailStyle);
AbstractColumn columnaItemCode = getColumn("itemCode", Long.class,
"Item Code", 22, headerStyle, detailStyle);
AbstractColumn columnQuantity = getColumn("quantity", Long.class,
"Quantity", 22, headerStyle, detailStyle);
Style amountStyle = new Style();
amountStyle.setHorizontalAlign(HorizontalAlign.RIGHT);
AbstractColumn columnAmount = ColumnBuilder.getInstance()
.setColumnProperty("amount", Float.class.getName())
.setTitle("Amount").setWidth(Integer.valueOf(30))
.setStyle(amountStyle).setPattern("$ 0.00")
.setStyle(detailStyle).setHeaderStyle(headerStyle).build();

AbstractColumn remarks = getColumn("remarks", String.class,
"Remarks", 100, headerStyle, detailStyle);
firstReport.addColumn(columnState)
.addColumn(columnBranch)
.addColumn(columnProductLine)
.addColumn(columnItem)
.addColumn(columnaItemCode)
.addColumn(columnQuantity)
.addColumn(columnAmount)
.addColumn(remarks);

firstReport.addFirstPageImageBanner("C:\\eclipse\\workspace\\DynamicJasperReports\\src\\fdvsolutions_dynamicjasper_project.png", Integer.valueOf(560), Integer.valueOf(51), ImageBanner.ALIGN_LEFT);
firstReport.setTitle("November 2006 sales report");
firstReport.setSubtitle("This report was generateed at");
firstReport.setUseFullPageWidth(true); //make colums to fill the page width

return firstReport;
}

private static FastReportBuilder getSecondReport(Style headerStyle, Style detailStyle) throws ColumnBuilderException{
FastReportBuilder secondReport = new FastReportBuilder();

AbstractColumn columnState = getColumn("state", String.class,
"State", 30, headerStyle, detailStyle);
AbstractColumn columnBranch = getColumn("branch", String.class,
"Branch", 30, headerStyle, detailStyle);
AbstractColumn columnProductLine = getColumn("productLine", String.class,
"Product Line", 50, headerStyle, detailStyle);
AbstractColumn columnItem = getColumn("item", String.class,
"Item", 50, headerStyle, detailStyle);
AbstractColumn columnaItemCode = getColumn("itemCode", Long.class,
"Item Code", 22, headerStyle, detailStyle);
AbstractColumn columnQuantity = getColumn("quantity", Long.class,
"Quantity", 22, headerStyle, detailStyle);
Style amountStyle = new Style();
amountStyle.setHorizontalAlign(HorizontalAlign.RIGHT);
AbstractColumn columnAmount = ColumnBuilder.getInstance()
.setColumnProperty("amount", Float.class.getName())
.setTitle("Amount").setWidth(Integer.valueOf(30))
.setStyle(amountStyle).setPattern("$ 0.00")
.setStyle(detailStyle).setHeaderStyle(headerStyle).build();

AbstractColumn remarks = getColumn("remarks", String.class,
"Remarks", 100, headerStyle, detailStyle);
secondReport.addColumn(columnState);
secondReport.addColumn(columnBranch);
secondReport.addColumn(columnProductLine);
secondReport.addColumn(columnItem);
secondReport.addColumn(columnaItemCode);
secondReport.addColumn(columnQuantity);
secondReport.addColumn(columnAmount);
secondReport.addColumn(remarks);

secondReport.addFirstPageImageBanner("C:\\eclipse\\workspace\\DynamicJasperReports\\src\\fdvsolutions_dynamicjasper_project.png", Integer.valueOf(560), Integer.valueOf(51), ImageBanner.ALIGN_LEFT);
secondReport.setTitle("December 2006 sales report");
secondReport.setSubtitle("This report was generateed at");
secondReport.setUseFullPageWidth(true); //make colums to fill the page width

return secondReport;
}

}

One Response to “Dynamic Jasper Report for beginners”

  1. Teela said

    Thank you very much.. your example gave me a quick start into dynamicjasper reports..

Leave a comment