Friday, May 11, 2012

Including page number and page count in JasperReports Footer


Multiple times, we come across such a requirement, where we need to display page number and page count info in report's footer.These footers help the viewer in identifying the proper sequence of pages after the report is printed.

The challenge in such scenario is to identify the total page count even in the first sheet of the report.

JasperReports provide us fine grained control on the time, when a specific text filed expression should be evaluated.Possible evaluation timings are Now, Report,Group, Band,Page,Column,Auto. We can use JasperReport's build in system variable "PAGE_NUMBER" to get the page number during the evaluation time.

To add page number/total page count info in report footer, we divide the complete info into two below sections on the basis of evaluation time.
  1. The info,which should be evaluated and printed as soon as the control reaches (Page Number and "/")
  2. The info which should be evaluated and printed when the complete report is created (Total Page Count)
Then we add two text  field in the report footer mentioning the evaluation time of second text field as Reort. Fist section will print the page number at default evaluation time (ie now).

Sample code- 
 
 <pageFooter>
    <band height="15">
      <textField>
        <reportElement x="0" y="0" width="520" height="15"/>
        <textElement textAlignment="Right"/>
        <textFieldExpression class="java.lang.Integer"><![CDATA[$V{PAGE_NUMBER}+"/"]]></textFieldExpression>
      </textField>
      <textField evaluationTime="Report">
        <reportElement x="521" y="0" width="14" height="15"/>
        <textElement textAlignment="Left"/>
        <textFieldExpression class="java.lang.Integer"><![CDATA[$V{PAGE_NUMBER}]]></textFieldExpression>
      </textField>
    </band>
  </pageFooter>
Note - While using the above code make sure that your footer does not get out of the max report height.

Sample view -

Sample Project -
Sample project can be downloaded from here

You will need maven-3 along with java 5 or higher version, setup in your machine to run the sample.
Kindly follow the below mentioned steps to run the sample and get the report -
  1. Download & unzip the project
  2. Run- mvn clean eclipse:eclipse install in project's home directory
  3. Import the application in eclipse
  4. Execute PageCountFooterTest java file
  5. Sample pdf will be generated at target\\classes\\pageCountFooterTest.pdf location.
References - 
http://salilstock.blogspot.in/2012/05/jasperreport-open-source-java-reporting.html

2 comments:

  1. Hi, is it possible to get the page numbers of different sections in the PDF report while preparing the index file for the report.

    ReplyDelete
  2. Hi, How Can I add Break page in list? is it possible?

    ReplyDelete