Thursday, May 10, 2007

An easy way to remove blank page generated by JasperReports

If your JasperReports report has one more sub-reports and it was generated as PDF file. In some circumstances, a blank page might be found within PDF file. Here is my solution to easily remove it.

private void removeBlankPage(List<JRPrintPage> pages) {

for (Iterator<JRPrintPage> i=pages.iterator(); i.hasNext();) {
JRPrintPage page = i.next();
if (page.getElements().size() == 0)
i.remove();
}
}

This method should be called before you flush your JasperPrint instance to PDF.

Followed with the sample code, it would be better to know the object hierarchy of JasperPrint.

  1. 1. A JasperPrint has one or more JRPrintPage, you can get it via getPages() method of JasperPrint. It returns a List of JRPrintPage. If you have three elements, then your printer will print 3 pages.
  2. 2. A JRPrintPage has one ore more JRPrintElement, each element might be a string of text, or a picture, or a rectangle, etc. You can change its position or content dynamically, or even add new JRPrintElement into JRPrintPage.