Jasper Reports 简明教程

JasperReports - Quick Guide

JasperReports - Getting Started

What is a Report

报告是有意义、定义明确且经过总结的信息展示。通常,例行活动是自动化的,数据汇总到支持决策的“报告”中。报告将通常混乱的数据表示为图表、图形和其他形式的图形表示。

A report is a meaningful, well-defined, and summarized presentation of information. Usually, the routine activities are automated and data summarized into a decision-supporting "Reports". Reports represent usual messy data into charts, graphs, and other forms of graphical representations.

Report Template

通常,大多数商业报告生成工具采用以下布局来生成报告。

Generally, the following layout is adopted to generate reports by most of the commercial report generating tools.

TITLE

PAGEHEADER

COLUMNHEADER

DETAIL

COLUMNFOOTER

PAGEFOOTER

SUMMARY

以下是图表中提到的每个元素的说明 −

Following are the descriptions of each element mentioned in the diagram −

S.NO

Element and Description

1

title Title contains the 'Title' of the report. It appears only once at the very beginning of the report, for example, "Tutorials Point Report."

2

pageHeader PageHeader may contain date and time information and/or organization name. This appears at the top of each page.

3

columnHeader ColumnHeader lists the names of those specific fields, which you want to display in the report, for example, "Author Name," "Starting Hour," "Finishing Hour," "Hours Worked," "Date," etc.

4

detail Detail is the part where entries of the specific fields (listed in columnHeader) are shown, for example "Manisha", "9:00", "18:00", "9", "10.02.2013."

5

columnFooter ColumnFooter may display summation of any of the field, for example, "Total Hours Worked: "180."

6

pageFooter PageFooter may contain page count information. It appears at the bottom of each page, for example, "1/23."

7

summary Summary contains information inferred from "detail" part, for example, after listing the number of hours, worked by each author, total hours worked by each author can be put in visual chart like pie chart, graph, etc. for better comparison.

JasperReports

以下是报表开发过程中常见的问题 −

Following are the common troubles faced during the report development −

  1. Core changes − Usually, reflect the business changes or enhancements it is required to change the core logic of the report.

  2. Results exporting − There are a wide range of formats, which your report can be exported to, such as: HTML, Text, PDF, MS Excel, RTF, ODT, Comma-separated values, XML, or image.

  3. Complicated reports − sub-reports and cross-tabs reports are good example.

  4. Charts reports − Visual charts for example, Graph, Pie, XY Line, Bar, Meter, and Time series.

为消除上述各项产生的开销并促进报表流程,引入了大量框架、工具、库和第三方应用程序。 JasperReports 是其中之一。

To remove the overhead of the above mentioned points and to facilitate the reporting process, a lot of frameworks, tools, libraries, and 3rd parties applications were introduced. JasperReports is one of them.

JasperReports 是一个开源 Java 报表引擎。它基于 Java 并且没有自己的表达式语法。JasperReports 具有将丰富内容传递到屏幕、打印机或 PDF、HTML、XLS、RTF、ODT、CSV、TXT 和 XML 文件的能力。由于它不是一个独立的工具,因此无法单独安装。相反,它可以通过将其库包含在应用程序的 CLASSPATH 中而嵌入到 Java 应用程序中。

JasperReports is an open source java reporting engine. It is Java based and doesn’t have its own expression syntax. JasperReports has the ability to deliver rich content onto the screen, to the printer, or into PDF, HTML, XLS, RTF, ODT, CSV, TXT, and XML files. As it is not a standalone tool, it cannot be installed on its own. Instead, it is embedded into Java applications by including its library in the application’s CLASSPATH.

JasperReports 是一个 Java 类库,不是针对最终用户,而是针对需要将报表功能添加到其应用程序中的 Java 开发人员。

JasperReports is a Java class library, and is not meant for the end users, but rather is targeted towards Java developers who need to add reporting capabilities to their applications.

Features of JasperReports

JasperReports 的一些重要功能 −

Some of the significant features of JasperReports are −

  1. It has a flexible report layout.

  2. It can present data either textually or graphically.

  3. Developers can supply data in multiple ways.

  4. It can accept data from the multiple data sources.

  5. It can generate watermarks (A watermark is like a secondary image that is laid over the primary image).

  6. It can generate sub reports.

  7. It is capable of exporting reports in a variety of formats.

JasperReports - Environment Setup

JasperReports 是一个纯粹的 Java 库,而不是一个独立的应用程序。它无法自己运行,因此需要将其嵌入另一个客户端或服务器端 Java 应用程序中。由于它基于 Java,因此可以在支持 Java(JDK 1.3 及更高版本)的任何平台上运行。所有 JasperReports 的功能都汇集在单个 JAR 文件 jasperreports-x.x.x.jar 中。此 JAR 文件以及必需和可选库(.ZIP 文件)可以从以下网站下载: JasperReport Library Link 。从该链接下载最新版本。

JasperReports is a pure Java library and not a standalone application. It cannot run on its own, hence it needs to be embedded into another client or server-side Java application. As it is Java based, it can be run on any platform that supports Java (JDK 1.3 and above). All the JasperReport’s functionalities are gathered in a single JAR file, jasperreports-x.x.x.jar. This JAR along with the required and optional libraries (.ZIP file) can be downloaded from the site: JasperReport Library Link. Download the latest version from this link.

ZIP 文件包括 JasperReports JAR 文件,以及 JasperReports 源代码、依赖的 JAR 文件和大量用于演示 JasperReport 功能的示例。

The ZIP file includes the JasperReports JAR file along with the JasperReports source code, dependent JARs, and a lot of examples demonstrating JasperReport’s functionalities.

JasperReport Environment

为开始创建报告,我们需要设置好环境。将下载的 JasperReport.ZIP 文件解压到任意位置(我们情况下,已将它解压到 C:\tools\jasperreports-5.0.1)。下面是解压的文件的目录结构:

To start creating the reports, we need to set up the environment ready. Extract the downloaded JasperReport.ZIP file to any location (in our case, we have extracted it to C:\tools\jasperreports-5.0.1). The directory structure of the extracted file is same as shown below −

jasper dir structure

这里是对所有目录的详细说明:

Here is the detail of all the directories −

  1. build − Contains the compiled JasperReport class files.

  2. demo − Contains various examples, demonstrating several aspects of JasperReports functionality.

  3. dist − Contains jasperreports-x.x.x.jar file. We shall add this JAR file to our CLASSPATH to take advantage of JasperReports.

  4. docs − Contains a local copy of the JasperReports documentation.

  5. lib − Contains all JARs needed, both to build JasperReports and to use it in our applications.

  6. src − Contains the JasperReports source code.

  7. build.xml − An ANT build file to build the JasperReports source code. If we don’t intend to modify JasperReports, we don’t need to use this file since JasperReports is distributed in the compiled form.

  8. changes.txt − A text document, explaining the differences between the current and previous versions of the JasperReports class library.

  9. license.txt − A text document that contains the full text of the LGPL (Lesser General Public License) license.

  10. readme.txt − A text document, containing instructions on how to build and execute the supplied examples.

基本上,我们仅将 dist 下的 jasperreports-x.x.x.jar 和 lib 目录下的 JAR 用来生成报表。由于 JasperReports 是一个开源工具,如果在 jasperreports-x.x.x.jar 的执行过程中识别到任何缺陷或 bug,我们可以使用 build.xml 文件修复它并再次构建 JAR。

Basically, we only use the jasperreports-x.x.x.jar under the dist and JARs under the lib directory for generating reports. As JasperReports being an open source tool, if any defect or bug is recognized during execution in the jasperreports-x.x.x.jar, we can fix it and build the JAR again using the build.xml file.

Set the CLASSPATH

为使用 JasperReport,我们需将下列文件设置到我们的 CLASSPATH:

To use JasperReport, we need to set the following files to our CLASSPATH −

  1. jasperreports-x.x.x.jar, where x.x.x is the JasperReports version. This found under directory C:\tools\jasperreports-x.x.x\dist).

  2. All the JAR files under the lib subdirectory (C:\tools\jasperreports-x.x.x\lib).

在安装时,我们使用了 JasperReport 5.0.1 版本。右键单击“我的电脑”,选择“属性”,单击“高级”标签下的“环境变量”按钮。现在使用 C:\tools\jasperreports-5.0.1\dist\jasperreports-5.0.1.jar:C:\tools\jasperreports-5.0.1\lib 更新“路径”变量。现在您已准备好创建您的报表。

At the time of installation, we used JasperReport version 5.0.1. Right-click on 'My Computer' and select 'Properties', click on the 'Environment variables' button under the 'Advanced' tab. Now update the 'Path' variable with this C:\tools\jasperreports-5.0.1\dist\jasperreports-5.0.1.jar:C:\tools\jasperreports-5.0.1\lib. Now you are ready to create your reports.

在本教程的所有示例中,我们都使用 ANT 任务来生成报表。 build 文件负责导入生成报表所需的所有 JAR。因此,正如前面提到的那样,设置 CLASSPATH 仅将帮助那些希望在不使用 ANT 的情况下生成报表的人。

In all the examples in this tutorial, we have used ANT tasks to generate reports. The build file takes care of importing all the required JARs for generating reports. Hence, setting CLASSPATH as mentioned above will only help those who wish to generate reports without using ANT.

Build Setup

本教程中的所有示例 −

All the examples in this tutorial −

  1. have been written using simple Text Editor.

  2. have been saved under the directory C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint.

  3. have been compiled and executed from command prompt, using Apache ANT. We will use a baseBuild.xml file, which we shall import in ANT build.xml file in the subsequent chapters. Save this file to C:\tools\jasperreports-5.0.1\test. Following is the content of baseBuild.xml file −

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportExample" basedir = ".">
   <description>Previews our JasperReport XML Design</description>
   <property name = "file.name" value = "jasper_report_template" />

   <!-- Directory where the JasperReports project file was extracted
   needs to be changed to match the local environment -->
   <property name = "jasper.dir" value = "../" />
   <property name = "dist.dir" value = "${jasper.dir}/dist" />
   <property name = "lib.dir" value = "${jasper.dir}/lib" />
   <property name = "src.dir" value = "src" />
   <property name = "classes.dir" value = "classes" />
   <property name = "main-class" value = "com.tutorialspoint.HelpMe" />

   <path id = "classpath">
      <pathelement location = "./" />
      <pathelement location = "${classes.dir}" />

      <fileset dir = "${lib.dir}">
         <include name = "**/*.jar" />
      </fileset>

      <fileset dir = "${dist.dir}">
         <include name = "**/*.jar" />
      </fileset>
   </path>

   <target name = "compile" depends = "clean-sample">
      <mkdir dir = "${classes.dir}"/>

      <javac srcdir = "${src.dir}" destdir = "${classes.dir}"
         classpathref = "classpath" />
   </target>

   <target name = "run" depends = "compile">
      <echo message = "Running class : ${main-class}"/>

      <java fork = "true" classname = "${main-class}">
         <classpath>
            <path refid = "classpath" />
         </classpath>
      </java>
   </target>

   <target name = "clean-sample">
      <delete dir = "${classes.dir}" />
      <delete file = "./${file.name}.jasper" />
      <delete file = "./${file.name}.jrprint" />
   </target>

</project>

此文件包含所有必需的目标,例如清理目录、编译 java 文件以及执行类文件。

This file has all the required targets, like cleaning the directories, compiling the java files, and executing the class files.

以下是对 baseBuild.xml 中提到的各种目录的详细信息。假设当前目录是 C:\tools\jasperreports-5.0.1\test) −

Following are the details, mentioned by various directories in baseBuild.xml. Assuming current directory is C:\tools\jasperreports-5.0.1\test) −

  1. jasper.dir − is C:\tools\jasperreports-5.0.1 directory

  2. lib.dir − is C:\tools\jasperreports-5.0.1\lib directory

  3. src.dir − is C:\tools\jasperreports-5.0.1\test\src

  4. classes.dir − is C:\tools\jasperreports-5.0.1\test\classes

  5. main-class − com.tutorialspoint.HelpMe. This class is a simple class executed, when no class file name is passed from the command line. Save this file to C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint.

package com.tutorialspoint;

public class HelpMe {
   public static void main(String[] args) {
      System.out.println("This is the default class executed."
         + "Please pass the fully qualified class" + " name to be executed as command line"
         + " parameter, for example," + " com.tutorialspoint.HelpMe ");
   }
}

Jasper Managers Classes

有多个类可用于编译 JRXML 报告设计、填充报告、打印报告、导出到 PDF、HTML 和 XML 文件、查看生成的报告以及报告设计。

There are number of classes, which will be used to compile a JRXML report design, to fill a report, to print a report, to export to PDF, HTML & XML files, view the generated reports, and report design.

report manage classes

这些类的列表 −

The list of these classes is −

  1. net.sf.jasperreports.engine.JasperCompileManager − Used to compile a JRXML report template.

  2. net.sf.jasperreports.engine.JasperFillManager − Used to fill a report with data from the data source.

  3. net.sf.jasperreports.engine.JasperPrintManager − Used to print the documents generated by the JasperReports library.

  4. net.sf.jasperreports.engine.JasperExportManager − Used to obtain PDF, HTML, or XML content for the documents produced by the report-filling process.

  5. net.sf.jasperreports.view.JasperViewer − It represents a simple Java Swing application, which can load and display reports.

  6. net.sf.jasperreports.view.JasperDesignViewer − Used at design time to preview the report templates.

Setting up Apache ANT

我们将使用 Apache ANT 构建所有示例。因此,请检查 ANT - Environment Setup 章节在您的系统上设置 Apache ANT。

We are going to build all the examples using Apache ANT. So, kindly check ANT - Environment Setup chapter to setup Apache ANT on your system.

JasperReports - Life Cycle

JasperReports 的主要目的是以简单灵活的方式创建页面的、易于打印的文档。下述流程图描述了创建报告时的典型工作流程。

The main purpose of JasperReports is to create page oriented, ready to print documents in a simple and flexible manner. The following flow chart depicts a typical work flow while creating reports.

jasperreport lifecycle

如图片所示,生命周期具有以下不同阶段:

As shown in the image, the life cycle has following distinct phases −

  1. Designing the report − In this step we, create the JRXML file, which is an XML document that contains the definition of the report layout. We can use any text editor or iReportDesigner to manually create it. If iReportDesigner is used, the layout is designed in a visual way, hence real structure of the JRXML can be ignored.

  2. Compiling the report − In this step, JRXML is compiled in a binary object called a Jasper file (*.jasper). This compilation is done for performance reasons. Jasper files are what you need to ship with your application in order to run the reports.

  3. Executing the report (Filling data into the report) − In this step, data from the application is filled in the compiled report. The class net.sf.jasperreports.engine.JasperFillManager provides necessary functions to fill the data in the reports. A Jasper print file (*.jrprint) is created, which can be used either to print or export the report.

  4. Exporting the report to desired format − In this step, we can export the Jasper print file created in the previous step to any format using JasperExportManager. As Jasper provides various forms of exports, hence with the same input, we can create multiple representations of the data.

将在后续章节中详细概述上述每个步骤。

A detailed overview of each of the above steps will be given in the subsequent chapters.

JasperReports - Designs

JasperReport 中的 JRXML 模板(或 JRXML 文件)是标准 XML 文件,具有 .jrxml 扩展名。所有 JRXML 文件都包含标签 <jasperReport> 作为根元素。这反过来又包含许多子元素(所有这些都是可选的)。JasperReport 框架可以处理不同类型的数据源。在本教程中,我们将演示如何通过将 Java 数据对象集合(使用 Java bean)传递到 JasperReport Engine 来生成基本报表。最终报表将显示包含姓名和所在国家/地区的人员列表。

The JRXML templates (or JRXML files) in JasperReport are standard XML files, having an extension of .jrxml. All the JRXML files contain tag <jasperReport>, as root element. This in turn contains many sub-elements (all of these are optional). JasperReport framework can handle different kinds of data sources. In this tutorial, we shall show how to generate a basic report, just by passing a collection of Java data object (using Java beans), to the JasperReport Engine. The final report shall display a list of people with the categories including their names and countries.

本章中介绍了以下步骤来描述如何设计 JasperReport:

The Following steps are covered in this chapter to describe — how to design a JasperReport −

  1. Creating a JRXML Report Template and.

  2. Previewing the XML Report Template.

Creating a JRXML Report Template

创建 JRXML 文件,该文件 jasper_report_template.jrxml 使用文本编辑器,并根据我们的环境设置将其保存为 C:\tools\jasperreports-5.0.1\test。

Create the JRXML file, which is jasper_report_template.jrxml using a text editor and save this file in C:\tools\jasperreports-5.0.1\test as per our environment setup.

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN"
   "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">

<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
   http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
   name = "jasper_report_template" language = "groovy" pageWidth = "595"
   pageHeight = "842" columnWidth = "555" leftMargin = "20" rightMargin = "20"
   topMargin = "20" bottomMargin = "20">

   <queryString>
      <![CDATA[]]>
   </queryString>

   <field name = "country" class = "java.lang.String">
      <fieldDescription><![CDATA[country]]></fieldDescription>
   </field>

   <field name = "name" class = "java.lang.String">
      <fieldDescription><![CDATA[name]]></fieldDescription>
   </field>

   <columnHeader>
      <band height = "23">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "3" width = "535"
               height = "15" backcolor = "#70A9A9" />

            <box>
               <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" />
            </box>

            <textElement />
            <text><![CDATA[]]> </text>
         </staticText>

         <staticText>
            <reportElement x = "414" y = "3" width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>

            <text><![CDATA[Country]]></text>
         </staticText>

         <staticText>
            <reportElement x = "0" y = "3" width = "136" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>

            <text><![CDATA[Name]]></text>
         </staticText>

      </band>
   </columnHeader>

    <detail>
      <band height = "16">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "0" width = "535"
               height = "14" backcolor = "#E5ECF9" />

            <box>
               <bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" />
            </box>

            <textElement />
            <text><![CDATA[]]> </text>
         </staticText>

         <textField>
            <reportElement x = "414" y = "0" width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font size = "9" />
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{country}]]>
            </textFieldExpression>
         </textField>

         <textField>
            <reportElement x = "0" y = "0" width = "136" height = "15" />
            <textElement textAlignment = "Center" verticalAlignment = "Middle" />

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{name}]]>
            </textFieldExpression>
         </textField>

      </band>
   </detail>

</jasperReport>

以下是上述报表模板中主要字段的详细信息:

Here are the details of main fields in the above report template −

  1. <queryString> − This is empty (as we are passing data through Java Beans). Usually contains the SQL statement, which retrieves the report result.

  2. <field name> − This element is used to map data from data sources or queries, into report templates. name is re-used in the report body and is case-sensitive.

  3. <fieldDescription> − This element maps the field name with the appropriate element in the XML file.

  4. <staticText> − This defines the static text that does not depend on any datasources, variables, parameters, or report expressions.

  5. <textFieldExpression> − This defines the appearance of the result field.

  6. $F{country} − This is a variable that contains the value of result, predefined field in the tag <field name>.

  7. <band> − Bands contain the data, which is displayed in the report.

一旦报告设计准备就绪,将其保存到 C:\ 目录。

Once the report design is ready, save it in C:\ directory.

Previewing the XML Report Template

JasperReports JAR 文件中提供了一个实用工具类 net.sf.jasperreports.view.JasperDesignViewer,它有助于在无需编译或填充的情况下预览报告设计。此实用工具是一个独立的 Java 应用程序,因此可以使用 ANT 执行。

There is a utility net.sf.jasperreports.view.JasperDesignViewer available in JasperReports JAR file, which helps in previewing the report design without having to compile or fill it. This utility is a standalone Java application, hence can be executed using ANT.

让我们编写 ANT 目标 viewDesignXML 来查看 JRXML。因此,让我们在 C:\tools\jasperreports-5.0.1\test 目录下创建并保存 build.xml (应放置在放置 JRXML 的同一目录中)。以下是 build.xml 文件−

Let’s write an ANT target viewDesignXML to view the JRXML. So, let’s create and save build.xml under C:\tools\jasperreports-5.0.1\test directory (should be placed in the same directory where JRXML is placed). Here is the build.xml file −

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewDesignXML" basedir = ".">

   <import file = "baseBuild.xml" />
   <target name = "viewDesignXML" description = "Design viewer is
      launched to preview the JXML report design.">

      <java classname = "net.sf.jasperreports.view.JasperDesignViewer" fork = "true">
         <arg value = "-XML" />
         <arg value = "-F${file.name}.jrxml" />
         <classpath refid = "classpath" />
      </java>
   </target>

</project>

接下来,让我们打开命令提示符并转到放置 build.xml 的目录。执行命令 ant (因为 viewDesignXML 是默认目标)。输出如下所示−

Next, let’s open a command prompt and go to the directory where build.xml is placed. Execute the command ant (As the viewDesignXML is the default target). Output is follows −

C:\tools\jasperreports-5.0.1\test>ant
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml

viewDesignXML:
[java] log4j:WARN No appenders could be found for logger
(net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
[java] log4j:WARN Please initialize the log4j system properly.

可以忽略 Log4j 警告,并且作为上述执行的结果,“JasperDesignViewer” 窗口打开,显示我们的报告模板预览。

Log4j warning can be ignored, and as a result of above execution, a window labeled "JasperDesignViewer" opens, displaying our report template preview.

jasper design viewer

正如我们所看到的,仅显示用于获取数据的报告表达式,因为 JasperDesignViewer 无法访问实际数据源或报告参数。通过关闭窗口或在命令行窗口中按 Ctrl-c 终止 JasperDesignViewer。

As we see, only report expressions for obtaining the data are displayed, as JasperDesignViewer doesn’t have access to the actual data source or report parameters. Terminate the JasperDesignViewer by closing the window or by hitting Ctrl-c in the command-line window.

JasperReports - Compiling Report Design

我们在前一章中生成了 JasperReport 模板(JRXML 文件)。该文件无法直接用于生成报表。必须将它编译成 JasperReport 的原生二进制格式,称为 Jasper 文件。在编译时,我们将 JasperDesign 对象转换为 JasperReport 对象 −

We have generated the JasperReport template (JRXML file) in the previous chapter. This file cannot be used directly to generate reports. It has to be compiled to JasperReport' native binary format, called Jasper file. On compiling, we transform JasperDesign object into JasperReport object −

jasper report compiling

接口 net.sf.jasperreports.engine.design.JRCompiler 在编译期间起到了核心作用。此接口具有多个实现,具体取决于用于报表表达式的语言,后者可以用 Java、Groovy、JavaScript 或任何其他脚本语言编写,只要编译器实现能够在运行时评估它们即可。

Interface net.sf.jasperreports.engine.design.JRCompiler plays a central role during compilation. This interface has several implementations depending on the language used for report expressions, which can be written in Java, Groovy, JavaScript, or any other scripting language as long as compiler implementation can evaluate it at runtime.

我们可以通过以下两种方式编译 JRXML 文件 −

We can compile JRXML file in the following two ways −

  1. Programmatic compilation.

  2. Compilation through ANT task.

Programmatic Compilation of JRXML

JasperReports API 提供了一个外观类 net.sf.jasperreports.engine.JasperCompileManager 用于编译 JasperReport。此类包含用于编译报表模板的多个公共静态方法。模板的源可以是文件、输入流和/或内存对象。

JasperReports API offers a facade class net.sf.jasperreports.engine.JasperCompileManager for compiling a JasperReport. This class consists of several public static methods for compiling report templates. The source of templates can be files, input streams and/or, memory objects.

JRXML 文件(jasper_report_template.jrxml)的内容如下。它被保存在目录 C:\tools\jasperreports-5.0.1\test 中 −

The contents of the JRXML file (jasper_report_template.jrxml) are as follows. It is saved at directory C:\tools\jasperreports-5.0.1\test

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN"
   "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">

<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
   http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
   name = "jasper_report_template" language = "groovy" pageWidth = "595"
   pageHeight = "842" columnWidth = "555" leftMargin = "20" rightMargin = "20"
   topMargin = "20" bottomMargin = "20">

   <queryString>
      <![CDATA[]]>
   </queryString>

   <field name = "country" class = "java.lang.String">
      <fieldDescription><![CDATA[country]]></fieldDescription>
   </field>

   <field name = "name" class = "java.lang.String">
      <fieldDescription><![CDATA[name]]></fieldDescription>
   </field>

   <columnHeader>
      <band height = "23">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "3"
               width = "535" height = "15" backcolor = "#70A9A9" />

            <box>
               <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" />
            </box>

            <textElement />
            <text><![CDATA[]]> </text>
         </staticText>

         <staticText>
            <reportElement x = "414" y = "3" width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>

            <text><![CDATA[Country]]></text>
         </staticText>

         <staticText>
            <reportElement x = "0" y = "3" width = "136" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>

            <text><![CDATA[Name]]></text>
         </staticText>

      </band>
   </columnHeader>

   <detail>
      <band height = "16">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "0"
               width = "535" height = "14" backcolor = "#E5ECF9" />

            <box>
               <bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" />
            </box>

            <textElement />
            <text><![CDATA[]]> </text>
         </staticText>

         <textField>
            <reportElement x = "414" y = "0" width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font size = "9" />
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{country}]]>
            </textFieldExpression>
         </textField>

         <textField>
            <reportElement x = "0" y = "0" width = "136" height = "15" />
            <textElement textAlignment = "Center" verticalAlignment = "Middle" />

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{name}]]>
            </textFieldExpression>
         </textField>

      </band>
   </detail>

</jasperReport>

以下代码展示了上述 jasper_report_template.jrxml 文件的编译。

The following code demonstrates compilation of the above jasper_report_template.jrxml file.

package com.tutorialspoint;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;

public class JasperReportCompile {

   public static void main(String[] args) {
      String sourceFileName = "C://tools/jasperreports-5.0.1/test" +
         "/jasper_report_template.jrxml";

      System.out.println("Compiling Report Design ...");
      try {
          /**
          * Compile the report to a file name same as
          * the JRXML file name
          */
         JasperCompileManager.compileReportToFile(sourceFileName);
      } catch (JRException e) {
         e.printStackTrace();
      }
      System.out.println("Done compiling!!! ...");
   }
}

Template Compilation

作为下一步,我们将在 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportCompile.java 文件中保存上述内容,并在 build.xml 文件中导入 baseBuild.xml,如下所示。baseBuild.xml 已具有 compilerun 目标 −

As next step, let’s save above content in the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportCompile.java and import the baseBuild.xml in the build.xml file as below. The baseBuild.xml already has the compile and run targets −

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "run" basedir = ".">

   <import file = "baseBuild.xml"/>

</project>

接下来,我们打开命令行窗口,然后转到放置 build.xml 的目录中。最后,执行命令 ant -Dmain-class = com.tutorialspoint.JasperReportCompile ,如下所示 −

Next, let’s open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class = com.tutorialspoint.JasperReportCompile as −

C:\tools\jasperreports-5.0.1\test>ant -Dmain-class = com.tutorialspoint.JasperReportCompile
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml
compile:
   [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:27:
   warning: 'includeantruntime' was not set, defaulting to
   build.sysclasspath=last;set to false for repeatable builds
   [javac] Compiling 1 source file to C:\tools\jasperreports-5.0.1\test\classes

run:
   [echo] Runnin class : com.tutorialspoint.JasperReportCompile
   [java] Compiling Report Design ...
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
   [java] log4j:WARN Please initialize the log4j system properly.
   [java] Done compiling!!! ...

BUILD SUCCESSFUL
Total time: 8 seconds

由于上述编译,您会看到模板文件 jasper_report_template.jasper 已在 C:\tools\jasperreports-5.0.1\test 目录中生成。

As a result of above compilation, you will see that template file jasper_report_template.jasper got generated in C:\tools\jasperreports-5.0.1\test directory.

Preview Compiled Report Template

net.sf.jasperreports.view.JasperDesignViewer 可用于预览已编译的报表模板和 JRXML 模板。

The net.sf.jasperreports.view.JasperDesignViewer can be used to preview compiled report templates and JRXML templates.

要进一步操作,我们向上面的 build.xml 文件添加一个新目标 viewDesign ,这将允许我们预览已编译的报表。以下是经过修改的 build.xml −

To move further, let’s add a new target viewDesign to the above build.xml file, which will allow us to preview the compiled report. Below is the revised build.xml −

导入文件 - baseBuild.xml 从第 Environment Setup 章节中选取,且应放置在与 build.xml 相同的目录中。

The import file - baseBuild.xml is picked from chapter Environment Setup and should be placed in the same directory as the build.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewDesign" basedir = ".">

   <import file = "baseBuild.xml" />
   <target name = "viewDesign" description="Design viewer is launched
      to preview the compiled report design.">

      <java classname = "net.sf.jasperreports.view.JasperDesignViewer" fork = "true">
         <arg value = "-F${file.name}.jasper" />
         <classpath refid = "classpath" />
      </java>
   </target>

</project>

让我们在命令提示符下执行命令 ant (viewDesign 是默认目标)。JasperDesignViewer 窗口打开,显示如下所示的 Jasper 文件 −

Let’s execute the command − ant (viewDesign is the default target) at command prompt. JasperDesignViewer window opens up displaying the Jasper file as below −

jasper design viewer

Compilation through ANT Task

由于报表模板编译更像是设计时间作业而不是运行时作业,因此 JasperReport 库有一个自定义 ANT 任务。在某些情况下,当 JRXML 文件在运行时创建时,我们就无法使用此 ANT 任务。自定义 ANT 任务称为 JRC,并通过类 net.sf.jasperreports.ant.JRAntCompileTask 实现。它的语法和行为与内置 <javac> ANT 任务非常相似。

As report template compilation is more like a design time job than a runtime job, JasperReport library has a custom ANT task. For certain situations, when JRXML file is created at runtime, we can’t use this ANT task. The custom ANT task is called JRC and is implemented by the class: net.sf.jasperreports.ant.JRAntCompileTask. Its syntax and behavior are very similar to the built-in <javac> ANT task.

Template Compilation

让我们向现有 build.xml 添加新目标 compilereportdesing 。此处,使用嵌套 <src> 标记通过文件集指定源文件夹。嵌套源标记允许编译散布在许多不同位置的且未分组在单个根报告源文件夹下的报表模板。以下是经过修改的 build.xml −

Let’s add new target compilereportdesing to our existing build.xml. Here, the source folder is specified using a nested <src> tag with the filesets. The nested source tag allows compiling report templates that are scattered through many different locations and are not grouped under a single root report source folder. Below is the revised build.xml −

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "compilereportdesing" basedir = ".">

   <import file = "baseBuild.xml" />
   <target name = "viewDesign" description = "Design viewer is
      launched to preview the compiled report design.">

      <java classname = "net.sf.jasperreports.view.JasperDesignViewer" fork = "true">
         <arg value = "-F${file.name}.jasper" />
         <classpath refid = "classpath" />
      </java>

   </target>

   <target name = "compilereportdesing" description = "Compiles the
      JXML file and produces the .jasper file.">

      <taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask">
         <classpath refid = "classpath" />
      </taskdef>

      <jrc destdir = ".">
         <src>
            <fileset dir = ".">
               <include name = "*.jrxml" />
            </fileset>
         </src>
         <classpath refid = "classpath" />
      </jrc>
   </target>

</project>

接下来,我们打开命令提示符,并转到放置 build.xml 的目录。执行命令 ant (compilereportdesing 是默认目标);输出如下所示 −

Next, let’s open command prompt and go to the directory where build.xml is placed. Execute the command ant (compilereportdesing is the default target); Output is as follows −

C:\tools\jasperreports-5.0.1\test>ant
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml

compilereportdesing:
   [jrc] Compiling 1 report design files.
   [jrc] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
   [jrc] log4j:WARN Please initialize the log4j system properly.
   [jrc] log4j:WARN See
   http://logging.apache.org/log4j/1.2/faq.html#noconfig
   for more info.
   [jrc] File :
   C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK.

BUILD SUCCESSFUL
Total time: 5 seconds

File jasper_report_template.jasper 在文件系统中生成(在我们的案例中是 C:\tools\jasperreports-5.0.1\test 目录)。此文件与通过调用 net.sf.jasperreports.engine.JasperCompileManager.compileReportToFile() 以编程方式生成的文件相同。我们可以执行 ant viewDesign 以预览此 Jasper 文件。

File jasper_report_template.jasper is generated in the file system (in our case C:\tools\jasperreports-5.0.1\test directory). This file is identical to the file generated programmatically by calling the net.sf.jasperreports.engine.JasperCompileManager.compileReportToFile(). We can preview this jasper file, executing ant viewDesign.

JasperReports - Filling Reports

任何报告工具的主要目的是生成高质量的文档。报告填充过程通过处理数据集来帮助报告工具实现此目的。

The main purpose of any reporting tool is to produce high quality documents. Report filling process helps reporting tool to achieve this by manipulating sets of data.

报告填充过程所需的主要输入如下:

The main inputs required for report-filling process are −

  1. Report Template − This is actual JasperReport file.

  2. Report Parameters − These are basically named values that are passed at the report filling time to the engine. We will discuss them in Report Parameter chapter.

  3. Data Source − We can fill a Jasper file from a range of datasources like an SQL query, an XML file, a csv file, an HQL (Hibernate Query Language) query, a collection of Java Beans, etc. This will be discussed in detail in Report Data Sources chapter.

此过程生成的输出是一个*.jrprint*文档,可以查看、打印或导出为其他格式。外观类net.sf.jasperreports.engine.JasperFillManager通常用于使用数据填充报告模板。此类有各种fillReportXXX()方法,用于填充报告模板(模板可以位于磁盘上、从输入流中选取或直接作为内存中提供)。

The output generated by this process is a *.jrprint * document which is ready to be viewed, printed, or exported to other formats. The facade class net.sf.jasperreports.engine.JasperFillManager is usually used for filling a report template with data. This class has various fillReportXXX() methods that fill report templates (templates could be located on disk, picked from input streams, or are supplied directly as in-memory).

此外观类中有两类fillReportXXX()方法:

There are two categories of fillReportXXX() methods in this facade class −

  1. The first type, receive a java.sql.Connection object as the third parameter. Most of the times, reports are filled with data from a relational database. This is achieved by − Connect to the database through JDBC. Include an SQL query inside the report template. JasperReports engine uses the connection passed in and executes the SQL query. A report data source is thus produced for filling the report.

  2. The second type, receive a net.sf.jasperreports.engine.JRDataSource object, when the data that need to be filled is available in other forms.

Filling Report Templates

我们来编写一个报告模板。JRXML文件(C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml)的内容如下:

Let’s write a report template. The contents of the JRXML file (C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml) are as below −

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN"
   "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">

<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
   http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
   name = "jasper_report_template" language = "groovy" pageWidth = "595"
   pageHeight = "842" columnWidth = "555" leftMargin = "20" rightMargin = "20"
   topMargin = "20" bottomMargin = "20">

   <queryString>
      <![CDATA[]]>
   </queryString>

   <field name = "country" class = "java.lang.String">
      <fieldDescription><![CDATA[country]]></fieldDescription>
   </field>

   <field name = "name" class = "java.lang.String">
      <fieldDescription><![CDATA[name]]></fieldDescription>
   </field>

   <columnHeader>
      <band height = "23">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "3"
               width = "535" height = "15" backcolor = "#70A9A9" />

            <box>
               <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" />
            </box>

            <textElement />
            <text><![CDATA[]]> </text>
         </staticText>

         <staticText>
            <reportElement x = "414" y = "3" width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>

            <text><![CDATA[Country]]></text>
         </staticText>

         <staticText>
            <reportElement x = "0" y = "3" width = "136" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>

            <text><![CDATA[Name]]></text>
         </staticText>

      </band>
   </columnHeader>

   <detail>
      <band height = "16">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "0"
               width = "535" height = "14" backcolor = "#E5ECF9" />

            <box>
               <bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" />
            </box>

            <textElement />
            <text><![CDATA[]]> </text>
         </staticText>

         <textField>
            <reportElement x = "414" y = "0" width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font size = "9" />
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{country}]]>
            </textFieldExpression>
         </textField>

         <textField>
            <reportElement x = "0" y = "0" width = "136" height = "15" />
            <textElement textAlignment = "Center" verticalAlignment = "Middle" />

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{name}]]>
            </textFieldExpression>
         </textField>

      </band>
   </detail>

</jasperReport>

接下来,我们向JasperReport引擎传递Java数据对象(Java bean)集合,以填充此已编译的报告。

Next, let’s pass a collection of Java data objects (Java beans), to the JasperReport Engine, to fill this compiled report.

编写POJO DataBean.java,它表示数据对象(Java bean)。此类定义了两个字符串对象,即“name”和“country”。将其保存到目录 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint

Write a POJO DataBean.java, which represents the data object (Java bean). This class defines two String objects i.e. 'name' and 'country'. Save it to the directory C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint.

package com.tutorialspoint;

public class DataBean {
   private String name;
   private String country;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getCountry() {
      return country;
   }

   public void setCountry(String country) {
      this.country = country;
   }
}

编写类DataBeanList.java,它具有生成Java bean对象集合的业务逻辑。将其进一步传递给JasperReports引擎以生成报告。这里我们在列表中添加了4个DataBean对象。将其保存到目录 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint

Write a class DataBeanList.java, which has business logic to generate a collection of java bean objects. This is further passed to the JasperReports engine, to generate the report. Here we are adding 4 DataBean objects in the List. Save it to the directory C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint.

package com.tutorialspoint;

import java.util.ArrayList;

public class DataBeanList {
   public ArrayList<DataBean> getDataBeanList() {
      ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();

      dataBeanList.add(produce("Manisha", "India"));
      dataBeanList.add(produce("Dennis Ritchie", "USA"));
      dataBeanList.add(produce("V.Anand", "India"));
      dataBeanList.add(produce("Shrinath", "California"));

      return dataBeanList;
   }

   /**
    * This method returns a DataBean object,
    * with name and country set in it.
    */
   private DataBean produce(String name, String country) {
      DataBean dataBean = new DataBean();
      dataBean.setName(name);
      dataBean.setCountry(country);

      return dataBean;
   }
}

写一个 JasperReportFill.java 主类文件,从类 (DataBeanList) 中获取 Java Bean 集合,并将其传递给 JasperReports 引擎以填充报告模板。将其保存到 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint 目录。

Write a main class file JasperReportFill.java, which gets the java bean collection from the class (DataBeanList) and passes it to the JasperReports engine, to fill the report template. Save it to the directory C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint.

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class JasperReportFill {
   @SuppressWarnings("unchecked")
   public static void main(String[] args) {
      String sourceFileName =
         "c://tools/jasperreports-5.0.1/test/jasper_report_template.jasper";
      DataBeanList DataBeanList = new DataBeanList();
      ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();

      JRBeanCollectionDataSource beanColDataSource = new
         JRBeanCollectionDataSource(dataList);
      Map parameters = new HashMap();
      try {
         JasperFillManager.fillReportToFile(
            sourceFileName, parameters, beanColDataSource);
      } catch (JRException e) {
         e.printStackTrace();
      }
   }
}

Generating Reports

现在,我们将使用常规 ANT 构建过程编译并执行这些文件。build.xml 文件如下所示 -

We will now compile and execute these files using our regular ANT build process. The build.xml file is as given below −

导入文件 - baseBuild.xml 从第 Environment Setup 章节中选取,且应放置在与 build.xml 相同的目录中。

The import file - baseBuild.xml is picked from chapter Environment Setup and should be placed in the same directory as the build.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "executereport" basedir = ".">
   <import file = "baseBuild.xml"/>

   <target name = "executereport" depends = "compile,compilereportdesing,run">
      <echo message = "Im here"/>
   </target>

   <target name = "compilereportdesing" description = "Compiles the JXML file and
      produces the .jasper file.">

      <taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask">
         <classpath refid = "classpath" />
      </taskdef>

      <jrc destdir = ".">
         <src>

            <fileset dir = ".">
               <include name = "*.jrxml" />
            </fileset>
         </src>
         <classpath refid = "classpath" />
      </jrc>

   </target>

</project>

接下来,让我们打开命令行窗口并转到放置 build.xml 的目录。最后,执行以下命令 * ant -Dmain-class = com.tutorialspoint.JasperReportFill* ( executereport 是默认目标) -

Next, let’s open command line window and go to the directory where build.xml is placed. Finally, execute the command * ant -Dmain-class = com.tutorialspoint.JasperReportFill* (executereport is the default target) as follows −

C:\tools\jasperreports-5.0.1\test>ant -Dmain-class = com.tutorialspoint.JasperReportFill
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml

compile:
   [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:27:
   warning: 'includeantruntime' was not set, defaulting to
   build.sysclasspath=last; set to false for repeatable builds
   [javac] Compiling 1 source file to
   C:\tools\jasperreports-5.0.1\test\classes

run:
   [echo] Runnin class : com.tutorialspoint.JasperReportFill
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

BUILD SUCCESSFUL
Total time: 8 seconds

通过上述执行操作,可生成 jasper_report_template.jrprint 文件,且该文件与 .jasper 文件放在同一目录中(在此例中,该文件生成在 C:\tools\jasperreports-5.0.1\test 中)。

As a result of above execution, a file jasper_report_template.jrprint is generated in the same directory as the .jasper file (In this case, it is generated at C:\tools\jasperreports-5.0.1\test).

Jasper Report - View & Print Reports

报告填充过程 JasperPrint 对象的输出可以使用内置查看器组件查看,或打印,或导出为更流行的文档格式,如 PDF、HTML、RTF、XLS、ODT、CSV 或 XML。本章将讨论 Jasper 文档的查看和打印,下一章(即 'Export Reports.' )将讨论导出。

The output of the report filling process JasperPrint objects can be viewed using a built-in viewer component, or printed, or exported to more popular document formats like PDF, HTML, RTF, XLS, ODT, CSV, or XML. Viewing and printing of the Jasper documents will be discussed in this chapter and exporting will be discussed in the next chapter i.e. 'Export Reports.'

Viewing Reports

JasperReport 提供了一个内置查看器,用于以其原始格式查看生成的报告。它是一个基于 swing 的组件,其他 Java 应用程序可以集成此组件,而无需将文档导出为其他格式以便查看或打印。net.sf.jasperreports.view.JRViewer 类表示此可视组件。此类也可以通过对其进行子类化根据应用程序需要进行定制。

JasperReport provides a built-in viewer for viewing the generated reports in its original format. It is a swing based component and other Java applications can integrate this component without having to export the documents to other formats in order to be viewed or printed. The net.sf.jasperreports.view.JRViewer class represents this visual component. This class can also be customized as per the application needs, by sub classing it.

JasperReports 还具有一个 Swing 应用程序,它使用可视组件来查看报告。此应用程序有助于以 *.jrprint 生成的相同格式查看报告。此 Swing 应用程序在类 net.sf.jasperreports.view.JasperViewer 中实现。要使用此类查看报告,我们需要将其包装到 ANT 目标中。

JasperReports also has a Swing application, which uses the visual component for viewing the reports. This application helps to view reports in the same format as *.jrprint is produced. This Swing application is implemented in the class net.sf.jasperreports.view.JasperViewer. To view reports using this class, we need to wrap it into an ANT target.

Viewing the generated Report

以下示例演示了如何使用 JasperViewer 类查看报告 -

The following example demonstrates − how to view a report using the JasperViewer class −

我们来编写一个报告模板。JRXML 文件(C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml)的内容如下 -

Let’s write a report template. The contents of the JRXML file (C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml) are as given below −

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN"
   "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">

<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
   http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
   name = "jasper_report_template" language = "groovy" pageWidth = "595"
   pageHeight = "842" columnWidth = "555" leftMargin = "20" rightMargin = "20"
   topMargin = "20" bottomMargin = "20">

   <queryString>
      <![CDATA[]]>
   </queryString>

   <field name = "country" class = "java.lang.String">
      <fieldDescription><![CDATA[country]]></fieldDescription>
   </field>

   <field name = "name" class = "java.lang.String">
      <fieldDescription><![CDATA[name]]></fieldDescription>
   </field>

   <columnHeader>
      <band height = "23">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "3"
               width = "535" height = "15" backcolor = "#70A9A9" />

            <box>
               <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" />
            </box>

            <textElement />
            <text><![CDATA[]]> </text>
         </staticText>

         <staticText>
            <reportElement x = "414" y = "3" width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>
            <text><![CDATA[Country]]></text>
         </staticText>

         <staticText>
            <reportElement x = "0" y = "3" width = "136" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>
            <text><![CDATA[Name]]></text>
         </staticText>

      </band>
   </columnHeader>

   <detail>
      <band height = "16">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "0"
               width = "535" height = "14" backcolor = "#E5ECF9" />

            <box>
               <bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" />
            </box>

            <textElement />
            <text><![CDATA[]]> </text>
         </staticText>

         <textField>
            <reportElement x = "414" y = "0" width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font size = "9" />
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{country}]]>
            </textFieldExpression>
         </textField>

         <textField>
            <reportElement x = "0" y = "0" width = "136" height = "15" />
            <textElement textAlignment = "Center" verticalAlignment = "Middle" />

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{name}]]>
            </textFieldExpression>
         </textField>

      </band>
   </detail>

</jasperReport>

接下来,让我们将 Java 数据对象(Java Bean)集合传递给 JasperReports 引擎,以填充此已编译的报告。

Next, let’s pass a collection of Java data objects (Java beans), to the JasperReports Engine, to fill this compiled report.

编写一个代表数据对象(Java bean)的 POJO DataBean.java。此类定义两个字符串对象,即“name”和“country”。将其保存到 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint 目录。

Write a POJO DataBean.java, which represents the data object (Java bean). This class defines two String objects i.e. 'name' and 'country.' Save it to the directory C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint.

package com.tutorialspoint;

public class DataBean {
   private String name;
   private String country;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getCountry() {
      return country;
   }

   public void setCountry(String country) {
      this.country = country;
   }
}

编写一个具有业务逻辑以生成 Java bean 对象集合的类 DataBeanList.java。将其进一步传递到 JasperReports 引擎以生成报告。在此,我们正在 List 中添加 4 个 DataBean 对象。将其保存到 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint 目录。

Write a class DataBeanList.java, which has business logic to generate a collection of java bean objects. This is further passed to the JasperReports engine, to generate the report. Here, we are adding 4 DataBean objects in the List. Save it to the directory C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint.

package com.tutorialspoint;

import java.util.ArrayList;

public class DataBeanList {
   public ArrayList<DataBean> getDataBeanList() {
      ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();

      dataBeanList.add(produce("Manisha", "India"));
      dataBeanList.add(produce("Dennis Ritchie", "USA"));
      dataBeanList.add(produce("V.Anand", "India"));
      dataBeanList.add(produce("Shrinath", "California"));

      return dataBeanList;
   }

   /**
    * This method returns a DataBean object,
    * with name and country set in it.
    */
   private DataBean produce(String name, String country) {
      DataBean dataBean = new DataBean();
      dataBean.setName(name);
      dataBean.setCountry(country);

      return dataBean;
   }
}

写一个 JasperReportFill.java 主类文件,从类 (DataBeanList) 中获取 Java Bean 集合,并将其传递给 JasperReports 引擎以填充报告模板。将其保存到 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint 目录。

Write a main class file JasperReportFill.java, which gets the java bean collection from the class (DataBeanList) and passes it to the JasperReports engine, to fill the report template. Save it to the directory C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint.

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class JasperReportFill {
   @SuppressWarnings("unchecked")
   public static void main(String[] args) {
      String sourceFileName =
         "c://tools/jasperreports-5.0.1/test/jasper_report_template.jasper";
      DataBeanList DataBeanList = new DataBeanList();
      ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();

      JRBeanCollectionDataSource beanColDataSource = new
         JRBeanCollectionDataSource(dataList);

      Map parameters = new HashMap();
      try {
         JasperFillManager.fillReportToFile(
            sourceFileName, parameters, beanColDataSource);
      } catch (JRException e) {
         e.printStackTrace();
      }
   }
}

让我们向 build.xml 文件编写一个目标 viewFillReport 。build.xml 文件如下 -

Let’s write a target viewFillReport to the build.xml file. The build.xml file is as follows −

导入文件 - baseBuild.xml 从第 Environment Setup 章节中选取,且应放置在与 build.xml 相同的目录中。

The import file - baseBuild.xml is picked from chapter Environment Setup and should be placed in the same directory as the build.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewFillReport" basedir = ".">
   <import file = "baseBuild.xml"/>

   <target name = "viewFillReport" depends = "compile,compilereportdesing,run"
      description = "Launches the report viewer
      to preview the report stored in the .JRprint file.">

      <java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true">
         <arg value = "-F${file.name}.JRprint" />
         <classpath refid = "classpath" />
      </java>
   </target>

   <target name = "compilereportdesing" description = "Compiles the JXML file and
      produces the .jasper file.">

      <taskdef name = "jrc"
         classname = "net.sf.jasperreports.ant.JRAntCompileTask">
         <classpath refid = "classpath" />
      </taskdef>

      <jrc destdir = ".">
         <src>
            <fileset dir = ".">
               <include name = "*.jrxml" />
            </fileset>
         </src>
         <classpath refid = "classpath" />
      </jrc>

   </target>

</project>

接下来,让我们打开命令行窗口,并转到放置 build.xml 的目录。最后,执行命令 * ant -Dmain-class=com.tutorialspoint.JasperReportFill*(viewFillReport 是默认目标)。结果,我们看到一个 JasperViewer 窗口,如下面的屏幕截图所示 -

Next, let’s open command line window and go to the directory where build.xml is placed. Finally, execute the command * ant -Dmain-class=com.tutorialspoint.JasperReportFill* (viewFillReport is the default target). As a result, we see a JasperViewer window as shown in the screen given below −

jasper report viewer

Printing Reports

我们可以使用 net.sf.jasperreports.engine.JasperPrintManager 类打印由 JasperReports 库生成的文档(以其专有格式即 JasperPrint 对象)。这是一个依赖 Java 2 Printing API 的外壳类。一旦 JasperReport 文档导出到其他格式(如 HTML 或 PDF),我们还可以打印文档。

We can print the documents generated by the JasperReports library (in their proprietary format i.e. JasperPrint objects) using the net.sf.jasperreports.engine.JasperPrintManager class. This is a facade class that relies on the Java 2 Printing API. We can also print the documents once the JasperReport documents are exported to other formats such as HTML or PDF.

Printing the Generated Report

以下代码演示了打印报告。让我们更新我们现有的类 JasperReportFill。我们将使用 JasperPrintManager.printReport()方法。该方法将源文件名(在此,我们传递.jrprint 文件,这是我们使用 JasperFillManager.fillReportToFile() 方法在上一步中生成的)作为第一个参数。第二个参数是用于显示标准打印对话框的布尔值(我们在此将其设置为 true )。

The following code demonstrates the printing of a report. Let’s update our existing class JasperReportFill. We will use JasperPrintManager.printReport() method. This method takes source file name (here we pass the .jrprint file, which we generate in the previous step using the method JasperFillManager.fillReportToFile()) as first parameter. The second parameter is the boolean for displaying the standard print dialog (we have set it to true here).

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrintManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class JasperReportFill {
   @SuppressWarnings("unchecked")
   public static void main(String[] args) {
      String sourceFileName = "c://tools/jasperreports-5.0.1/" +
         "test/jasper_report_template.jasper";
      String printFileName = null;
      DataBeanList DataBeanList = new DataBeanList();
      ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();

      JRBeanCollectionDataSource beanColDataSource = new
         JRBeanCollectionDataSource(dataList);

      Map parameters = new HashMap();
      try {
    	   printFileName = JasperFillManager.fillReportToFile(
            sourceFileName, parameters, beanColDataSource);
         if(printFileName != null){
            JasperPrintManager.printReport( printFileName, true);
         }
      } catch (JRException e) {
         e.printStackTrace();
      }
   }
}

现在,让我们将此文件保存到目录 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint 。我们将使用 ANT 编译并执行此文件。build.xml 的内容如下 -

Now, let’s save this file to the directory C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint. We will compile and execute this file using ANT. The contents of build.xml are as given below −

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "executereport" basedir = ".">
   <import file = "baseBuild.xml"/>

   <target name = "executereport" depends = "compile,compilereportdesing,run">
      <echo message = "Im here"/>
   </target>

   <target name = "compilereportdesing" description = "Compiles the JXML file and
      produces the .jasper file.">

      <taskdef name = "jrc"
         classname = "net.sf.jasperreports.ant.JRAntCompileTask">
         <classpath refid = "classpath" />
      </taskdef>

      <jrc destdir = ".">
         <src>
            <fileset dir = ".">
               <include name = "*.jrxml" />
            </fileset>
         </src>
         <classpath refid = "classpath" />
      </jrc>

   </target>

</project>

接下来,让我们打开命令提示符并转到放置 build.xml 的目录。最后,执行命令 ant -Dmain-class=com.tutorialspoint.JasperReportPrint 。结果,会出现一个打印对话框。单击确定以打印文档。

Next, let’s open command prompt and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportPrint. As a result, a print dialog box appears. Click ok to print the document.

JasperReports - Exporting Reports

我们在上一章中看到了如何打印和查看 JasperReport 生成的文档。在这里,我们将看到如何将这些报告转换为 PDF、HTML 和 XLS 等其他格式或导出到这些格式。提供了 Facade 类 net.sf.jasperreports.engine.JasperExportManager 以实现此功能。导出是指将 JasperPrint 对象(.jrprint 文件)转换为不同的格式。

We have seen in the previous chapter, how to print and view a JasperReport generated document. Here, we shall see how to transform or export these reports into other formats such as PDF, HTML, and XLS. Facade class net.sf.jasperreports.engine.JasperExportManager is provided to achieve this functionality. Exporting means transforming the JasperPrint object (.jrprint file) into different format.

以下代码(JasperReportExport.java)演示了 JasperReport 文档的导出过程。JasperExportManager 仅提供将报告导出到 PDF、HTML 和 XML 的方法。为了导出到 XLS 格式,我们使用了类 net.sf.jasperreports.engine.export.JRXlsExporter。此代码生成以下三个文件−

The following code (JasperReportExport.java) demonstrates the exporting process of the JasperReport document. The JasperExportManager provides methods to export a report into PDF, HTML, and XML only. To export to the XLS format, we have used the class net.sf.jasperreports.engine.export.JRXlsExporter. This code generates following three files −

  1. sample_report.pdf

  2. sample_report.html

  3. sample_report.xls

Exporting to Other Formats

我们来编写一个报告模板。JRXML文件(C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml)的内容如下:

Let’s write a report template. The contents of the JRXML file (C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml) are as below −

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN"
   "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">

<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
   http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
   name = "jasper_report_template" language = "groovy" pageWidth = "595"
   pageHeight = "842" columnWidth = "555" leftMargin = "20" rightMargin = "20"
   topMargin = "20" bottomMargin = "20">

   <queryString>
      <![CDATA[]]>
   </queryString>

   <field name = "country" class = "java.lang.String">
      <fieldDescription><![CDATA[country]]></fieldDescription>
   </field>

   <field name = "name" class = "java.lang.String">
      <fieldDescription><![CDATA[name]]></fieldDescription>
   </field>

   <columnHeader>
      <band height = "23">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "3"
               width = "535" height = "15" backcolor = "#70A9A9" />

            <box>
               <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" />
            </box>

            <textElement />
            <text><![CDATA[]]> </text>
         </staticText>

         <staticText>
            <reportElement x = "414" y = "3" width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>

            <text><![CDATA[Country]]></text>
         </staticText>

         <staticText>
            <reportElement x = "0" y = "3" width = "136" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>

            <text><![CDATA[Name]]></text>
         </staticText>

      </band>
   </columnHeader>

   <detail>
      <band height = "16">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "0"
               width = "535" height = "14" backcolor = "#E5ECF9" />

            <box>
               <bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" />
            </box>

            <textElement />
            <text><![CDATA[]]> </text>
         </staticText>

         <textField>
            <reportElement x = "414" y = "0" width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font size = "9" />
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{country}]]>
            </textFieldExpression>
         </textField>

         <textField>
            <reportElement x = "0" y = "0" width = "136" height = "15" />
            <textElement textAlignment = "Center" verticalAlignment = "Middle" />

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{name}]]>
            </textFieldExpression>
         </textField>

      </band>
   </detail>

</jasperReport>

接下来, C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java POJO 文件内容如下所示−

Next, contents of the POJO file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java are as given below −

package com.tutorialspoint;

public class DataBean {
   private String name;
   private String country;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getCountry() {
      return country;
   }

   public void setCountry(String country) {
      this.country = country;
   }
}

文件 *C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java * 的内容如下所示−

The contents of the file *C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java * are as given below −

package com.tutorialspoint;

import java.util.ArrayList;

public class DataBeanList {
   public ArrayList<DataBean> getDataBeanList() {
      ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();

      dataBeanList.add(produce("Manisha", "India"));
      dataBeanList.add(produce("Dennis Ritchie", "USA"));
      dataBeanList.add(produce("V.Anand", "India"));
      dataBeanList.add(produce("Shrinath", "California"));

      return dataBeanList;
   }

   /**
    * This method returns a DataBean object,
    * with name and country set in it.
    */
   private DataBean produce(String name, String country) {
      DataBean dataBean = new DataBean();
      dataBean.setName(name);
      dataBean.setCountry(country);

      return dataBean;
   }
}

写一个 JasperReportFill.java 主类文件,从类 (DataBeanList) 中获取 Java Bean 集合,并将其传递给 JasperReports 引擎以填充报告模板。将其保存到 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint 目录。

Write a main class file JasperReportFill.java, which gets the java bean collection from the class (DataBeanList) and passes it to the JasperReports engine, to fill the report template. Save it to the directory C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint.

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRXlsExporter;

public class JasperReportFill {
   @SuppressWarnings("unchecked")
   public static void main(String[] args) {
      String sourceFileName = "c://tools/jasperreports-5.0.1/"
         + "test/jasper_report_template.jasper";
      String printFileName = null;
      DataBeanList DataBeanList = new DataBeanList();
      ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();
      JRBeanCollectionDataSource beanColDataSource =
         new JRBeanCollectionDataSource(dataList);

      Map parameters = new HashMap();
      try {
         printFileName = JasperFillManager.fillReportToFile(sourceFileName,
            parameters, beanColDataSource);
         if (printFileName != null) {
            /**
             * 1- export to PDF
             */
            JasperExportManager.exportReportToPdfFile(printFileName,
               "C://sample_report.pdf");

            /**
             * 2- export to HTML
             */
            JasperExportManager.exportReportToHtmlFile(printFileName,
               "C://sample_report.html");

            /**
             * 3- export to Excel sheet
             */
            JRXlsExporter exporter = new JRXlsExporter();

            exporter.setParameter(JRExporterParameter.INPUT_FILE_NAME,
               printFileName);
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,
               "C://sample_report.xls");

            exporter.exportReport();
         }
      } catch (JRException e) {
         e.printStackTrace();
      }
   }
}

在这里,我们包含了将 jasper 打印文件导出到 pdf、html 和 xls 格式的逻辑。

Here, we have included the logic to export the jasper print file to pdf, html and xls format.

Generating Reports

让我们使用常规 ANT 构建过程编译并执行上述文件。build.xml 文件如下所示−

Let’s compile and execute above files using our regular ANT build process. The build.xml file is as given below −

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "executereport" basedir = ".">
   <import file = "baseBuild.xml"/>

   <target name = "executereport" depends = "compile,compilereportdesing,run">
      <echo message = "Im here"/>
   </target>

   <target name = "compilereportdesing" description = "Compiles the JXML file and
      produces the .jasper file.">

      <taskdef name = "jrc"
         classname = "net.sf.jasperreports.ant.JRAntCompileTask">
         <classpath refid = "classpath" />
      </taskdef>

      <jrc destdir = ".">
         <src>
            <fileset dir = ".">
               <include name = "*.jrxml" />
            </fileset>
         </src>
         <classpath refid = "classpath" />
      </jrc>

   </target>

</project>

转到命令提示符,然后转到放置 build.xml 的目录 C:\tools\jasperreports-5.0.1\test。最后,执行命令 ant -Dmain-class=com.tutorialspoint.JasperReportFill 。输出如下所示−

Go to the command prompt and then go to the directory C:\tools\jasperreports-5.0.1\test, where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill. The output is as follows −

C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml

clean-sample:
   [delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint

compile:
   [mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes
   [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28:
   warning: 'includeantruntime' was not set, defaulting t
   [javac] Compiling 4 source files to C:\tools\jasperreports-5.0.1\test\classes

compilereportdesing:
   [jrc] Compiling 1 report design files.
   [jrc] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
   [jrc] log4j:WARN Please initialize the log4j system properly.
   [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
   [jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK.

run:
   [echo] Runnin class : com.tutorialspoint.JasperReportFill
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

executereport:
   [echo] Im here

BUILD SUCCESSFUL
Total time: 32 seconds

作为上述执行的结果,你将在 C:\ 目录中找到三个文件 sample_report.pdf、sample_report.html、sample_report.xls。

As the result of above execution, you will find three files sample_report.pdf, sample_report.html, sample_report.xls generated in the C:\ directory.

Reports Parameters

填充报告的主要输入是− 报告模板、参数和数据源。本章将介绍参数,在下一章中我们将讨论数据源。

The main input for filling a report are − report template, parameters, and data sources. This chapter will describe the parameters and in the next chapter we will discuss the data sources.

参数是对象引用,在报告填充操作期间传递给报告引擎。无法通过数据源传递的数据可以通过使用参数传递。可以通过参数传递诸如作者姓名、报告标题等数据。JasperReports 模板或 JRXML 模板可以具有零个或多个参数元素。

Parameters are the object references, those are passed during report-filling operations to the report engine. The data which cannot be passed through the data source, can be passed by using parameters. Data like author name, title of the report, etc. can be passed through parameters. A JasperReports template or JRXML template can have zero or more parameter elements.

Parameter Declaration

参数声明如下−

Parameter declaration as follows −

<parameter name = "exampleParameter" class = "java.lang.String" />

The Name Attribute

<parameter> 元素的 name 属性是必需的。它通过名称引用报告表达式中的参数。参数名称应为一个单词。它不应包含任何特殊字符,例如句点或逗号。

The name attribute of the <parameter> element is mandatory. It references the parameter in report expressions by name. Parameter name should be a single word. It should not contain any special characters like dot or comma.

The Class Attribute

class 属性也是必需的,它为参数值指定类名。它的默认值为 java.lang.String。这可以更改为运行时可用的任何类。无论报告参数的类型如何,引擎都会负责强制转换报告表达式中使用 $P{} 令牌的内容,从而使手动强制转换变得不必要。

The class attribute is also mandatory and it specifies the class name for the parameter values. Its default value is java.lang.String. This can be changed to any class available at runtime. Irrespective of the type of a report parameter, the engine takes care of casting in the report expressions in which the $P{} token is used, hence making the manual casts is unnecessary.

报表参数值始终打包在一个 java.util.Map 对象中,其具有参数名称作为其键。报表参数可以用在报表的查询字符串中,以进一步定制从数据库中检索出的数据集。它们的作用就像查询中的动态过滤器,向报表提供数据。

The report parameter values are always packed in a java.util.Map object, which has the parameter name as its key. Report parameters can be used in the query string of the report, so as to further customize the data set, retrieved from the database. These act like dynamic filters in the query that supplies data for the report.

Built-in Parameters

以下是预定义的报表参数,可随时用于表达式中:

Following are the pre-defined report parameters, ready to use in the expressions −

S.NO

Parameter Name and Description

1

REPORT_PARAMETERS_MAP Contains a map with all user defined and built-in parameters.

2

REPORT_CONNECTION This points to the user supplied class java.sql.Connection, used for JDBC datasources.

3

REPORT_DATA_SOURCE This is a user supplied instance of JRDataSource representing either one of the built-in data source types or a user-defined one.

4

REPORT_MAX_COUNT This is a java.lang.Integer value, allowing the users to limit the records from datasource.

5

REPORT_SCRIPTLET This points to net.sf.jasperreports.engine.JRAbstractScriptlet and contains an instance of the report scriptlet provided by the user.

6

REPORT_LOCALE This a java.util.Locale instance, containing the resource bundle desired locale.

7

REPORT_RESOURCE_BUNDLE This points to java.util.ResourceBundle object and contains localized messages.

8

REPORT_TIME_ZONE This is a java.util.TimeZone instance, used for the date formatting.

9

REPORT_VIRTUALIZER This is an instance of net.sf.jasperreports.engine.JRVirtualizer object, and used for the page virtualization (optimize memory consumption).

10

REPORT_CLASS_LOADER This is a java.lang.ClassLoader instance to be used during the report filling process to load resources such as images, fonts, and subreport templates

11

IS_IGNORE_PAGINATION If set to java.lang.Boolean.TRUE the report will be generated on one long page and page break will not occur.

Example

让我们将 ReportTitle 和 Author 传递给报表(由 JasperReportFill.java 生成)。修改后的文件 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java 如下:

Let us pass ReportTitle and Author to the report (generated by JasperReportFill.java). Revised file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java is as follows −

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class JasperReportFill {
   @SuppressWarnings("unchecked")
   public static void main(String[] args) {
      String sourceFileName =
         "C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper";

      DataBeanList DataBeanList = new DataBeanList();
      ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();

      JRBeanCollectionDataSource beanColDataSource =
      new JRBeanCollectionDataSource(dataList);

      Map parameters = new HashMap();
      /**
       * Passing ReportTitle and Author as parameters
       */
      parameters.put("ReportTitle", "List of Contacts");
      parameters.put("Author", "Prepared By Manisha");

      try {
         JasperFillManager.fillReportToFile(
         sourceFileName, parameters, beanColDataSource);
      } catch (JRException e) {
         e.printStackTrace();
      }
   }
}

POJO 文件 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java 的内容如下:

The contents of the POJO file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java are as below −

package com.tutorialspoint;

public class DataBean {
   private String name;
   private String country;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getCountry() {
      return country;
   }

   public void setCountry(String country) {
      this.country = country;
   }
}

C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java 文件的内容如下 −

The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java are as given below −

package com.tutorialspoint;

import java.util.ArrayList;

public class DataBeanList {
   public ArrayList<DataBean> getDataBeanList() {
      ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();

      dataBeanList.add(produce("Manisha", "India"));
      dataBeanList.add(produce("Dennis Ritchie", "USA"));
      dataBeanList.add(produce("V.Anand", "India"));
      dataBeanList.add(produce("Shrinath", "California"));

      return dataBeanList;
   }

   /**
    * This method returns a DataBean object,
    * with name and country set in it.
    */
   private DataBean produce(String name, String country) {
      DataBean dataBean = new DataBean();
      dataBean.setName(name);
      dataBean.setCountry(country);

      return dataBean;
   }
}

让我们将参数 <*ReportTitle*> 和 <*Author*> 添加到我们的现有报表模板(第 Report Designs 章)。报表标题和作者将显示在报表开头。修改后的报表模板(jasper_report_template.jrxml)如下。将其保存到 C:\tools\jasperreports-5.0.1\test 目录中:

Let’s add parameters the <*ReportTitle*> and <*Author*> to our existing report template (Chapter Report Designs). The Report Title and Author will be displayed at the beginning of the report. The revised report template (jasper_report_template.jrxml) is as follows. Save it to C:\tools\jasperreports-5.0.1\test directory −

<?xml version = "1.0"?>
<!DOCTYPE jasperReport PUBLIC
   "//JasperReports//DTD Report Design//EN"
   "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">

<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
   http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
   name = "jasper_report_template" pageWidth = "595"
   pageHeight = "842" columnWidth = "515"
   leftMargin = "40" rightMargin = "40" topMargin = "50" bottomMargin = "50">

   <parameter name = "ReportTitle" class = "java.lang.String"/>
   <parameter name = "Author" class = "java.lang.String"/>

   <queryString>
      <![CDATA[]]>
   </queryString>

   <field name = "country" class = "java.lang.String">
      <fieldDescription><![CDATA[country]]></fieldDescription>
   </field>

   <field name = "name" class = "java.lang.String">
      <fieldDescription><![CDATA[name]]></fieldDescription>
   </field>

   <title>
      <band height = "70">

         <line>
            <reportElement x = "0" y = "0" width = "515" height = "1"/>
         </line>

         <textField isBlankWhenNull = "true" bookmarkLevel = "1">
            <reportElement x = "0" y = "10" width = "515" height = "30"/>

            <textElement textAlignment = "Center">
               <font size = "22"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{ReportTitle}]]>
            </textFieldExpression>

            <anchorNameExpression>
               <![CDATA["Title"]]>
            </anchorNameExpression>
         </textField>

         <textField isBlankWhenNull = "true">
            <reportElement  x = "0" y = "40" width = "515" height = "20"/>

            <textElement textAlignment = "Center">
               <font size = "10"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{Author}]]>
            </textFieldExpression>
         </textField>

      </band>
   </title>

   <columnHeader>
      <band height = "23">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "3" width = "535" height = "15"
               backcolor = "#70A9A9" />

            <box>
               <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" />
            </box>

            <textElement />

            <text>
               <![CDATA[]]>
            </text>
         </staticText>

         <staticText>
            <reportElement x = "414" y = "3" width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>

            <text><![CDATA[Country]]></text>
         </staticText>

         <staticText>
            <reportElement x = "0" y = "3" width = "136" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>

            <text><![CDATA[Name]]></text>
         </staticText>

      </band>
   </columnHeader>

   <detail>
      <band height = "16">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "0" width = "535" height = "14"
               backcolor = "#E5ECF9" />

            <box>
               <bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" />
            </box>

            <textElement />

            <text>
               <![CDATA[]]>
            </text>
         </staticText>

         <textField>
            <reportElement x = "414" y = "0" width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font size = "9" />
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{country}]]>
            </textFieldExpression>
         </textField>

         <textField>
            <reportElement x = "0" y = "0" width = "136" height = "15" />
            <textElement textAlignment = "Center" verticalAlignment = "Middle" />

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{name}]]>
            </textFieldExpression>
         </textField>

      </band>
   </detail>

</jasperReport>

Report Generation

我们将使用常规的 ANT 构建过程编译并执行以上文件。文件 build.xml(保存在 C:\tools\jasperreports-5.0.1\test 目录下)的内容如下。

We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are as below.

导入文件 - baseBuild.xml 从第 Environment Setup 章选取并应该放置在与 build.xml 相同的目录中。

The import file - baseBuild.xml is picked from the chapter Environment Setup and should be placed in the same directory as the build.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewFillReport" basedir = ".">
   <import file = "baseBuild.xml" />

   <target name = "viewFillReport" depends = "compile,compilereportdesing,run"
      description = "Launches the report viewer to preview
      the report stored in the .JRprint file.">


      <java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true">
         <arg value = "-F${file.name}.JRprint" />
         <classpath refid = "classpath" />
      </java>
   </target>

   <target name = "compilereportdesing" description = "Compiles the JXML file and
      produces the .jasper file.">

      <taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask">
         <classpath refid = "classpath" />
      </taskdef>

      <jrc destdir = ".">
         <src>
            <fileset dir = ".">
               <include name = "*.jrxml" />
            </fileset>
         </src>
         <classpath refid = "classpath" />
      </jrc>

   </target>

</project>

接下来,让我们打开命令行窗口并转到放置 build.xml 的目录。最后,执行以下命令 ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport 是默认目标) -

Next, let’s open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as follows −

C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml

clean-sample:
   [delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint

compile:
   [mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes
   [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28: warning:
   'includeantruntime' was not set, defaulting to build.sysclasspath=last;
   set to false for repeatable builds
   [javac] Compiling 7 source files to C:\tools\jasperreports-5.0.1\test\classes

compilereportdesing:
   [jrc] Compiling 1 report design files.
   [jrc] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
   [jrc] log4j:WARN Please initialize the log4j system properly.
   [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig
   for more info.
   [jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK.

run:
   [echo] Runnin class : com.tutorialspoint.JasperReportFill
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

viewFillReport:
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

BUILD SUCCESSFUL
Total time: 18 seconds

由于以上编译,JasperViewer 窗口会如以下屏幕所示打开:

As a result of above compilation, a JasperViewer window opens up as shown in the following screen −

report param example

在这里,我们看到,报表标题“联系人列表”和作者“由 Manisha 准备”显示在报表的开头。

Here, we see that, the ReportTitle "List Of Contacts" and Author "Prepared By Manisha" are displayed at the beginning of the report.

Report Data Sources

数据源是结构化的数据容器。在生成报表时,JasperReports 引擎从数据源获取数据。可以从数据库、XML 文件、对象数组以及对象集合获取数据。我们已经在 Filling Reports 章中看到,fillReportXXX() 方法期望接收报表的数据源,它必须以 net.sf.jasperreports.engine.JRDataSource 对象或 java.sql.Connection 的形式进行填充(如果报表数据位于关系数据库中)。

Datasources are structured data container. While generating the report, JasperReports engine obtains data from the datasources. Data can be obtained from the databases, XML files, arrays of objects, and collection of objects. We saw in the chapter Filling Reports, the fillReportXXX () method expects to receive a data source of the report, which has to fill, in the form of net.sf.jasperreports.engine.JRDataSource object or a java.sql.Connection (when the report data is found in a relational database).

JRDataSource 接口只有两个方法,应该实现以下内容 −

The JRDataSource interface has only two methods, which should be implemented −

  1. public boolean next() throws JRException; At the report filling time, this method is called on the data source object by the reporting engine when iterating through the data.

  2. public Object getFieldValue(JRField jrField) throws JRException; This method provides the value for each report field in the current data source record.

检索数据源中数据的唯一方法是使用报表字段。JRDataSource 接口有多个默认实现,具体取决于获取数据源中记录的方式。

The only way to retrieve data from the data source is by using the report fields. There are several default implementations of the JRDataSource interface, depending on the way, the records in the data source are acquired.

Datasource Implementations

下表总结了数据源及其实现类 −

The table given below summarizes the datasources and their implementation classes −

Datasource

Implementation Class

JDBC

net.sf.jasperreports.engine.JRResultSetDataSource

JavaBean

net.sf.jasperreports.engine.data.JRBeanCollectionDataSource, net.sf.jasperreports.engine.data.JRBeanArrayDataSource

Map-based

net.sf.jasperreports.engine.data.JRMapArrayDataSource, net.sf.jasperreports.engine.data.JRMapCollectionDataSource

TableModel

net.sf.jasperreports.engine.data.JRTableModelDataSource

XML

net.sf.jasperreports.engine.data.JRXmlDataSource

CSV

net.sf.jasperreports.engine.data.JRCsvDataSource

XLS

net.sf.jasperreports.engine.data.JRXlsDataSource

Empty

net.sf.jasperreports.engine.JREmptyDataSource

JDBC Data Sources

JRResultSetDataSource 会包装 java.sql.ResultSet 对象。当报表数据从关系数据库中提取时,这是最常用的数据源实现。如果 java.sql.Connection 传递到引擎,它将首先执行相关查询并将返回的 java.sql.ResultSet 对象存储在 JRResultSetDataSource 实例中。

Class JRResultSetDataSource craps a java.sql.ResultSet object. This is the most commonly used data source implementations when report data are extracted from a relational database. If a java.sql.Connection is passed to the engine instead, it executes first the related query and stores the returned java.sql.ResultSet object in a JRResultSetDataSource instance.

JavaBean Data Sources

JRBeanArrayDataSourceJRBeanCollectionDataSource 表示可以包装 JavaBean 对象数组和集合的实现。数组或集合中的每个对象都将被视为此类型数据源中的一条记录。特定 JavaBean 属性和相应报表字段之间的映射是通过命名约定进行的。报表字段的名称必须与 JavaBean 规范中指定的 JavaBean 属性的名称相同。

Classes JRBeanArrayDataSource and JRBeanCollectionDataSource represent implementations that can wrap arrays and collections of JavaBean objects. Each object inside the array or the collection will be seen as one record in this type of data source. The mapping between a particular JavaBean property and the corresponding report field is made by naming conventions. The name of the report field must be the same as the name of the JavaBean property as specified by the JavaBeans specifications.

在本教程的所有示例中,我们都使用了 JRBeanCollectionDataSource。

In all the examples of this tutorial, we have used JRBeanCollectionDataSource.

Map-based Data Sources

如果父应用程序已将报告数据存储在内存中,类 JRMapArrayDataSourceJRMapCollectionDataSource 的实现非常有用。包装的数组或集合中的每个 Map 对象都被视为数据源中的一个虚拟记录,报表字段的值是从使用报告字段(指定为键)的 map 中提取的。

The implementation classes JRMapArrayDataSource and JRMapCollectionDataSource are useful if the parent application already stores the reporting data available in-memory as java.util.Map objects. Each Map object in the wrapped array or collection is considered a virtual record in the data source, and the value of each report field is extracted from the map using the report field named as the key.

TableModel Data Sources

在许多客户端应用程序中,数据以表格格式显示。许多应用程序中一个常见的需求是允许用户将此表格格式打印为报表。实现类 JRTableModelDataSource 使得从表格格式为 Swing 应用程序生成报表变得轻而易举。此类包装一个 javax.swing.table.TableModel 对象。可以通过它们的名称或它们的以 0 为基准的索引来访问包装的 TableModel 对象中的列。

In many client-side applications, data is displayed in tabular format. A common requirement in many applications is to allow the user to print this tabular format as a report. Implementation class JRTableModelDataSource makes the task of generating reports from tabular format trivial for Swing applications. This class wraps a javax.swing.table.TableModel object. Columns in the wrapped TableModel object can be accessed either by their names or by their 0-based indexes.

XML Data Sources

JRXmlDataSource 是一种基于 DOM 的数据源实现,它使用 XPath 表达式从 XML 文档中选择数据。XML 数据源中的记录由通过 XPath 表达式选择的节点元素表示。使用字段说明(JRXML 中的 <fieldDescription> 元素)提供的 XPath 表达式从每个记录中检索字段值。

Class JRXmlDataSource is a data source implementation based on DOM, which uses XPath expressions to select data from the XML document. Records in the XML data source are represented by node elements selected through the XPath expression. Field values are retrieved from each record using the XPath expression provided by the field description (<fieldDescription> element in JRXML).

XPath 是一种用于导航 XML 文档的属性和元素的语言。在 http://www.w3.org/TR/xpath. 中可以找到有关 XPath 的更多信息

XPath is a language used to navigate through an XML document’s attributes and elements. More information about XPath can be found at http://www.w3.org/TR/xpath.

CSV Data Sources

JRCsvDataSource 表示一种用于数据源的实现,它从结构化文本文件(通常是 CSV)中检索其数据。使用它们的列索引检索字段值。

JRCsvDataSource represents an implementation for data sources, which retrieve their data from structured text files; usually CSVs. Field values are retrieved using their column index.

XLS Data Sources

JRXlsDataSource 表示一种用于数据源的实现,它从 Excel 文档中检索其数据。此数据源实现的报表字段映射也基于字段列索引。

JRXlsDataSource represents an implementation for data sources, which retrieve their data from Excel documents. Report-field mapping for this data source implementation is also based on the field column index.

Empty Data Sources

JREmptyDataSource 模拟了一个数据源,其内部具有给定数量的虚拟空记录。UI 工具使用它来提供基本的报表预览功能,或在特殊报表模板中,或用于测试和调试目的。

The class JREmptyDataSource, simulates a data source with a given number of virtual empty records inside. It is used by the UI tools to offer basic report preview functionality, or in special report templates, or for testing and debugging purposes.

Rewindable Data Sources

net.sf.jasperreports.engine.JRRewindableDataSource 扩展了基本的 JRDataSource 接口。它只会将一个方法 moveFirst() 添加到接口中。该方法旨在将光标移动到数据源中的第一个元素。

The net.sf.jasperreports.engine.JRRewindableDataSource extends the basic JRDataSource interface. It adds only one method, called moveFirst (), to the interface. This method is intended to move the cursor to the first element in the datasource.

当使用不允许拆分(因为 isSplitAllowed="false" 设置而产生)的频带中放置的子报表进行操作时,可回绕数据源非常有用,且当前页面上没有足够空间来渲染子报表。

Rewindable data sources are useful when working with sub-reports placed inside a band that is not allowed to split due to the isSplitAllowed="false" setting and there is not enough space on the current page for the sub report to be rendered.

以上所有数据源实现都是可回绕的,除了 JRResultSetDataSource ,因为它不支持将记录指针移回。仅当此数据源被手动用于包装一个 java.sql.ResultSet 并将其传递到子报表中时,才会出现问题。如果 SQL 查询位于子报表模板中,则不存在问题,因为引擎会在下个页面重新启动子报表时再次执行它。

All the above data source implementations are rewindable except for the JRResultSetDataSource, as it does not support moving the record pointer back. This poses a problem only if this data source is used manually to wrap a java.sql.ResultSet before passing it to the sub-report. There is no problem, if the SQL query resides in the sub-report template, as the engine will execute it again when restarting the sub-report on the next page.

Data Source Providers

JasperReports 库具有一个接口 net.sf.jasperreports.engine.JRDataSourceProvider 。它有助于创建和销毁数据源对象。在使用 GUI 工具创建报表模板时,需要一个用于定制报表数据源的特殊工具。JRDataSourceProvider 是将定制数据源插入设计工具中的标准方法。此接口的定制实现应实现以下方法,这些方法允许创建和销毁数据源对象,还允许(如果可能)列出数据源中可用的报表字段 −

The JasperReports library has an interface net.sf.jasperreports.engine.JRDataSourceProvider. This helps in creating and disposing of data source objects. When creating a report template using GUI tools, a special tool for customizing the report’s data source is needed. JRDataSourceProvider is the standard way to plug custom data sources into a design tool. A custom implementation of this interface should implement the following methods that allow creating and disposing of data source objects and also methods for listing the available report fields inside the data source if possible −

public boolean supportsGetFieldsOperation();

public JRField[] getFields(JasperReport report)
   throws JRException, UnsupportedOperationException;

public JRDataSource create(JasperReport report) throws JRException;

public void dispose(JRDataSource dataSource) throws JRException;

Reports Fields

报表字段是元素,表示数据源和报表模板之间的数据映射。可以将字段组合在报表表达式中以获得所需输出。报表模板可以包含零个或多个 <field> 元素。声明报表字段时,数据源应提供与报表模板中定义的所有字段相对应的数据。

Report fields are elements, which represent mapping of data between datasource and report template. Fields can be combined in the report expressions to obtain the desired output. A report template can contain zero or more <field> elements. When declaring report fields, the data source should supply data corresponding to all the fields defined in the report template.

Field Declaration

字段声明如下所示 -

Field declaration is done as shown below −

<field name = "FieldName" class = "java.lang.String"/>

The Name Attribute

<field> 元素的 name 属性是必需的。它通过名称引用报表表达式中的字段。

The name attribute of the <field> element is mandatory. It references the field in report expressions by name.

The Class Attribute

class 属性指定字段值类的名称。它的默认值为 java.lang.String。这可以在运行时更改为任何类。无论报表字段的类型如何,引擎都会负责将使用 $F{} 标记的报表表达式强制为适当的类型,因此无需手动强制类型转换。

The class attribute specifies the class name for the field values. Its default value is java.lang.String. This can be changed to any class available at runtime. Irrespective of the type of a report field, the engine takes care of casting in the report expressions in which the $F{} token is used, hence making manual casts unnecessary.

Field Description

<fieldDesciption> 元素是可选元素。在实现自定义数据源时,这非常有用。例如,我们可以存储键或某些信息,通过这些信息,我们可以从自定义数据源中检索字段值。通过使用 <fieldDesciption> 元素代替字段名称,可以在从数据源中检索字段值时轻松克服字段命名约定的限制。

The <fieldDesciption> element is an optional element. This is very useful when implementing a custom data source. For example, we can store a key or some information, by which we can retrieve the value of field from the custom data source at runtime. By using the <fieldDesciption> element instead of the field name, you can easily overcome restrictions of field-naming conventions when retrieving the field values from the data source.

下面是我们现有 JRXML 文件(第 Report Designs 章)中的一段代码。在这里,我们可以看到 nameclassfieldDescription 元素的用法。

Following is a piece of code from our existing JRXML file (Chapter Report Designs). Here, we can see usage of name, class, and fieldDescription elements.

<field name = "country" class = "java.lang.String">
   <fieldDescription><![CDATA[country]]></fieldDescription>
</field>

<field name = "name" class = "java.lang.String">
   <fieldDescription><![CDATA[name]]></fieldDescription>
</field>

Sort Fields

在需要对数据排序而数据源实现不支持的情况下(例如,CSV 数据源),JasperReports 支持基于字段的内存数据源排序。可以使用报表模板中的一个或多个 <sortField> 元素进行排序。

At the times when data sorting is required and the data source implementation doesn’t support it (for e.g. CSV datasource), JasperReports supports in-memory field-based data source sorting. The sorting can be done using one or more <sortField> elements in the report template.

如果指定了至少一个排序字段,则在报告填充过程中,数据源将传递给 JRSortableDataSource 实例。这会反过来从数据源获取所有记录,根据指定字段在内存中执行排序,并替换原始数据源。

If at least one sort field is specified, during report filling process, the data source is passed to a JRSortableDataSource instance. This in turn, fetches all the records from data source, performs in memory sort according to the specified fields, and replaces the original data source.

排序字段名称应与报表字段名称相同。用于排序的字段应具有实现 java.util.Comparable 的类型。除 java.lang.String 类型的字段之外,对所有字段执行自然顺序排序(对于 String 类型,使用与报表填充区域设置对应的收集器)。当指定多个排序字段时,将使用字段作为排序键按它们在报表模板中出现的顺序执行排序。以下示例演示了排序功能。

The sort field name should be identical to the report field name. Fields used for sorting should have types that implement java.util.Comparable. Natural order sorting is performed for all fields except those of type java.lang.String (for String type, collator corresponding to the report fill locale is used). When several sort Fields are specified, the sorting will be performed using the fields as sort keys in the order in which they appear in the report template. Following example demonstrates the sorting feature.

Sorted Report Example

让我们将 <*sortField*> 元素添加到我们现有的报表模板(第 Report designs 章)。让我们按降序对 country 字段进行排序。修改后的报表模板(jasper_report_template.jrxml)如下。将其保存到 C:\tools\jasperreports-5.0.1\test 目录 -

Let’s add the <*sortField*> element to our existing report template (Chapter Report designs). Let’s sort field country in descending order. The revised report template (jasper_report_template.jrxml) is as follows. Save it to C:\tools\jasperreports-5.0.1\test directory −

<?xml version = "1.0"?>
<!DOCTYPE jasperReport PUBLIC
   "//JasperReports//DTD Report Design//EN"
   "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">

<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi =
   "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation =
   "http://jasperreports.sourceforge.net/jasperreports
   http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
   name = "jasper_report_template" pageWidth = "595" pageHeight = "842"
   columnWidth = "515" leftMargin = "40" rightMargin = "40"
   topMargin = "50" bottomMargin = "50">

   <parameter name = "ReportTitle" class = "java.lang.String"/>
   <parameter name = "Author" class = "java.lang.String"/>

   <queryString>
      <![CDATA[]]>
   </queryString>

   <field name = "country" class = "java.lang.String">
      <fieldDescription><![CDATA[country]]></fieldDescription>
   </field>

   <field name = "name" class = "java.lang.String">
      <fieldDescription><![CDATA[name]]></fieldDescription>
   </field>

   <sortField name = "country" order = "Descending"/>
   <sortField name = "name"/>

   <title>
      <band height = "70">

         <line>
            <reportElement x = "0" y = "0" width = "515" height = "1"/>
         </line>

         <textField isBlankWhenNull = "true" bookmarkLevel = "1">
            <reportElement x = "0" y = "10" width = "515" height = "30"/>

            <textElement textAlignment = "Center">
               <font size = "22"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{ReportTitle}]]>
            </textFieldExpression>

            <anchorNameExpression>
               <![CDATA["Title"]]>
            </anchorNameExpression>
         </textField>

         <textField isBlankWhenNull = "true">
            <reportElement  x = "0" y = "40" width = "515" height = "20"/>

            <textElement textAlignment = "Center">
               <font size = "10"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{Author}]]>
            </textFieldExpression>

         </textField>

      </band>
   </title>

   <columnHeader>
      <band height = "23">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "3" width = "535" height = "15"
               backcolor = "#70A9A9" />

            <box>
               <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" />
            </box>

            <textElement />

            <text>
               <![CDATA[]]>
            </text>
         </staticText>

         <staticText>
            <reportElement x = "414" y = "3" width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>

            <text><![CDATA[Country]]></text>
         </staticText>

         <staticText>
            <reportElement x = "0" y = "3" width = "136" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>

            <text><![CDATA[Name]]></text>
         </staticText>

      </band>
   </columnHeader>

   <detail>
      <band height = "16">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "0" width = "535" height = "14"
               backcolor = "#E5ECF9" />

            <box>
               <bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" />
            </box>

            <textElement />
            <text>
               <![CDATA[]]>
            </text>
         </staticText>

         <textField>
            <reportElement x = "414" y = "0" width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font size = "9" />
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{country}]]>
            </textFieldExpression>
         </textField>

         <textField>
            <reportElement x = "0" y = "0" width = "136" height = "15" />
            <textElement textAlignment = "Center" verticalAlignment = "Middle" />

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{name}]]>
            </textFieldExpression>
         </textField>

      </band>
   </detail>

</jasperReport>

用于填充报告的 Java 代码保持不变。文件 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java 的内容如下 -

The java codes for report filling remains unchanged. The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java are as given below −

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class JasperReportFill {
   @SuppressWarnings("unchecked")
   public static void main(String[] args) {
      String sourceFileName =
      "C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper";

      DataBeanList DataBeanList = new DataBeanList();
      ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();

      JRBeanCollectionDataSource beanColDataSource =
      new JRBeanCollectionDataSource(dataList);

      Map parameters = new HashMap();
      /**
       * Passing ReportTitle and Author as parameters
       */
      parameters.put("ReportTitle", "List of Contacts");
      parameters.put("Author", "Prepared By Manisha");

      try {
         JasperFillManager.fillReportToFile(
         sourceFileName, parameters, beanColDataSource);
      } catch (JRException e) {
         e.printStackTrace();
      }
   }
}

C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java POJO 文件的内容如下 −

The contents of the POJO file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java are as given below −

package com.tutorialspoint;

public class DataBean {
   private String name;
   private String country;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getCountry() {
      return country;
   }

   public void setCountry(String country) {
      this.country = country;
   }
}

C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java 文件的内容如下 −

The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java are as given below −

package com.tutorialspoint;

import java.util.ArrayList;

public class DataBeanList {
   public ArrayList<DataBean> getDataBeanList() {
      ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();

      dataBeanList.add(produce("Manisha", "India"));
      dataBeanList.add(produce("Dennis Ritchie", "USA"));
      dataBeanList.add(produce("V.Anand", "India"));
      dataBeanList.add(produce("Shrinath", "California"));

      return dataBeanList;
   }

   /**
    * This method returns a DataBean object,
    * with name and country set in it.
    */
   private DataBean produce(String name, String country) {
      DataBean dataBean = new DataBean();
      dataBean.setName(name);
      dataBean.setCountry(country);

      return dataBean;
   }
}

Report generation

我们将使用常规 ANT 构建流程编译并执行上述文件。build.xml 文件(保存在 C:\tools\jasperreports-5.0.1\test 目录下)的内容如下。

We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are as given below.

导入文件 - baseBuild.xml 从第 Environment Setup 章节中选取,且应放置在与 build.xml 相同的目录中。

The import file - baseBuild.xml is picked from chapter Environment Setup and should be placed in the same directory as the build.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewFillReport" basedir = ".">
   <import file = "baseBuild.xml" />

   <target name = "viewFillReport" depends = "compile,compilereportdesing,run"
      description = "Launches the report viewer to preview
      the report stored in the .JRprint file.">

      <java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true">
         <arg value = "-F${file.name}.JRprint" />
         <classpath refid = "classpath" />
      </java>
   </target>

   <target name = "compilereportdesing" description = "Compiles the JXML file and
      produces the .jasper file.">

      <taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask">
         <classpath refid = "classpath" />
      </taskdef>

      <jrc destdir = ".">
         <src>
            <fileset dir = ".">
               <include name = "*.jrxml" />
            </fileset>
         </src>
         <classpath refid = "classpath" />
      </jrc>

   </target>

</project>

接下来,让我们打开命令行窗口并转到放置 build.xml 的目录。最后,执行以下命令 ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport 是默认目标) -

Next, let’s open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as follows −

C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml

clean-sample:
   [delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint

compile:
   [mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes
   [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28: warning:
   'includeantruntime' was not set, defaulting to build.sysclasspath=last;
   set to false for repeatable builds
   [javac] Compiling 7 source files to C:\tools\jasperreports-5.0.1\test\classes

compilereportdesing:
   [jrc] Compiling 1 report design files.
   [jrc] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
   [jrc] log4j:WARN Please initialize the log4j system properly.
   [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig
   for more info.
   [jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK.

run:
   [echo] Runnin class : com.tutorialspoint.JasperReportFill
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

viewFillReport:
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

BUILD SUCCESSFUL
Total time: 18 seconds

作为上述编译的结果,一个 JasperViewer 窗口会打开,如以下给出的屏幕截图所示 -

As a result of above compilation, a JasperViewer window opens up as shown in the screen given below −

report field sort example

在此,我们可以看到,国家名称按字母顺序降序排列。

Here, we can see that the country names are arranged in descending order alphabetically.

Report Expression

报表表达式是 JasperReports 的强大功能,它允许我们在报表上显示计算数据。计算数据不是静态数据,也没有特别作为报表参数或数据源字段传递。报表表达式由报表参数、字段和静态数据组合而成。默认情况下,Java 语言用于编写报表表达式。JasperReports 编译器支持用于报表表达式的其他脚本语言,如 Groovy 脚本语言、JavaScript 或 BeanShell 脚本。

Report expressions are the powerful features of JasperReports, which allow us to display calculated data on a report. Calculated data is the data that is not a static data and is not specifically passed as a report parameter or datasource field. Report expressions are built from combining report parameters, fields, and static data. The Java language is used for writing report expressions by default. Other scripting languages for report expressions like Groovy scripting language, JavaScript, or BeanShell script are supported by JasperReports compilers.

本章将为您解释报表表达式如何工作,假设报表表达式仅使用 Java 语言编写。在一个 JRXML 报表模板中,有若干元素定义表达式,如下 −

This chapter will explain you − how do report expressions work, assuming that they have been written using the Java language only. In a JRXML report template, there are several elements that define expressions as −

  1. <variableExpression>

  2. <initialValueExpression>

  3. <groupExpression>

  4. <printWhenExpression>

  5. <imageExpression>

  6. <textFieldExpression>

Expression Declaration

基本上,所有报表表达式都是 Java 表达式,可以引用报表字段、报表变量和报表参数。

Basically, all report expressions are Java expressions, which can reference the report fields, report variables, and report parameters.

Field Reference in Expression

要在表达式中使用报表字段引用,必须将字段的名称放在 $F{*and }* 字符序列之间,如下所示 −

To use a report field reference in an expression, the name of the field must be put between $F{*and}* character sequences, as shown below −

<textfieldexpression>
   $F{Name}
</textfieldexpression>

以下是现有 JRXML 文件中的一段代码(第 Report Designs) 章 −

Following is a piece of code from our existing JRXML file (chapter Report Designs)

<textFieldExpression class = "java.lang.String">
   <![CDATA[$F{country}]]>
</textFieldExpression>

Variable Reference in Expression

要在表达式中引用变量,必须将变量名称放在 $V{*and }* 之间,如下面给出的示例所示 −

To reference a variable in an expression, we must put the name of the variable between $V{*and}* as shown in the example given below −

<textfieldexpression>
   "Total height : " + $V{SumOfHeight} + " ft."
</textfieldexpression>

Parameter Reference in Expression

要在表达式中引用参数,应该将参数名称放在 $P{*and }* 之间,如下面给出的示例所示 −

To reference a parameter in an expression, the name of the parameter should be put between $P{*and}* as shown in the example given below −

<textfieldexpression>
   "ReportTitle : " + $P{Title}
</textfieldexpression>

以下是现有 JRXML 文件中的一段代码,它说明了如何在表达式中引用参数。(第 Report Designs 章的 JRXML) −

Following is a piece of code from our existing JRXML file, which demonstrates the referencing of parameter in an expression. (JRXML from chapter Report Designs) −

<textField isBlankWhenNull = "true" bookmarkLevel = "1">
   <reportElement x = "0" y = "10" width = "515" height = "30"/>

   <textElement textAlignment = "Center">
      <font size = "22"/>
   </textElement>

   <textFieldExpression class = "java.lang.String">
      <![CDATA[$P{ReportTitle}]]>
   </textFieldExpression>

   <anchorNameExpression>
      <![CDATA["Title"]]>
   </anchorNameExpression>
</textField>

<textField isBlankWhenNull = "true">
   <reportElement  x = "0" y = "40" width = "515" height = "20"/>

   <textElement textAlignment = "Center">
      <font size = "10"/>
   </textElement>

   <textFieldExpression class = "java.lang.String">
      <![CDATA[$P{Author}]]>
   </textFieldExpression>
</textField>

如您在上面看到的那样,参数、字段和变量引用实际上是真正的 Java 对象。通过在报表模板中进行参数、字段或变量声明了解它们的类,我们甚至可以在表达式中对那些对象引用调用方法。

As you have seen above, the parameter, field, and variable references are in fact real Java objects. Knowing their class from the parameter, field, or variable declaration made in the report template, we can even call methods on those object references in the expressions.

以下示例显示了如何从 java.lang.String 报表字段“Name”中提取并显示第一个字母 −

The following example shows − how to extract and display the first letter from java.lang.String report field "Name" −

<textFieldExpression>
   $F{Name}.substring(0, 1)
</textFieldExpression>

Resource Bundle Reference in Expression

要在表达式中引用资源,应将键放在 $R{*and }* 之间,如下面给出的示例所示 −

To reference a resource in an expression, the key should be put between $R{*and}* as shown in the example given below −

<textfieldexpression>
   $R{report.title}
</textfieldexpression>

基于运行时提供的语言环境和 report.title 键,加载与报表模板关联的资源包。因此,通过从资源包中提取 String 值来显示报表标题。关于国际化的更多信息可以在第 Internationalization 章中找到。

Based on the runtime-supplied locale and the report.title key, the resource bundle associated with the report template is loaded. Hence, the title of report is displayed by extracting the String value from the resource bundle. More on internationalization can be found in the chapter Internationalization.

Calculator

计算器是 JasperReports 中的一个实体,它在报告填充时评估表达式并增加变量或数据集。在编译过程中,编译器将生成信息并将其存储在编译报告中。在报告填充时,使用此信息来构建 net.sf.jasperreports.engine.fill.JRCalculator 类的实例。

Calculator is an entity in JasperReports, which evaluates expressions and increments variables or datasets at report-filling time. During compiling process, the information is produced and stored in the compile report by the compiler. This information is used during the report-filling time to build an instance of the net.sf.jasperreports.engine.fill.JRCalculator class.

Java 源文件由基于 Java 的报告编译器动态生成和编译。这个生成的类是 JRCalculator 的子类,编译生成字节码存储在 JasperReport 对象中。在报告填充时加载这个字节码,并实例化结果类以获取表达式评估所需的计算器对象。

Java source file is generated and compiled by Java-based report compilers on the fly. This generated class is a subclass of the JRCalculator, and the bytecode produced by compiling it is stored inside the JasperReport object. This bytcode is loaded at the report filling time and the resulting class is instantiated to obtain the calculator object needed for expression evaluation.

Conditional Expressions

定义变量表达式时,JasperReports 不支持 if-else 语句。相反,可以使用三元运算符 {cond} ? {statement 1} : {statement 2} 。此运算符可以嵌套在 Java 表达式中,以根据多种条件获取所需输出。

JasperReports doesn’t support if-else statements when defining variable expressions. Instead, you can use the ternary operators {cond} ? {statement 1} : {statement 2}. This operator can be nested inside a Java expression to obtain the desired output based on multiple conditions.

Example of conditional Expression in Report

让我们修改现有的报告模板(第 Report Designs 章),并为 country 字段添加条件表达式。修改后的报告模板 (jasper_report_template.jrxml) 如下。将其保存到 C:\tools\jasperreports-5.0.1\test 目录中−

Let’s modify existing report template (Chapter Report Designs) and add a conditional expression for the field country. The revised report template (jasper_report_template.jrxml) is as follows. Save it to C:\tools\jasperreports-5.0.1\test directory −

<?xml version = "1.0"?>
<!DOCTYPE jasperReport PUBLIC
   "//JasperReports//DTD Report Design//EN"
   "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">

<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation =
   "http://jasperreports.sourceforge.net/jasperreports
   http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
   name = "jasper_report_template" pageWidth = "595" pageHeight = "842"
   columnWidth = "515" leftMargin = "40" rightMargin = "40"
   topMargin = "50" bottomMargin = "50">

   <parameter name = "ReportTitle" class = "java.lang.String"/>
   <parameter name = "Author" class = "java.lang.String"/>

   <queryString>
      <![CDATA[]]>
   </queryString>

   <field name = "country" class = "java.lang.String">
      <fieldDescription><![CDATA[country]]></fieldDescription>
   </field>

   <field name = "name" class = "java.lang.String">
      <fieldDescription><![CDATA[name]]></fieldDescription>
   </field>

   <sortField name = "country" order = "Descending"/>
   <sortField name = "name"/>

   <title>
      <band height = "70">

         <line>
            <reportElement x = "0" y = "0" width = "515" height = "1"/>
         </line>

         <textField isBlankWhenNull = "true" bookmarkLevel = "1">
            <reportElement x = "0" y = "10" width = "515" height = "30"/>

            <textElement textAlignment = "Center">
               <font size = "22"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{ReportTitle}]]>
            </textFieldExpression>

            <anchorNameExpression>
               <![CDATA["Title"]]>
            </anchorNameExpression>
         </textField>

         <textField isBlankWhenNull = "true">
            <reportElement  x = "0" y = "40" width = "515" height = "20"/>

            <textElement textAlignment = "Center">
               <font size = "10"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{Author}]]>
            </textFieldExpression>
         </textField>

      </band>
   </title>

   <columnHeader>
      <band height = "23">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "3" width = "535" height = "15"
               backcolor = "#70A9A9" />

            <box>
               <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" />
            </box>

            <textElement />

            <text>
               <![CDATA[]]>
            </text>
         </staticText>

         <staticText>
            <reportElement x = "414" y = "3" width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>

            <text><![CDATA[Country]]></text>
         </staticText>

         <staticText>
            <reportElement x = "0" y = "3" width = "136" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>

            <text><![CDATA[Name]]></text>
         </staticText>

      </band>
   </columnHeader>

   <detail>
      <band height = "16">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "0" width = "535" height = "14"
               backcolor = "#E5ECF9" />

            <box>
               <bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" />
            </box>

            <textElement />

            <text>
               <![CDATA[]]>
            </text>
         </staticText>

         <textField>
            <reportElement x = "414" y = "0" width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font size = "9" />
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{country}.isEmpty() ? "NO COUNTRY" : $F{country}]]>
            </textFieldExpression>
         </textField>

         <textField>
            <reportElement x = "0" y = "0" width = "136" height = "15" />
            <textElement textAlignment = "Center" verticalAlignment = "Middle" />

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{name}]]>
            </textFieldExpression>
         </textField>

      </band>
   </detail>

</jasperReport>

报告填充的 Java 代码如下。文件 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java 的内容为 −

The java codes for report filling are as follows. The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java are as −

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class JasperReportFill {
   @SuppressWarnings("unchecked")
   public static void main(String[] args) {
      String sourceFileName =
      "C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper";

      DataBeanList DataBeanList = new DataBeanList();
      ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();

      JRBeanCollectionDataSource beanColDataSource =
      new JRBeanCollectionDataSource(dataList);

      Map parameters = new HashMap();
      /**
       * Passing ReportTitle and Author as parameters
       */
      parameters.put("ReportTitle", "List of Contacts");
      parameters.put("Author", "Prepared By Manisha");

      try {
         JasperFillManager.fillReportToFile(
         sourceFileName, parameters, beanColDataSource);
      } catch (JRException e) {
         e.printStackTrace();
      }
   }
}

POJO 文件 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java 的内容为 -

The contents of the POJO file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java are as −

package com.tutorialspoint;

public class DataBean {
   private String name;
   private String country;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getCountry() {
      return country;
   }

   public void setCountry(String country) {
      this.country = country;
   }
}

我们会在 Java Bean List 中添加一条新记录,country 字段为空。文件 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java 的内容为 −

We will add a new record with country field as empty in our Java bean List. The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java are as −

package com.tutorialspoint;

import java.util.ArrayList;

public class DataBeanList {
   public ArrayList<DataBean> getDataBeanList() {
      ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();

      dataBeanList.add(produce("Manisha", "India"));
      dataBeanList.add(produce("Dennis Ritchie", "USA"));
      dataBeanList.add(produce("V.Anand", "India"));
      dataBeanList.add(produce("Shrinath", "California"));
      dataBeanList.add(produce("Tanmay", ""));

      return dataBeanList;
   }

   /**
    * This method returns a DataBean object,
    * with name and country set in it.
    */
   private DataBean produce(String name, String country) {
      DataBean dataBean = new DataBean();
      dataBean.setName(name);
      dataBean.setCountry(country);

      return dataBean;
   }
}

Report Generation

我们使用常规 ANT 构建进程编译并执行上述文件。build.xml 文件(保存在目录 C:\tools\jasperreports-5.0.1\test 下)的内容如下。

We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are given below.

导入文件 - baseBuild.xml 取自第 Environment Setup ,应放在与 build.xml 相同的目录中。

The import file - baseBuild.xml is picked from chapter the Environment Setup and should be placed in the same directory as the build.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewFillReport" basedir = ".">
   <import file = "baseBuild.xml" />

   <target name = "viewFillReport" depends = "compile,compilereportdesing,run"
      description = "Launches the report viewer to preview
      the report stored in the .JRprint file.">

      <java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true">
         <arg value = "-F${file.name}.JRprint" />
         <classpath refid = "classpath" />
      </java>
   </target>

   <target name = "compilereportdesing" description = "Compiles the JXML file and
      produces the .jasper file.">

      <taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask">
         <classpath refid = "classpath" />
      </taskdef>

      <jrc destdir = ".">
         <src>
            <fileset dir = ".">
               <include name = "*.jrxml" />
            </fileset>
         </src>
         <classpath refid = "classpath" />
      </jrc>

   </target>

</project>

接下来,打开命令行窗口,并转到放置 build.xml 的目录。最后,执行命令 ant -Dmain-class = com.tutorialspoint.JasperReportFill (viewFullReport 是默认目标),如下所示:

Next, let’s open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class = com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as −

C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml

clean-sample:
   [delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint

compile:
   [mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes
   [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28:
   warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last;
   set to false for repeatable builds
   [javac] Compiling 3 source files to C:\tools\jasperreports-5.0.1\test\classes

compilereportdesing:
   [jrc] Compiling 1 report design files.
   [jrc] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
   [jrc] log4j:WARN Please initialize the log4j system properly.
   [jrc] log4j:WARN See
   http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
   [jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK.

run:
   [echo] Runnin class : com.tutorialspoint.JasperReportFill
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

viewFillReport:
    [java] log4j:WARN No appenders could be found for logger
    (net.sf.jasperreports.extensions.ExtensionsEnvironment).
    [java] log4j:WARN Please initialize the log4j system properly.

BUILD SUCCESSFUL
Total time: 5 minutes 5 seconds

C:\tools\jasperreports-5.0.1\test>

作为上述编译的结果,一个 JasperViewer 窗口会打开,如以下给出的屏幕截图所示 -

As a result of above compilation, a JasperViewer window opens up as shown in the screen given below −

report expression example

在这里,我们可以看到,对于最后一条记录,我们没有传递 country 字段的任何数据,“NO COUNTRY” 正在打印。

Here, we can see, for the last record, we had not passed any data for the field country, "NO COUNTRY" is being printed.

Report Variables

报表变量是建立在报表表达式之上的特殊对象。

Report variables are special objects built on top of the report expression.

报表变量简化了以下任务:

Report variables simplify the following tasks −

  1. Report expressions, which are heavily used throughout the report template. These expressions can be declared only once by using the report variables.

  2. Report variables can perform various calculations based on the corresponding expressions values such as count, sum, average, lowest, highest, variance, etc.

如果在报表设计中定义了变量,则表达式中的新变量可以引用这些变量。因此,在报表设计中声明变量的顺序很重要。

If variables are defined in a report design, then these can be referenced by new variables in the expressions. Hence, the order in which the variables are declared in a report design is important.

Variable Declaration

变量声明如下:

A variable declaration is as follows −

<variable name = "CityNumber" class = "java.lang.Integer" incrementType = "Group"
   incrementGroup = "CityGroup" calculation = "Count">
   <variableExpression>
      <![CDATA[Boolean.TRUE]]>
   </variableExpression>
</variable>

如上所见,<variable> 元素包含许多属性。这些属性总结如下:

As seen above, <variable> element contains number of attributes. These attributes are summarized below −

The Name Attribute

与参数和字段类似,</variable> 元素的 name 属性是必需的。它允许通过其在报表表达式中声明的名称引用变量。

Similar to parameters and fields, the name attribute of </variable> element is mandatory. It allows referencing the variable by its declared name in the report expressions.

The Class Attribute

class 属性也是必需的,它为变量值指定类名。其默认值为 java.lang.String。可以在报表编译时间和报表填充时间将其更改为在类路径中可用的任何类。引擎负责在报表表达式中使用 $V{} 令牌的类型转换,因此不需要手动类型转换。

The class attribute is also mandatory that specifies the class name for the variable values. Its default value is java.lang.String. This can be changed to any class available in the classpath, both at the report-compilation time and the report filling time. The engine takes care of type-casting in report expressions which the $V{} token is used, hence manual type-casting is not required.

Calculation

此属性确定——在填充报表时对变量执行什么计算。以下小节描述了 <variable> 元素的 calculation 属性的所有可能值。

This attribute determines − what calculation to perform on the variable when filling the report. The following subsections describe all the possible values for the calculation attribute of the <variable> element.

  1. Average − The variable value is the average of every non-null value of the variable expression. Valid for numeric variables only.

  2. Count − The variable value is the count of non-null instances of the variable expression.

  3. First − The variable value is the value of the first instance of the variable expression. Subsequent values are ignored.

  4. Highest − The variable value is the highest value for the variable expression.

  5. Lowest − The variable value is the lowest value for the variable expression in the report.

  6. Nothing − No calculations are performed on the variable.

  7. StandardDeviation − The variable value is the standard deviation of all non-null values matching the report expression. Valid for numeric variables only.

  8. Sum − The variable value is the sum of all non-null values returned by the report expression.

  9. System − The variable value is a custom calculation (calculating the value for that variable yourself, using the scriptlets functionality of JasperReports).

  10. Variance − The variable value is the variance of all non-null values returned by evaluation of the report variable’s expression.

Incrementer FactoryClass

此属性决定在报表上填写当前记录时用于计算变量值所用的类。默认值应为实施 net.sf.jasperreports.engine.fill.JRIncrementerFactory 的任何类。引擎将在运行时使用工厂类来根据变量所设置的计算属性实例化增量对象。

This attribute determines the class used to calculate the value of the variable when filling the current record on the report. Default value would be any class implementing net.sf.jasperreports.engine.fill.JRIncrementerFactory. The factory class will be used by the engine to instantiate incrementer objects at runtime depending on the calculation attribute set for the variable.

IncrementType

这决定何时重新计算变量值。此属性使用值,如下 −

This determines when to recalculate the value of the variable. This attribute uses values, as below −

  1. Column − The variable value is recalculated at the end of each column.

  2. Group − The variable value is recalculated when the group specified by incrementGroup changes.

  3. None − The variable value is recalculated with every record.

  4. Page − The variable value is recalculated at the end of every page.

  5. Report − The variable value is recalculated once, at the end of the report.

IncrementGroup

当 incrementType 为组时,这决定在哪个组名称处重新计算变量值。此处为 JRXML 报表模板中声明的任何组之名称。

This determines the name of the group at which the variable value is recalculated, when incrementType is Group. This takes name of any group declared in the JRXML report template.

ResetType

这决定何时重置变量值。此属性使用值,如下 −

This determines when the value of a variable is reset. This attribute uses values, as below −

  1. Column − The variable value is reset at the beginning of each column.

  2. Group − The variable value is reset when the group specified by incrementGroup changes.

  3. None − The variable value is never reset.

  4. Page − The variable value is reset at the beginning of every page.

  5. Report − The variable value is reset only once, at the beginning of the report.

ResetGroup

当 resetType 为组时,这决定在哪个组名称处重置变量值。此属性的值为 JRXML 报表模板中声明的任何组的名称。

This determines the name of the group at which the variable value is reset, when resetType is Group. The values for this attribute would be the name of any group declared in the JRXML report template.

Built-In Report Variables

有些内置系统变量随时可用于表达式中,如下 −

There are some built-in system variables, ready to use in expressions, as follows −

S.NO

Variable Name and Description

1

PAGE_NUMBER This variable’s value is its current page number. It can be used to display both the current page number and the total number of pages using a special feature of JasperReports text field elements, the evaluationTime attribute.

2

COLUMN_NUMBER This variable contains the current column number.

3

REPORT_COUNT This report variable contains the total number of records processed.

4

PAGE_COUNT This variable contains the number of records that were processed when generating the current page.

5

COLUMN_COUNT This variable contains the number of records that were processed when generating the current column.

6

GroupName_COUNT The name of this variable is derived from the name of the group it corresponds to, suffixed with the _COUNT sequence. This variable contains the number of records in the current group.

Example

让我们向现有报表模板(第 Report Designs 章)添加一个变量( countNumber )。我们将在每个记录之前添加计数。经修订的报表模板(jasper_report_template.jrxml)如下。将其保存到 C:\tools\jasperreports-5.0.1\test 目录中−

Let’s add a variable (countNumber) to our existing report template (Chapter Report Designs). We will prefix the count to each record. The revised report template (jasper_report_template.jrxml) is as follows. Save it to C:\tools\jasperreports-5.0.1\test directory −

<?xml version = "1.0"?>
<!DOCTYPE jasperReport PUBLIC
   "//JasperReports//DTD Report Design//EN"
   "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">

<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
   http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
   name = "jasper_report_template" pageWidth = "595"
   pageHeight = "842" columnWidth = "515"
   leftMargin = "40" rightMargin = "40" topMargin = "50" bottomMargin = "50">

   <parameter name = "ReportTitle" class = "java.lang.String"/>
   <parameter name = "Author" class = "java.lang.String"/>

   <queryString>
      <![CDATA[]]>
   </queryString>

   <field name = "country" class = "java.lang.String">
      <fieldDescription>
         <![CDATA[country]]>
      </fieldDescription>
   </field>

   <field name = "name" class = "java.lang.String">
      <fieldDescription>
         <![CDATA[name]]>
      </fieldDescription>
   </field>

   <variable name = "countNumber" class = "java.lang.Integer" calculation = "Count">
      <variableExpression>
         <![CDATA[Boolean.TRUE]]>
      </variableExpression>
   </variable>

   <title>
      <band height = "70">

         <line>
            <reportElement x = "0" y = "0" width = "515" height = "1"/>
         </line>

         <textField isBlankWhenNull = "true" bookmarkLevel = "1">
            <reportElement x = "0" y = "10" width = "515" height = "30"/>

            <textElement textAlignment = "Center">
               <font size = "22"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{ReportTitle}]]>
            </textFieldExpression>

            <anchorNameExpression>
               <![CDATA["Title"]]>
            </anchorNameExpression>
         </textField>

         <textField isBlankWhenNull = "true">
            <reportElement  x = "0" y = "40" width = "515" height = "20"/>

            <textElement textAlignment = "Center">
               <font size = "10"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{Author}]]>
            </textFieldExpression>
         </textField>

      </band>
   </title>

   <columnHeader>
      <band height = "23">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "3" width = "535"	height = "15"
               backcolor = "#70A9A9" />

            <box>
               <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" />
            </box>

            <textElement />

            <text>
               <![CDATA[]]>
            </text>
         </staticText>

         <staticText>
            <reportElement x = "414" y = "3" width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>

            <text><![CDATA[Country]]></text>
         </staticText>

         <staticText>
            <reportElement x = "0" y = "3" width = "136" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>

            <text><![CDATA[Name]]></text>
         </staticText>

      </band>
   </columnHeader>

   <detail>
      <band height = "16">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "0" width = "535" height = "14"
               backcolor = "#E5ECF9" />

            <box>
               <bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" />
            </box>

            <textElement />

            <text>
               <![CDATA[]]>
            </text>
         </staticText>

         <textField>
            <reportElement x = "414" y = "0" width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font size = "9" />
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{country}]]>
            </textFieldExpression>
         </textField>

         <textField>
            <reportElement x = "0" y = "0" width = "136" height = "15" />
            <textElement textAlignment = "Center" verticalAlignment = "Middle" />

            <textFieldExpression class = "java.lang.String">
               <![CDATA["  " + String.valueOf($V{countNumber}) +"."+$F{name}]]>
            </textFieldExpression>
         </textField>

      </band>
   </detail>

</jasperReport>

用于填充报告的 Java 代码保持不变。文件 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java 的内容如下 -

The java codes for report filling remains unchanged. The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java are as given below −

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class JasperReportFill {
   @SuppressWarnings("unchecked")
   public static void main(String[] args) {
      String sourceFileName =
      "C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper";

      DataBeanList DataBeanList = new DataBeanList();
      ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();

      JRBeanCollectionDataSource beanColDataSource =
      new JRBeanCollectionDataSource(dataList);

      Map parameters = new HashMap();
      /**
       * Passing ReportTitle and Author as parameters
       */
      parameters.put("ReportTitle", "List of Contacts");
      parameters.put("Author", "Prepared By Manisha");

      try {
         JasperFillManager.fillReportToFile(
         sourceFileName, parameters, beanColDataSource);
      } catch (JRException e) {
         e.printStackTrace();
      }
   }
}

C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java POJO 文件的内容如下 −

The contents of the POJO file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java are as given below −

package com.tutorialspoint;

public class DataBean {
   private String name;
   private String country;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getCountry() {
      return country;
   }

   public void setCountry(String country) {
      this.country = country;
   }
}

C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java 文件的内容如下 −

The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java are as given below −

package com.tutorialspoint;

import java.util.ArrayList;

public class DataBeanList {
   public ArrayList<DataBean> getDataBeanList() {
      ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();

      dataBeanList.add(produce("Manisha", "India"));
      dataBeanList.add(produce("Dennis Ritchie", "USA"));
      dataBeanList.add(produce("V.Anand", "India"));
      dataBeanList.add(produce("Shrinath", "California"));

      return dataBeanList;
   }

   /**
    * This method returns a DataBean object,
    * with name and country set in it.
    */
   private DataBean produce(String name, String country) {
      DataBean dataBean = new DataBean();
      dataBean.setName(name);
      dataBean.setCountry(country);

      return dataBean;
   }
}

Report Generation

我们将使用常规 ANT 构建流程编译并执行上述文件。build.xml 文件(保存在 C:\tools\jasperreports-5.0.1\test 目录下)的内容如下。

We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are as given below.

导入文件 - baseBuild.xml 从第 Environment Setup 章选取并应该放置在与 build.xml 相同的目录中。

The import file - baseBuild.xml is picked from the chapter Environment Setup and should be placed in the same directory as the build.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewFillReport" basedir = ".">

   <import file = "baseBuild.xml" />
   <target name = "viewFillReport" depends = "compile,compilereportdesing,run"
      description = "Launches the report viewer to preview
      the report stored in the .JRprint file.">

      <java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true">
         <arg value = "-F${file.name}.JRprint" />
         <classpath refid = "classpath" />
      </java>
   </target>

   <target name = "compilereportdesing" description = "Compiles the JXML file and
      produces the .jasper file.">

      <taskdef name = "jrc"
         classname = "net.sf.jasperreports.ant.JRAntCompileTask">
         <classpath refid = "classpath" />
      </taskdef>

      <jrc destdir = ".">
         <src>
            <fileset dir = ".">
               <include name = "*.jrxml" />
            </fileset>
         </src>
         <classpath refid = "classpath" />
      </jrc>

   </target>

</project>

接下来,让我们打开命令行窗口并进入放置 build.xml 的目录。最后,执行命令 ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport 是默认目标),如下所示 −

Next, let’s open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as −

C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml

clean-sample:
   [delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint

compile:
   [mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes
   [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28: warning:
   'includeantruntime' was not set, defaulting to build.sysclasspath=last;
   set to false for repeatable builds
   [javac] Compiling 7 source files to C:\tools\jasperreports-5.0.1\test\classes

compilereportdesing:
   [jrc] Compiling 1 report design files.
   [jrc] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
   [jrc] log4j:WARN Please initialize the log4j system properly.
   [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig
   for more info.
   [jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK.

run:
   [echo] Runnin class : com.tutorialspoint.JasperReportFill
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

viewFillReport:
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

BUILD SUCCESSFUL
Total time: 18 seconds

以上编译的结果是在屏幕下方打开一个 JasperViewer 窗口−

As a result of above compilation, a JasperViewer window opens up as in the screen below −

report variable example

此处,我们看到每个记录前加了计数。

Here, we see that the count is prefixed for each record.

Report Sections

我们在第 Getting Started 章讨论了一个简单报表模板的结构。JasperReports 根据类似的方法,将报表模板构建为多个部分。部分是具有指定高度的报表部分,可包含报表对象,如线条、矩形、图像或文本字段。

We discussed the structure of a simple report template in the chapter Getting Started. On similar lines, JasperReports structures the report template into multiple sections. Sections are portions of the report that have a specified height and can contain report objects like lines, rectangles, images, or text fields.

报表引擎在报表填充时遍历所提供的报表数据源的虚拟记录。然后,根据每个部分定义的行为,引擎在适当的时候呈现每个报表部分。例如,针对数据源中的每个记录呈现详细信息部分。发生分页时,按需呈现页眉和页脚部分。

The report engine iterates through the virtual records of the supplied report data source, at report filling time. Depending on each section’s defined behavior, the engine then renders each report section when appropriate. For instance, the detail section is rendered for each record in the data source. When page breaks occur, the page header and page footer sections are rendered as needed.

在 JasperReports 中,术语和报表部分也称为 report bands 。部分由一个或多个波段组成。这些部分在报表生成时重复填充,并准备最终的文档。

In JasperReports, terminology and report sections are also called as report bands. Sections are made up of one or more bands. These sections are filled repeatedly at report-generating time and prepare the final document.

Main Sections

JasperReports 中的报表模板包含以下主要部分:−

A report template in JasperReports has the following main sections −

<title></title>

<pageheader></pageheader>

<columnheader></columnheader>

<groupheader></groupheader>

<detail></detail>

<groupfooter></groupfooter>

<columnfooter></columnfooter>

<pagefooter></pagefooter>

<lastpagefooter></lastpagefooter>

<summary></summary>

<nodata></nodata>

<background></background>

下表总结了各个部分 −

The following table summarizes each of the sections −

S.NO

Section and Description

1

Title This section appears only once at the beginning of the report.

2

Page Header This section appears at the beginning of each page in the generated document.

3

Column Header This section appears at the beginning of each column in the generated document. If the report has only one column defined, then column header and footer sections are ignored.

4

Group Header This section is introduced by a report group (chapter Groups). Each time the grouping expression changes its value, the group header section is printed above the detail section. In case, if more than one group is defined, the group header is printed in the order of group definition.

5

Detail This section is repeated for each line of data supplied by the report’s data source. The detail section can be made of multiple bands.

6

Group Footer This section is introduced by a report group (chapter Groups). The group footer section is printed below the detail section before the value of the grouping expression changes. The group footer is always printed for the last line of data in data source. In case, if more than one group is defined, the group footer is printed in the reverse order of group definition.

7

Column Footer This section appears at the bottom of each column. If the report’s column count is 1, then column header and footer sections are ignored.

8

Page Footer This section appears at the bottom of each page.

9

Last Page Footer This section replaces the regular page footer on the last page of the report. In case, the summary section is also present, then this might not be the very last page of the document. This section is sometimes useful when summary information has to be displayed at the bottom of the last page.

10

Summary This section appears only once at the end of the report.

11

No Data This section is printed when the When No Data Print report property is set to No Data Section. If the <noData> section is defined in the report template, and if the data source is empty, then the <noData> section will be the only one taken into account at fill time, and its content will produce the report output.

12

Background The background section is displayed on every page and cannot overflow to the next page. Elements placed on this section are evaluated at page initialization time and are displayed in the background. All other page objects are displayed on top of the background objects. This section is useful for creating page watermarks.

Section, Elements and Attribute Relation

下图显示报表节中元素和属性之间的关系。

The following diagram shows the elements and attributes relationship in a section of a report.

report sections

Section Elements

上述所有报表节都是可选的。但是,任何报表模板至少都有一个此类节。每个此类节都包含一个单一的 <*band*> 元素作为其唯一子元素。<*band*> 可以包含零个或多个以下子元素 -

All the above mentioned report sections are optional. But any report template will have at least one such section. Each of these sections contains a single <*band*> element as its only sub-element. A <*band*> can contain zero or more following sub-elements −

<line>, <rectangle>, <ellipse>, <image>, <staticText>, <textField>, <subReport> 或 <elementGroup>

<line>, <rectangle>, <ellipse>, <image>, <staticText>, <textField>, <subReport>, or <elementGroup>

除了元素组外,每个此类元素都必须包含一个单一的 <*reportElement*> 作为其第一个元素。<*reportElement*> 确定为该特定元素布局数据的方式。与变量和参数不同,报表元素不需要具有名称,因为通常无需在报表模板中获取任何单个元素。

Each of these elements must contain a single <*reportElement*> as its first element (except elementGroup). A <*reportElement*> determines how data is laid out for that particular element. Unlike variables and parameters, report elements are not required to have a name, because normally you do not need to obtain any individual element inside a report template.

下表汇总了 <*reportElement*> 的属性 -

The table below summarizes the attributes of <*reportElement*> −

Attribute

Description

Valid Values

x

Specifies the x coordinate of the band element.

An integer value indicating the x coordinate of the element in pixels. This attribute is required.

y

Specifies the y coordinate of the band element.

An integer value indicating the y coordinate of the element in pixels. This attribute is required.

width

Specifies the width of the band element.

An integer value indicating the element width in pixels. This attribute is required.

height

Specifies the height of the band element.

An integer value indicating the element height in pixels. This attribute is required.

key

Unique identifier of band element.

A unique string value.

stretchType

Specifies how does the element stretch when the containing band stretches

NoStretch (default) − The element will not stretch. RelativeToTallestObject − The element will stretch to accommodate the tallest object in its group. RelativeToBand − The element will stretch to fit the band’s height.

positionType

Specifies the element’s position when the band stretches.

Float − The element will move depending on the size of the surrounding elements. FixRelativeToTop (default) − The element will maintain a fixed position relative to the band’s top. FixRelativeToBottom − The element will maintain a fixed position relative to the band’s bottom.

isPrintRepeatedValues

Specifies if repeated values are printed.

true (default) − Repeated values will be printed. false − Repeated values will not be printed.

mode

Specifies the background mode of the element

Opaque, Transparent

isRemoveLineWhenBlank

Specifies if the element should be removed when it is blank and there are no other elements in the same horizontal space.

true, false

isPrintInFirstWholeBand

Specifies if the element must be printed in a whole band, that is, a band that is not divided between report pages or columns.

true, false

isPrintWhenDetailOverFlows

Specifies if the element will be printed when the band overflows to a new page or column.

true, false

printWhenGroupChanges

Specifies that the element will be printed when the specified group changes.

A string value.

forecolor

Specifies the foreground color of the element.

Either a hexadecimal RGB value preceded by the # character, or one of the following predefined values: black, blue, cyan, darkGray, gray, green, lightGray, magenta, orange, pink, red, yellow, white.

backcolor

Specifies the background color of the element.

Same as Valid Values for forecolor

Section Attributes

下面是报表部分的属性 -

Following are the attributes of a report section −

Height

指定部分的高度(像素)对于特定部分非常重要,在整体报表设计中非常重要。

Height of the section specifies the height in pixels for that particular section and is very important in the overall report design.

Print When Expression

布尔表达式,用于确定是否打印节。

A Boolean expression that determines whether the section should be printed or not.

Split Allowed

用于指示是否允许节在当前页无法容纳时拆分。如果为 true,则将节转移到下一页。请注意,如果节不适应下一页,则无论标志值如何,都会拆分节。splitType 可采用以下值:

A flag indicating whether the section is allowed to split when it does not fit on the current page. If true, the section will be transferred to the next page. Note that in case, the section does not fit on the next page, then the section will be split regardless of the flag’s value. splitType can take following values −

  1. splitType="Stretch:" Splits stretched content. If the section stretches on the current page (if the available space is less than declared height), the region that is added to the original height is allowed to split onto the next page.

  2. splitType="Prevent:" Prevent split on first attempt. If the section does not fit on the next page, the split occurs normally, as band split prevention is effective only on the first split attempt.

  3. splitType="Immediate:" Split immediately. The band is allowed to split anywhere except above, its topmost element.

Example

为了演示每个节,让我们编写报表模板(jasper_report_template.jrxml)。将此文件保存到 C:\tools\jasperreports-5.0.1\test 目录。在此文件中,我们在每个节中显示一个文本(我们上面讨论)。文件内容如下:

To demonstrate each section, let’s write report template (jasper_report_template.jrxml). Save this file to C:\tools\jasperreports-5.0.1\test directory. In this file, we would be displaying a text in each of the sections (we discussed above). The contents of the file are as given below −

<?xml version = "1.0" encoding = "UTF-8"?>

<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
   http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
   name = "jasper_report_template" pageWidth = "300" pageHeight = "300"
   columnWidth = "300" leftMargin = "0" rightMargin = "0"
   topMargin = "0" bottomMargin = "0" >

   <title>
      <band height = "50">

         <textField>
            <reportElement x = "100" y = "16" width = "100" height = "20"/>
            <textElement/>

            <textFieldExpression>
               <![CDATA["Title"]]>
            </textFieldExpression>

         </textField>

      </band>
   </title>

   <pageHeader>
      <band height = "40">

         <textField>
            <reportElement  mode = "Opaque" x = "100" y = "10"
               width = "90" height = "20"/>

            <textElement>
               <font isBold = "true"/>
            </textElement>

            <textFieldExpression>
               <![CDATA["Page Header"]]>
            </textFieldExpression>
         </textField>

      </band>
   </pageHeader>

   <columnHeader>
      <band height = "40">

         <textField>
            <reportElement  x = "100" y = "10" width = "90" height = "20"/>

            <textElement>
               <font isItalic = "true"/>
            </textElement>

            <textFieldExpression>
               <![CDATA["Column Header"]]>
            </textFieldExpression>
         </textField>

      </band>
   </columnHeader>

   <detail>
      <band height ="40">

         <textField>
            <reportElement mode = "Opaque" x = "100" y = "10"
               width = "90" height = "20" backcolor = "#99CCFF"/>
            <textElement/>

            <textFieldExpression>
               <![CDATA["Report Details"]]>
            </textFieldExpression>
         </textField>

      </band>
   </detail>

   <columnFooter>
      <band height = "40">

         <textField>
            <reportElement  x = "100" y = "10" width = "90" height = "20"/>
            <textElement/>

            <textFieldExpression>
               <![CDATA["Column Footer"]]>
            </textFieldExpression>
         </textField>

      </band>
   </columnFooter>

   <pageFooter>
      <band height = "40">

         <textField>
            <reportElement  x = "100" y = "10" width = "90" height = "20"/>
            <textElement/>

            <textFieldExpression>
               <![CDATA["Page Footer"]]>
            </textFieldExpression>
         </textField>

      </band>
   </pageFooter>

   <lastPageFooter>
      <band height = "40">

         <textField>
            <reportElement  x = "100" y = "10" width = "90" height = "20"/>
            <textElement/>

            <textFieldExpression>
               <![CDATA["Last Page Footer"]]>
            </textFieldExpression>
         </textField>

      </band>
   </lastPageFooter>

   <summary>
      <band height = "40">

         <textField>
            <reportElement  x = "100" y = "10" width = "90" height = "20"/>
            <textElement/>

            <textFieldExpression>
               <![CDATA["Summary"]]>
            </textFieldExpression>
         </textField>

      </band>
   </summary>

</jasperReport>

填充和生成报表的 Java 代码如下。让我们将此文件 JasperReportFill.java 保存到 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint 目录。

The java code to fill and generate the report is given below. Let’s save this file JasperReportFill.java to C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint directory.

package com.tutorialspoint;

import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;

public class JasperReportFill {
   public static void main(String[] args) {
      String sourceFileName = "C://tools/jasperreports-5.0.1/test/" +
         "jasper_report_template.jasper";

      try {
         JasperFillManager.fillReportToFile(sourceFileName, null,
            new JREmptyDataSource());
      } catch (JRException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }

   }
}

在此,我们在填充报表时使用 JREmptyDataSource 的一个实例来模拟具有一个记录的数据源,但此单个记录中的所有字段均为 null。

Here, we use an instance of JREmptyDataSource when filling reports to simulate a data source with one record in it, but with all the fields in this single record being null.

Report Generation

我们将使用常规的 ANT 构建过程编译并执行以上文件。文件 build.xml(保存在 C:\tools\jasperreports-5.0.1\test 目录下)的内容如下。

We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are as below.

导入文件 - baseBuild.xml 从第 Environment Setup 章中获取,并应放置在与 build.xml 相同的目录中。

The import file - baseBuild.xml is picked up from the chapter Environment Setup and should be placed in the same directory as the build.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewFillReport" basedir = ".">

   <import file = "baseBuild.xml" />
   <target name = "viewFillReport" depends = "compile,compilereportdesing,run"
      description = "Launches the report viewer to preview
      the report stored in the .JRprint file.">

      <java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true">
         <arg value = "-F${file.name}.JRprint" />
         <classpath refid = "classpath" />
      </java>

   </target>

   <target name = "compilereportdesing" description = "Compiles the JXML file and
      produces the .jasper file.">

      <taskdef name = "jrc"
         classname = "net.sf.jasperreports.ant.JRAntCompileTask">
         <classpath refid = "classpath" />
      </taskdef>

      <jrc destdir = ".">
         <src>
            <fileset dir = ".">
               <include name = "*.jrxml" />
            </fileset>
         </src>
         <classpath refid = "classpath" />
      </jrc>

   </target>

</project>

接下来,让我们打开命令行窗口并转到放置 build.xml 的目录。最后,执行以下命令 ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport 是默认目标) -

Next, let’s open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as follows −

C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml

clean-sample:
   [delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint

compile:
   [mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes
   [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28:
   warning: 'includeantruntime' was not set, defau
   [javac] Compiling 1 source file to C:\tools\jasperreports-5.0.1\test\classes

compilereportdesing:
   [jrc] Compiling 1 report design files.
   [jrc] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.engine.xml.JRXmlDigesterFac
   [jrc] log4j:WARN Please initialize the log4j system properly.
   [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
   [jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK.

run:
   [echo] Runnin class : com.tutorialspoint.JasperReportFill
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnviro
   [java] log4j:WARN Please initialize the log4j system properly.

viewFillReport:
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnviro
   [java] log4j:WARN Please initialize the log4j system properly.

BUILD SUCCESSFUL
Total time: 18 minutes 22 seconds

以上编译的结果是在屏幕下方打开一个 JasperViewer 窗口−

As a result of above compilation, a JasperViewer window opens up as in the screen below −

report sections example

在这里,我们可以在每个节中看到打印了一个文本。需要注意的是,由于 JRXML 包含一个 <lastPageFooter> 元素,它将显示在报表的最后一页,而不是显示 <pageFooter> 元素。如果报表有多个列,则只会在报表上显示 <columnHeader> 和 <columnFooter> 元素。

Here, we can see in each of the sections a text is printed. It is to be noted that as JRXML contains a <lastPageFooter> element, it will be displayed in the last page of the report instead of the <pageFooter> element being displayed. The <columnHeader> and <columnFooter> elements will only be displayed on the report, if it has more than one column.

Report Groups

JasperReports 中的组有助于以一种合乎逻辑的方式整理报表上的数据。报表组表示数据源中连续记录的序列,这些记录具有一些共同点,例如某个报表字段的值。报表组由 <group> 元素定义。报表可以有任意数量的组。声明后,可以在整个报表中引用组。

Groups in JasperReports help to organize data on report in a logical manner. A report group represents a sequence of consecutive records in the data source, which have something in common, such as the value of a certain report fields. A report group is defined by the <group> element. A report can have any number of groups. Once declared, groups can be referred throughout the report.

报表组有三个元素:

A report group has three elements −

  1. Group expression − This indicates the data that must change to start a new data group.

  2. Group header section − Helps place label at the beginning of the grouped data.

  3. Group footer section − Helps place label at the end of the grouped data.

如果在报表填充时迭代遍历数据源时组表达式的值发生更改,则组会中断,并且在结果文档中插入相应的 <groupFooter> 和 <groupHeader> 节。

During the iteration through the data source at report-filling time if the value of the group expression changes, a group rupture occurs and the corresponding <groupFooter> and <groupHeader> sections are inserted in the resulting document.

报表组机制不对数据源提供的的数据执行任何排序。仅当数据源中的记录已经按照报表中使用的组表达式进行排序时,数据分组才会按预期工作。

Report group mechanism does not perform any sorting on the data supplied by the data source. Data grouping works as expected only when the records in the data source are already ordered according to the group expressions used in the report.

Group Attributes

<group> 元素包含允许我们控制分组数据如何布局的属性。这些属性总结在下面的表格中:

The <group> element contains attributes that allow us to control how grouped data is laid out. The attributes are summarized in table below −

S.NO

Attribute and Description

1

name This is mandatory. It references the group in report expressions by name. It follows the same naming conventions that we mentioned for the report parameters, fields, and report variables. It can be used in other JRXML attributes when you want to refer a particular report group.

2

isStartNewColumn When set to true, each data group will begin on a new column. Default value is false.

3

isStartNewPage When set to true, each data group will begin on a new page. Default value is false.

4

isResetPageNumber When set to true, the report page number will be reset every time a new group starts. Default value is false.

5

isReprintHeaderOnEachPage When set to true, the group header will be reprinted on every page. Default value is false.

6

minHeightToStartNewPage Defines minimum amount of vertical space needed at the bottom of the column in order to place the group header on the current column. The amount is specified in report units.

7

footerPosition Renders position of the group footer on the page, as well as its behavior in relation to the report sections that follow it.Its value can be: Normal, StackAtBottom, ForceAtBottom, and CollateAtBottom. Default value is Normal.

8

keepTogether When set to true, prevents the group from splitting on its first break attempt.

Example

让我们在现有的报表模板中添加一个组 ( CountryGroup ),(第 Report Designs 章),统计每个国家的出现次数,并将其显示为小组页脚。组头中,每个记录的计数作为前缀,经过修订的报表模板 (jasper_report_template.jrxml) 如下。将其保存到 C:\tools\jasperreports-5.0.1\test 目录中−

Let’s add a group (CountryGroup) to existing report template (Chapter Report Designs). Occurrence of each country is counted and the count is displayed as the group footer. In the group header, the count of each record is prefixed. The revised report template (jasper_report_template.jrxml) is as follows. Save it to C:\tools\jasperreports-5.0.1\test directory −

<?xml version = "1.0"?>
<!DOCTYPE jasperReport PUBLIC
   "//JasperReports//DTD Report Design//EN"
   "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">

<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
   http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
   name = "jasper_report_template" pageWidth = "595"
   pageHeight = "842" columnWidth = "515"
   leftMargin = "40" rightMargin = "40" topMargin = "50" bottomMargin = "50">

   <parameter name = "ReportTitle" class = "java.lang.String"/>
   <parameter name = "Author" class = "java.lang.String"/>

   <queryString>
      <![CDATA[]]>
   </queryString>

   <field name = "country" class = "java.lang.String">
      <fieldDescription><![CDATA[country]]></fieldDescription>
   </field>

   <field name = "name" class = "java.lang.String">
      <fieldDescription><![CDATA[name]]></fieldDescription>
   </field>

   <sortField name = "country" order = "Descending"/>
   <sortField name = "name"/>

   <variable name = "CountryNumber" class = "java.lang.Integer"
      incrementType = "Group" incrementGroup = "CountryGroup"
      calculation = "Count">
      <variableExpression><![CDATA[Boolean.TRUE]]></variableExpression>
   </variable>

   <group name = "CountryGroup" minHeightToStartNewPage = "60">
      <groupExpression><![CDATA[$F{country}]]></groupExpression>

      <groupHeader>
         <band height = "20">

            <textField evaluationTime = "Group" evaluationGroup = "CountryGroup"
               bookmarkLevel = "1">
               <reportElement mode = "Opaque" x = "0" y = "5" width = "515"
                  height = "15" backcolor = "#C0C0C0"/>

               <box leftPadding = "10">
                  <bottomPen lineWidth = "1.0"/>
               </box>
               <textElement/>

               <textFieldExpression class = "java.lang.String">
                  <![CDATA["  " + String.valueOf($V{CountryNumber}) + ". "
                  + String.valueOf($F{country})]]>
               </textFieldExpression>

               <anchorNameExpression>
                  <![CDATA[String.valueOf($F{country})]]>
               </anchorNameExpression>
            </textField>

         </band>
      </groupHeader>

      <groupFooter>
         <band height = "20">

            <staticText>
               <reportElement x = "400" y = "1" width = "60" height = "15"/>
               <textElement textAlignment = "Right"/>
               <text><![CDATA[Count :]]></text>
            </staticText>

            <textField>
               <reportElement x = "460" y = "1" width = "30" height = "15"/>
               <textElement textAlignment = "Right"/>

               <textFieldExpression class = "java.lang.Integer">
                  <![CDATA[$V{CountryGroup_COUNT}]]>
               </textFieldExpression>
            </textField>

         </band>
      </groupFooter>

   </group>

   <title>
      <band height = "70">

         <line>
            <reportElement x = "0" y = "0" width = "515" height = "1"/>
         </line>

         <textField isBlankWhenNull = "true" bookmarkLevel = "1">
            <reportElement x = "0" y = "10" width = "515" height = "30"/>

            <textElement textAlignment = "Center">
               <font size = "22"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{ReportTitle}]]>
            </textFieldExpression>

            <anchorNameExpression>
               <![CDATA["Title"]]>
            </anchorNameExpression>
         </textField>

         <textField isBlankWhenNull = "true">
            <reportElement  x = "0" y = "40" width = "515" height = "20"/>

            <textElement textAlignment = "Center">
               <font size = "10"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{Author}]]>
            </textFieldExpression>
         </textField>

      </band>
   </title>

   <columnHeader>
      <band height = "23">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "3" width = "535" height = "15"
               backcolor = "#70A9A9" />

            <box>
               <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" />
            </box>

            <textElement />
               <text><![CDATA[]]>
            </text>
         </staticText>

         <staticText>
            <reportElement x = "414" y = "3" width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>

            <text><![CDATA[Country]]></text>
         </staticText>

         <staticText>
            <reportElement x = "0" y = "3" width = "136" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>

            <text><![CDATA[Name]]></text>
         </staticText>

      </band>
   </columnHeader>

   <detail>
      <band height = "16">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "0" width = "535" height = "14"
               backcolor = "#E5ECF9" />

            <box>
               <bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" />
            </box>

            <textElement />

            <text>
               <![CDATA[]]>
            </text>
         </staticText>

         <textField>
            <reportElement x = "414" y = "0" width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font size = "9" />
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{country}]]>
            </textFieldExpression>
         </textField>

         <textField>
            <reportElement x = "0" y = "0" width = "136" height = "15" />
            <textElement textAlignment = "Center" verticalAlignment = "Middle" />

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{name}]]>
            </textFieldExpression>
         </textField>

      </band>
   </detail>

</jasperReport>

用于填充报告的 Java 代码保持不变。文件 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java 的内容如下 -

The java codes for report filling remains unchanged. The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java are as given below −

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class JasperReportFill {
   @SuppressWarnings("unchecked")
   public static void main(String[] args) {
      String sourceFileName =
      "C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper";

      DataBeanList DataBeanList = new DataBeanList();
      ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();

      JRBeanCollectionDataSource beanColDataSource =
      new JRBeanCollectionDataSource(dataList);

      Map parameters = new HashMap();
      /**
       * Passing ReportTitle and Author as parameters
       */
      parameters.put("ReportTitle", "List of Contacts");
      parameters.put("Author", "Prepared By Manisha");

      try {
         JasperFillManager.fillReportToFile(
         sourceFileName, parameters, beanColDataSource);
      } catch (JRException e) {
         e.printStackTrace();
      }
   }
}

POJO 文件 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java 的内容如下:

The contents of the POJO file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java are as below −

package com.tutorialspoint;

public class DataBean {
   private String name;
   private String country;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getCountry() {
      return country;
   }

   public void setCountry(String country) {
      this.country = country;
   }
}

C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java 文件的内容如下 −

The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java are as given below −

package com.tutorialspoint;

import java.util.ArrayList;

public class DataBeanList {
   public ArrayList<DataBean> getDataBeanList() {
      ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();

      dataBeanList.add(produce("Manisha", "India"));
      dataBeanList.add(produce("Dennis Ritchie", "USA"));
      dataBeanList.add(produce("V.Anand", "India"));
      dataBeanList.add(produce("Shrinath", "California"));

      return dataBeanList;
   }

   /**
    * This method returns a DataBean object,
    * with name and country set in it.
    */
   private DataBean produce(String name, String country) {
      DataBean dataBean = new DataBean();
      dataBean.setName(name);
      dataBean.setCountry(country);

      return dataBean;
   }
}

Report Generation

我们将使用常规的 ANT 构建过程编译并执行以上文件。文件 build.xml(保存在 C:\tools\jasperreports-5.0.1\test 目录下)的内容如下。

We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are as below.

从第 Environment Setup 章中选取导入文件-baseBuild.xml,并将其放置在与 build.xml 相同的目录中。

The import file - baseBuild.xml is picked up from chapter Environment Setup and should be placed in the same directory as the build.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewFillReport" basedir = ".">
   <import file = "baseBuild.xml" />

   <target name = "viewFillReport" depends = "compile,compilereportdesing,run"
      description = "Launches the report viewer to preview
      the report stored in the .JRprint file.">

      <java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true">
         <arg value = "-F${file.name}.JRprint" />
         <classpath refid = "classpath" />
      </java>
   </target>

   <target name = "compilereportdesing" description = "Compiles the JXML file and
      produces the .jasper file.">

      <taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask">
         <classpath refid = "classpath" />
      </taskdef>

      <jrc destdir = ".">
         <src>
            <fileset dir = ".">
               <include name = "*.jrxml" />
            </fileset>
         </src>
         <classpath refid = "classpath" />
      </jrc>

   </target>

</project>

接下来,让我们打开命令行窗口并进入放置 build.xml 的目录。最后,执行命令 ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport 是默认目标),如下所示 −

Next, let’s open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as −

C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml

clean-sample:
   [delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint

compile:
   [mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes
   [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28: warning:
   'includeantruntime' was not set, defaulting to build.sysclasspath=last;
   set to false for repeatable builds
   [javac] Compiling 7 source files to C:\tools\jasperreports-5.0.1\test\classes

compilereportdesing:
   [jrc] Compiling 1 report design files.
   [jrc] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
   [jrc] log4j:WARN Please initialize the log4j system properly.
   [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig
   for more info.
   [jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK.

run:
   [echo] Runnin class : com.tutorialspoint.JasperReportFill
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

viewFillReport:
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

BUILD SUCCESSFUL
Total time: 18 seconds

以上编译的结果是在屏幕下方打开一个 JasperViewer 窗口−

As a result of above compilation, a JasperViewer window opens up as in the screen below −

report groups example

在此,我们看到每个国家分组,每个国家的出现次数统计显示在每个组的页脚中。

Here, we see that the each country is grouped and the count of occurrence of each country is displayed at the footer of each group.

Report Fonts

报表含文本元素,而这些元素各自可具有其单独的字体设定,可使用 <textElement> 标签内的 <*font*> 标签来指定这些设定,报表能够定义许多字体,一旦定义后,它们可作为整个报表其他字体定义的默认字体或基本字体设定来使用。

A report contains text elements and each of these can have its own font settings. These settings can be specified using the <*font*> tag available in the <textElement> tag. A report can define a number of fonts. Once defined, they can be used as default or base font settings for other font definitions throughout the entire report.

Report Fonts

报表字体是字体设定的集合,在报表级别声明,在设置文本元素的字体属性时,报表字体可以在整个报表模板中重复使用。

A report font is a collection of font settings, declared at the report level. A report font can be reused throughout the entire report template when setting the font properties of text elements.

报表字体现已被弃用,请勿使用在文档自身中声明的 <reportFont/> 元素,而应改用 <style/> 元素。

Report fonts are now deprecated. Do not use <reportFont/> elements declared within the document itself. Use the <style/> element instead.

Font Attributes

下表概述了 <*font*> 元素的主要属性−

Table below summarizes the main attributes of the <*font*> element −

S.NO

Attribute and Description

1

fontName The font name, which can be the name of a physical font, a logical one, or the name of a font family from the registered JasperReports font extensions.

2

size The size of the font measured in points. It defaults to 10.

3

isBold The flag specifying if a bold font is required. It defaults to false.

4

isItalic The flag specifying if an italic font is required. It defaults to false.

5

isUnderline The flag specifying if the underline text decoration is required. It defaults to false.

6

isStrikeThrough The flag specifying if the strikethrough text decoration is required. It defaults to false.

7

pdfFontName The name of an equivalent PDF font required by the iText library when exporting documents to PDF format.

8

pdfEncoding The equivalent PDF character encoding, also required by the iText library.

9

isPdfEmbedded The flag that specifies whether the font should be embedded into the document itself. It defaults to false. If set to true, helps view the PDF document without any problem.

Font Types

在 JasperReports 中,字体可分类为:

In JasperReports fonts can be categorized as −

  1. Logical Fonts − Five font types, which have been recognized by the Java platform since version 1.0, are called logical fonts. These are − Serif, SansSerif, Monospaced, Dialog, and DialogInput. These logical fonts are not actual font libraries that are installed anywhere on the system. They are merely font type names recognized by the Java runtime. These must be mapped to some physical font that is installed on the system.

  2. Physical Fonts − These fonts are the actual font libraries consisting of, for example, TrueType or PostScript Type 1 fonts. The physical fonts may be Arial, Time, Helvetica, Courier, or any number of other fonts, including international fonts.

  3. Font Extensions − The JasperReports library can make use of fonts registered on-the-fly at runtime, through its built-in support for font extensions. A list of font families can be made available to the JasperReports using font extension. These are made out of similarly looking font faces and supporting specific locales.

如上表所述,我们需要在 fontName 属性中指定物理字体的名称、逻辑字体的名称或注册的 JasperReports 字体扩展中字体系列的名称。

As described in the table above we need to specify in the attribute fontName the name of a physical font, the name of a logical font, or the name of a font family from the registered JasperReports font extensions.

PDF Font Name

当导出报表为 PDF(便携式文档格式)时,JasperReports 库使用 iText 库。可在各种平台上查看 PDF 文件,并且始终外观相同。这部分是因为在此格式中,有一种处理字体的特殊方式。向 PDF 导出时,fontName 属性没有任何作用。存在 pdfFontName 属性,我们需要在此属性中指定字体设置。

JasperReports library uses the iText library, when exporting reports to PDF(Portable Document Format). PDF files can be viewed on various platforms and will always look the same. This is partially because in this format, there is a special way of dealing with fonts. fontName attribute is of no use when exporting to PDF. Attribute pdfFontName exist where we need to specify the font settings.

iText 库知道如何处理内置字体和 TTF 文件,并且识别以下内置字体名称:

The iText library knows how to deal with built-in fonts and TTF files and recognizes the following built-in font names −

  1. Courier

  2. Courier-Bold

  3. Courier-BoldOblique

  4. Courier-Oblique

  5. Helvetica

  6. Helvetica-Bold

  7. Helvetica-BoldOblique

  8. Helvetica-Oblique

  9. Symbol

  10. Times-Roman

  11. Times-Bold

  12. Times-BoldItalic

  13. Times-Italic

  14. ZapfDingbats

根据 iText 库的先决条件,要使用字体,我们需要将以下内容之一指定为字体名称:

As per iText library pre-requisite, to work with fonts, we need to specify one of the following as the font name −

  1. A built-in font name from the above list.

  2. The name of a TTF (True Type Font) file, which it can locate on disk.

  3. The real name of the font, provided that the TTF file containing the font has been previously registered with iText or that an alias was defined when the font was registered.

基于上述先决条件,pdfFontName 属性可包含以下值之一:

Based on the above pre-requisites, the pdfFontName attribute can contain one of the following values −

  1. The name of a built-in PDF font from the above list.

  2. The name of a TTF file that can be located on disk at runtime when exporting to PDF.

  3. The real name of a registered font.

  4. The suffix of the key (the part after net.sf.jasperreports.export.pdf.font) for a font registered with iText as a font file.

Default Fonts and Inheritance

每个文本元素从其父元素继承字体和样式属性,而其父元素反过来又从其父元素继承这些属性。如果未为元素定义样式和/或字体,那么将在 <jasperReport/> 根元素中声明的默认样式(和/或字体,但现在这不赞扬)被应用。

Each text element inherits font and style attributes from its parent element, which in turn inherits these attributes from its parent. If no styles and/or fonts are defined for elements, the default style (and/or font - but this is now deprecated) declared in the <jasperReport/> root element will be applied.

在 JasperReports 中定义默认样式或字体不是强制性的。如果没有为给定元素定义字体,引擎会查找继承的字体属性,或者如果没有通过这种方式找到属性,则会在 /src/default.jasperreports.properties 文件中查找 net.sf.jasperreports.default.font.name 属性。其值定义了在未为文本元素显式定义字体属性或从其父元素继承字体属性时要使用的字体系列名称。

Defining default styles or fonts in JasperReports is not mandatory. If no font is defined for a given element, the engine looks either for the inherited font attributes, or, if no attributes are found on this way, it looks for the net.sf.jasperreports.default.font.name property in the /src/default.jasperreports.properties file. Its value defines the name of the font family to be used when font properties are not explicitly defined for a text element or inherited from its parent.

在 /src/default.jasperreports.properties 文件中定义的主默认字体属性及其值在下表中 -

The main default font properties and their values defined in the /src/default.jasperreports.properties file are in the table below −

Property

Description

net.sf.jasperreports.default.font.name=SansSerif

The default font name.

net.sf.jasperreports.default.font.size=10

The default font size.

net.sf.jasperreports.default.pdf.font.name=Helvetica

The default PDF font.

net.sf.jasperreports.default.pdf.encoding=Cp1252

The default PDF character encoding.

net.sf.jasperreports.default.pdf.embedded=false

By default PDF fonts are not embedded.

Example

为了演示如何使用字体和字体属性以获得特定文本外观,我们编写新的报表模板 (jasper_report_template.jrxml)。JRXML 的内容如下。将其保存到 C:\tools\jasperreports-5.0.1\test 目录中。在这里,我们在报表的标题中以各种字体格式显示文本。

To demonstrate using fonts and font attributes in order to get a particular text appearance, let’s write new report template (jasper_report_template.jrxml). The contents of the JRXML are as below. Save it to C:\tools\jasperreports-5.0.1\test directory. Here, we will display a text in the title of the report in various font formats.

<?xml version = "1.0" encoding = "UTF-8"?>

<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
   http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
   name = "jasper_report_template" pageWidth = "595" pageHeight = "842"
   columnWidth = "555" leftMargin = "20" rightMargin = "20" topMargin = "30"
   bottomMargin = "30">

   <title>
      <band height = "682">

      <staticText>
         <reportElement x = "0" y = "50" width = "150" height = "40"/>
         <textElement/>

         <text>
            <![CDATA[Welcome to TutorialsPoint!]]>
         </text>
      </staticText>

      <staticText>
         <reportElement x = "160" y = "50" width = "390" height = "40"/>
         <textElement/>

         <text>
           <![CDATA[<staticText>
           <reportElement x = "0" y = "50" width = "150" height = "40"/>
           <text>Welcome to TutorialsPoint!</text></staticText>]]>
         </text>
      </staticText>

      <staticText>
         <reportElement x = "0" y = "100" width = "150" height = "40"/>

         <textElement>
            <font size = "12"/>
         </textElement>

         <text><![CDATA[Welcome to TutorialsPoint!]]></text>
      </staticText>

      <staticText>
         <reportElement x = "160" y = "100" width = "390" height = "40"/>
         <textElement/>

         <text>
            <![CDATA[<staticText>
            <reportElement x = "0" y = "100" width = "150" height = "40"/>

            <textElement>
               <font size = "14"/>
            </textElement>

            <text> Welcome to TutorialsPoint!</text></staticText>]]>
         </text>
      </staticText>

      <staticText>
         <reportElement x = "0" y = "150" width = "150" height = "40"/>

         <textElement>
            <font fontName = "DejaVu Serif" size = "12" isBold = "false"/>
         </textElement>

         <text><![CDATA[Welcome to TutorialsPoint!]]></text>
      </staticText>

      <staticText>
         <reportElement x = "160" y = "150" width = "390" height = "40"/>
         <textElement/>

         <text>
            <![CDATA[<staticText>
            <reportElement x = "0" y = "250" width = "150" height = "40"/>

            <textElement>
               <font fontName = "DejaVu Serif" size = "12" isBold = "false"/>
            </textElement>

            <text>Welcome to TutorialsPoint!</text></staticText>]]>
         </text>
      </staticText>

      <staticText>
         <reportElement x = "0" y = "200" width = "150" height = "40"/>

         <textElement>
            <font fontName = "DejaVu Serif" size = "12" isBold = "true"/>
         </textElement>

         <text><![CDATA[Welcome to TutorialsPoint!]]></text>
      </staticText>

      <staticText>
         <reportElement x = "160" y = "200" width = "390" height = "40"/>
         <textElement/>

         <text>
            <![CDATA[<staticText>
            <reportElement x = "0" y = "300" width = "150" height = "40"/>

            <textElement>
               <font fontName = "DejaVu Serif" size = "12" isBold = "true"/>
            </textElement>

            <text>Welcome to TutorialsPoint!</text></staticText>]]>
         </text>
      </staticText>

      <staticText>
         <reportElement x = "0" y = "250" width = "150" height = "40"/>

         <textElement>
            <font fontName = "Monospaced" size = "12" isItalic = "true"
               isUnderline = "true" pdfFontName = "Courier-Oblique"/>
         </textElement>

         <text><![CDATA[Welcome to TutorialsPoint!]]></text>
      </staticText>

      <staticText>
         <reportElement x = "160" y = "250" width = "390" height = "40"/>
         <textElement/>

         <text>
            <![CDATA[<staticText>
            <reportElement x = "0" y = "350" width = "150" height = "40"/>

            <textElement>
               <font fontName = "Monospaced" size = "12" isItalic = "true"
                  isUnderline = "true" pdfFontName = "Courier-Oblique"/>
            </textElement>

            <text>Welcome to TutorialsPoint!</text></staticText>]]>
         </text>
      </staticText>

      <staticText>
         <reportElement x = "0" y = "300" width = "150" height = "40"/>

         <textElement>
            <font fontName = "Monospaced" size = "12" isBold = "true"
               isStrikeThrough = "true" pdfFontName = "Courier-Bold"/>
         </textElement>
         <text><![CDATA[Welcome to TutorialsPoint!]]></text>
      </staticText>

      <staticText>
         <reportElement x = "160" y = "300" width = "390" height = "40"/>
         <textElement/>

         <text>
            <![CDATA[<staticText>
            <reportElement x = "0" y = "400" width = "150" height = "40"/>

            <textElement>
               <font fontName = "Monospaced" size = "12" isBold = "true"
                  isStrikeThrough = "true" pdfFontName = "Courier-Bold"/>
            </textElement>

            <text>Welcome to TutorialsPoint!</text></staticText>]]>
         </text>
      </staticText>

      <staticText>
         <reportElement x = "0" y = "350" width = "150" height = "40"
            forecolor = "#FF0000"/>

         <textElement>
            <font size = "14"/>
         </textElement>

         <text><![CDATA[Welcome to TutorialsPoint!]]></text>
      </staticText>

      <staticText>
         <reportElement x = "160" y = "350" width = "390" height = "40"/>
         <textElement/>

         <text>
            <![CDATA[<staticText>
            <reportElement x = "0" y = "450" width = "150" height = "40"
               forecolor = "red"/>

            <textElement><font size = "14"/></textElement>
            <text>Welcome to TutorialsPoint!</text></staticText>]]>
         </text>
      </staticText>

      <staticText>
         <reportElement x = "0" y = "400" width = "150" height = "40" mode = "Opaque"
            forecolor = "#00FF00" backcolor = "#FFFF00"/>

         <textElement>
            <font fontName = "Serif" size = "12" isBold = "true"
               pdfFontName = "Times-Bold"/>
         </textElement>

         <text><![CDATA[Welcome to TutorialsPoint!]]></text>
      </staticText>

      <staticText>
         <reportElement x = "160" y = "400" width = "390" height = "40"/>
         <textElement/>

         <text>
            <![CDATA[<staticText>
            <reportElement x = "0" y = "500" width = "150" height = "40"
               forecolor = "green" backcolor = "#FFFF00" mode = "Opaque"/>

            <textElement>
               <font fontName = "Serif" size = "12" isBold = "true"
                  pdfFontName = "Times-Bold"/>
            </textElement>

            <text>Welcome to TutorialsPoint!</text></staticText>]]>
         </text>
      </staticText>

      <staticText>
         <reportElement x = "0" y = "450" width = "150" height = "40" mode = "Opaque"
            forecolor = "#0000FF" backcolor = "#FFDD99"/>

         <textElement textAlignment = "Center" verticalAlignment = "Middle">
            <font fontName = "SansSerif" size = "12" isBold = "false"
            isItalic = "true" pdfFontName = "Sans.Slanted" isPdfEmbedded = "true"/>
         </textElement>

         <text><![CDATA[Welcome to TutorialsPoint!]]></text>
      </staticText>

      <staticText>
         <reportElement x = "160" y = "450" width = "390" height = "40"/>
         <textElement/>

         <text>
            <![CDATA[<staticText>
            <reportElement x = "0" y = "550" width = "150" height = "90"
               forecolor = "blue" backcolor = "#FFDD99" mode = "Opaque"/>

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font fontName = "SansSerif" size = "12" isBold = "false"
                  pdfFontName = "Sans.Slanted" isPdfEmbedded = "true"/>
            </textElement>

            <text>Welcome to TutorialsPoint!</text></staticText>]]>
         </text>
      </staticText>

      <staticText>
         <reportElement mode = "Opaque" x = "0" y = "500" width = "150" height = "40"
            forecolor = "#FF0000" backcolor = "#99DDFF"/>

         <textElement textAlignment = "Right" verticalAlignment = "Bottom">
            <font fontName = "SansSerif" size = "12" isBold = "true"
               pdfFontName = "DejaVu Sans Bold" isPdfEmbedded = "true"/>
         </textElement>

         <text><![CDATA[Welcome to TutorialsPoint!]]></text>
      </staticText>

      <staticText>
         <reportElement x = "160" y = "500" width = "390" height = "40"/>
         <textElement/>

         <text>
            <![CDATA[<staticText>
            <reportElement x = "0" y = "650" width = "150" height = "90"    forecolor = "red"
               backcolor = "#99DDFF" mode = "Opaque"/>

            <textElement textAlignment = "Right" verticalAlignment = "Bottom">
               <font fontName = "SansSerif" size = "12" isBold = "true"
                  pdfFontName = "DejaVu Sans Bold" isPdfEmbedded = "true"/>
            </textElement>

            <text>Welcome to TutorialsPoint!</text></staticText>]]>
         </text>

      </staticText>

   </band>
</title>

</jasperReport>

填充并生成报表的 java 代码如下所示。让我们将此文件 JasperFontsReportFill.java 保存到 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint 目录中。

The java code to fill and generate the report is as given below. Let’s save this file JasperFontsReportFill.java to C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint directory.

package com.tutorialspoint;

import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;

public class JasperFontsReportFill {
   public static void main(String[] args) {
      String sourceFileName = "C://tools/jasperreports-5.0.1/test/" +
         "jasper_report_template.jasper";

      try {
         JasperFillManager.fillReportToFile(sourceFileName, null,
            new JREmptyDataSource());
      } catch (JRException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }

   }
}

在这里,我们在填充报表时使用 JREmptyDataSource 实例来模拟一个包含一条记录的数据源,但所有字段都为 null。

Here, we use an instance of JREmptyDataSource when filling reports to simulate a data source with one record in it, but with all the fields being null.

Report Generation

我们将使用常规 ANT 构建流程编译并执行上述文件。build.xml 文件(保存在 C:\tools\jasperreports-5.0.1\test 目录下)的内容如下。

We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are as given below.

导入文件 - baseBuild.xml 从第 Environment Setup 章节中选取,且应放置在与 build.xml 相同的目录中。

The import file - baseBuild.xml is picked from chapter Environment Setup and should be placed in the same directory as the build.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewFillReport" basedir = ".">
   <import file = "baseBuild.xml" />

   <target name = "viewFillReport" depends = "compile,compilereportdesing,run"
      description = "Launches the report viewer to preview the report
      stored in the .JRprint file.">

      <java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true">
         <arg value = "-F${file.name}.JRprint" />
         <classpath refid = "classpath" />
      </java>

   </target>

   <target name = "compilereportdesing" description = "Compiles the JXML file and
      produces the .jasper file.">

      <taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask">
         <classpath refid = "classpath" />
      </taskdef>

      <jrc destdir = ".">
         <src>
            <fileset dir = ".">
               <include name = "*.jrxml" />
            </fileset>
         </src>
         <classpath refid = "classpath" />
      </jrc>

   </target>

</project>

接下来,让我们打开命令行窗口并转到放置 build.xml 的目录。最后,执行命令 ant -Dmain-class=com.tutorialspoint.JasperFontsReportFill (viewFullReport 为默认目标),如下所示 -

Next, let’s open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperFontsReportFill (viewFullReport is the default target) as −

C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperFontsReportFill
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml

clean-sample:
   [delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint

compile:
   [mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes
   [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28:
   warning: 'includeantruntime' was not set, defaulting to build.
   [javac] Compiling 5 source files to C:\tools\jasperreports-5.0.1\test\classes

compilereportdesing:
   [jrc] Compiling 1 report design files.
   [jrc] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
   [jrc] log4j:WARN Please initialize the log4j system properly.
   [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
   [jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK.

run:
   [echo] Runnin class : com.tutorialspoint.JasperFontsReportFill
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

viewFillReport:
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

BUILD SUCCESSFUL
Total time: 45 minutes 3 seconds

作为上述编译的结果,一个 JasperViewer 窗口会打开,如以下给出的屏幕截图所示 -

As a result of above compilation, a JasperViewer window opens up as shown in the screen given below −

report fonts example

在这里,我们可以看到文本“欢迎来到 TutorialsPoint”以不同的字体格式显示。

Here, we can see that the text "Welcome to TutorialsPoint" is displayed in different font formats.

Unicode Support

在 JasperReports 中,处理文本需要一些专门的工具来处理字符表示和文本格式化属性。任何文本都可以看作具有特定表示结构的字符序列。文本外观包括布局(和段落)和字体设置。但在大多数情况下,文本布局保持不变,在不同区域设置中运行报表时,字体设置可能会发生变化。

In JasperReports, working with texts needs some dedicated tools to process both the character representations and the text formatting properties. Any text can be considered as a character sequence with a particular representation structure. The text appearance consists in both layout (and paragraph) and font settings. But while in most cases, the text layout remains invariant, font settings may change when running the report in different Locales.

我们知道,不同的语言需要不同的字符集来表示特定字符。因此,处理文本意味着处理字体。但是,有关如何在 JasperReports 中使用字体的详细讨论可在章节 Report Fonts 中找到。

We know that different languages need different character sets with respect to specific characters representation. Therefore, working with texts means working with fonts. However, a detailed discussion about how to use fonts in JasperReports is available in the chapter Report Fonts.

有关给定报表中文本内容的一项主要功能是使其国际化的可能性。这意味着,我们可以在不同的本地化环境中运行报表,使用不同的语言和其他本地化设置,而无需进行任何硬编码修改。当报表打算国际化时,字符编码是一项重要功能。

One of the main features concerning the text content in a given report is the possibility to internationalize it. It means, we can run the report in different localized environments, using different languages and other localization settings without any hardcoded modification. Character encoding is an important feature when a report is intended to be internationalized.

Character Encoding

字符是传达有意义信息的最小书写单位。它是一个抽象概念,字符没有视觉外观。“大写拉丁语 A”不同于“小写拉丁语 a”以及“大写西里尔语 A”和“大写希腊 Alpha”。

A character is the smallest unit of writing conveying a meaningful information. It is an abstract concept, a character does not have a visual appearance. "Uppercase Latin A" is a different character from "lowercase Latin a" and from "uppercase Cyrillic A" and "uppercase Greek Alpha".

字符的可视表示称为 glyph 。某一组字形称为 font 。“大写拉丁语 A”、“大写西里尔语 A”和“大写希腊 Alpha”可能具有相同的字形,但它们是不同的字符。同时,在 Times New Roman、Gill Sans 和 Poetica Chancery Italic 中,“大写拉丁语 A”的字形看起来可能非常不同,但它们仍然表示相同的字符。

A visual representation of a character is known as a glyph. A certain set of glyphs is called a font. "Uppercase Latin A", "uppercase Cyrillic A" and "uppercase Greek Alpha" may have identical glyphs, but they are different characters. At the same time, the glyphs for "uppercase Latin A" can look very different in Times New Roman, Gill Sans and Poetica chancery italic, but they still represent the same character.

可用字符集称为字符库。库中给定字符的位置(索引)称为其代码位置或代码点。在给定库中用数字表示代码点的方法称为 character encoding

The set of available characters is called a character repertoire. The location (index) of a given character within a repertoire is known as its code position, or code point. The method of numerically representing a code point within a given repertoire is called the character encoding.

编码通常用八位字节表示。八位字节是一组八个二进制数字,即八个一和零。一个八位字节可以用 0 到 255 或 0x00 到 0xFF(使用十六进制符号)之间的数值范围表示。

Encodings are normally expressed in terms of octets. An octet is a group of eight binary digits, i.e., eight ones and zeros. An octet can express a numeric range between 0 and 255, or between 0x00 and 0xFF, to use hexadecimal notation.

Unicode

Unicode 是一种字符库,其中包含世界上大多数语言中使用的字符。它可以容纳数百万个字符,并且已经包含数十万个字符。Unicode 被划分为 64K 字符的“平面”。在大多数情况下,只使用一个平面,称为基本多语言平面或 BMP。

A Unicode is a character repertoire that contains most of the characters used in the languages of the world. It can accommodate millions of characters, and already contains hundreds of thousands. Unicode is divided into "planes" of 64K characters. The only one used in most circumstances is the first plane, known as the basic multilingual plane, or BMP.

UTF-8 是推荐的编码。它使用可变数量的八位字节来表示不同的字符。

UTF-8 is the recommended encoding. It uses a variable number of octets to represent different characters.

在 JRXML 文件中,对编码属性在标题中进行了指定。在报告编译过程中,它用于对 XML 内容进行解码。例如,如果报告仅包含法语单词和 ç、é、â 等字符,那么 ISO-8859-1(又名 Latin-1)编码就足够了。

In a JRXML file, the encoding attribute is specified in the header. It is used at report compilation time to decode the XML content. For instance, if the report contains French words only and characters such as ç, é, â, then the ISO-8859-1 (a.k.a Latin-1) encoding is sufficient −

<?xml version = "1.0" encoding = "ISO-8859-1"?>

如上所见,理想情况下,我们可以选择适合最小字符集的编码,它可以正确显示文档中的所有字符。但在处理多语言文档(即包含拼写了多种语言的单词的文档)时,应选择适合最小字符集的编码,即使它们属于不同的语言,也能正确显示文档中的所有字符。能够处理多语言文档的字符编码之一是 UTF-8 ,它用作 JasperReports 的默认编码值。

As seen above, ideally we can choose the encoding fit to the minimal character set, which can correctly represent all the characters in the document. But in case of Multilanguage documents (i.e. documents containing words spelled in several languages), one should choose the encoding adapted to the minimal character set, able to correctly represent all the characters in the document, even if they belong to different languages. One of the character encodings able to handle multilingual documents is the UTF-8, used as default encoding value by JasperReports.

在国际化过程中,文本通常保存在资源包文件中,而不是保存在文档中。因此,有时 JRXML 本身看起来完全兼容 ASCII,但运行时生成的报告确实包含无法通过 ASCII 读取的文本。因此,对于特定类型的文档导出格式(如 CSV、HTML、XHTML、XML 和文本),人们还必须了解生成文档的编码。不同的语言由不同的字符编码提供支持。因此,每次我们都需要在本地化环境中运行报告。此外,我们还必须知道,哪个是最适合生成文档语言的字符编码。在这种情况下,JRXML 文件中自行定义的编码属性可能不再有用。

The texts are usually kept in resource bundle files rather than within the document during internationalization. So, there are cases where the JRXML itself looks completely ASCII-compatible, but generated reports at runtime do contain texts unreadable with ASCII. As a result, for a certain type of document export formats (such as CSV, HTML, XHTML, XML, and text) one has to know the encoding for the generated document too. Different languages are supported by different character encodings. So each time, we need to run a report in a localized environment. Further, we have to know, which is the most appropriate character encoding for the generated document language. In this case, the encoding property defined in the JRXML file itself might be no more useful.

要解决此类问题,我们可以使用一个称为 net.sf.jasperreports.export.character.encoding 的导出自定义属性。此导出自定义属性默认为 UTF-8,并且存在于 JasperReports 中。

To solve this kind of issues we can use an export customer property known as net.sf.jasperreports.export.character.encoding. This export custom property is default to UTF-8 and is present in JasperReports.

此默认值在 default.jasperreports.properties 文件中设置。对于导出时的更具体选项, CHARACTER_ENCODING 导出参数也可用。

This default value is set in the default.jasperreports.properties file. For more specific options at export time, the CHARACTER_ENCODING export parameter is also available.

Example

为了演示在 Jasperreports 中使用 unicode 支持,我们新建一个报告模板(jasper_report_template.jrxml)。 Save it to C:\tools\jasperreports-5.0.1\test 目录。在这里,我们将使用 Unicode 字符(\uXXXX)显示不同语言的文本。使用 UTF-8 编码的任何字符都可以仅使用其 4 位十六进制代码进行显示。例如,希腊字母 Γ 可以写成 \u0393。当遇到此类表示法时,引擎会调用字符集中适当的字符表示法,并且只会打印出该特定字符。JRXML 的内容如下所示:

To demonstrate using unicode support in Jasperreports, let’s write new report template (jasper_report_template.jrxml). Save it to C:\tools\jasperreports-5.0.1\test directory. Here, we will display a text in different languages using the Unicode characters (\uXXXX). Any character encoded with UTF-8 can be represented using only its 4-digits hexadecimal code. For instance, the Greek letter Γ can be written as \u0393. When such a notation is encountered, the engine calls for the appropriate character representation in the character set, and only that particular character will be printed out. The contents of the JRXML are as below −

<?xml version = "1.0" encoding = "UTF-8"?>

<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
   http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
   name = "jasper_report_template" language = "groovy" pageWidth = "595"
   pageHeight = "842" columnWidth = "555" leftMargin = "20" rightMargin = "20"
   topMargin = "20" bottomMargin = "20">

   <parameter name = "GreekText" class = "java.lang.String" isForPrompting = "false">
      <defaultValueExpression><![CDATA["\u0394\u03B5\u03BD "+
         "\u03BA\u03B1\u03C4\u03B1\u03BB\u03B1\u03B2\u03B1\u03AF"+
         "\u03BD\u03C9 \u0395\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC"]]>
      </defaultValueExpression>
   </parameter>

   <parameter name = "CyrillicText" class = "java.lang.String" isForPrompting = "false">
      <defaultValueExpression><![CDATA["\u042F \u043D\u0435 "+
         "\u043C\u043E\u0433\u0443 \u043F\u043E\u043D\u044F\u0442\u044C "+
         "\u0433\u0440\u0435\u0447\u0435\u0441\u043A\u0438\u0439"]]>
      </defaultValueExpression>
   </parameter>

   <parameter name = "ArabicText" class = "java.lang.String" isForPrompting = "false">
      <defaultValueExpression><![CDATA["\u0627\u0646\u0646\u0649 \u0644\u0627 "+
         "\u0627\u0641\u0647\u0645 \u0627\u0644\u0644\u063A\u0629 "+
         "\u0627\u0644\u0639\u0631\u0628\u064A\u0629"]]>
      </defaultValueExpression>
   </parameter>

   <parameter name = "HebrewText" class = "java.lang.String" isForPrompting = "false">
      <defaultValueExpression><![CDATA["\u05D0\u05E0\u05D9 \u05DC\u05D0 "+
         "\u05DE\u05D1\u05D9\u05DF \u05E2\u05D1\u05E8\u05D9\u05EA"]]>
      </defaultValueExpression>
   </parameter>

   <title>
      <band height = "782">

         <textField>
            <reportElement x = "0" y = "50" width = "200" height = "60"/>

            <textElement>
               <font fontName = "DejaVu Sans" size = "14"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{GreekText} + "\n" + $P{CyrillicText}]]>
            </textFieldExpression>
         </textField>

         <staticText>
            <reportElement x = "210" y = "50" width = "340" height = "60"/>
            <textElement/>

            <text>
               <![CDATA["GreekText and CyrillicText"]]>
            </text>
         </staticText>

         <textField>
            <reportElement x = "0" y = "120" width = "200" height = "60"/>

            <textElement>
               <font fontName = "DejaVu Sans" size = "14" isBold = "true"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{GreekText} + "\n" + $P{CyrillicText}]]>
            </textFieldExpression>

         </textField>

         <staticText>
            <reportElement x = "210" y = "120" width = "340" height = "60"/>
            <textElement/>
            <text><![CDATA["GreekText and CyrillicText"]]></text>
         </staticText>

         <textField>
            <reportElement x = "0" y = "190" width = "200" height = "60"/>

            <textElement>
               <font fontName = "DejaVu Sans" size = "14" isItalic = "true"
                  isUnderline = "true"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{GreekText} + "\n" + $P{CyrillicText}]]>
            </textFieldExpression>

         </textField>

         <staticText>
            <reportElement x = "210" y = "190" width = "340" height = "60"/>
            <textElement/>
            <text><![CDATA["GreekText and CyrillicText"]]></text>
         </staticText>

         <textField>
            <reportElement x = "0" y = "260" width = "200" height = "60"/>

            <textElement>
               <font fontName = "DejaVu Sans" size = "14" isBold = "true"
                  isItalic = "true" isUnderline = "true"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{GreekText} + "\n" + $P{CyrillicText}]]>
            </textFieldExpression>

         </textField>

         <staticText>
            <reportElement x = "210" y = "260" width = "340" height = "60"/>
            <textElement/>
            <text><![CDATA["GreekText and CyrillicText"]]></text>
         </staticText>

         <textField>
            <reportElement x = "0" y = "330" width = "200" height = "60"/>

            <textElement textAlignment = "Right">
               <font fontName="DejaVu Sans" size = "22"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{ArabicText}]]>
            </textFieldExpression>

         </textField>

         <textField>
            <reportElement x = "210" y = "330" width = "340" height = "60"/>

            <textElement textAlignment = "Right">
               <font fontName = "DejaVu Sans" size = "22"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{HebrewText}]]>
            </textFieldExpression>

         </textField>

      </band>
   </title>

</jasperReport>

在上述文件中,我们可以看到 UTF-8 编码的存在。本地化的 Unicode 文本片段也存储在文档参数中。

In the above file, we can see the presence of the UTF-8 encoding. Also the localized Unicode pieces of text are stored in document parameters.

用于填充和生成报告的 java 代码如下。我们将此文件保存在 JasperUnicodeReportFill.java 于 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint 目录中。

The java code to fill and generate the report is as below. Let’s save this file JasperUnicodeReportFill.java to C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint directory.

package com.tutorialspoint;

import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;

public class JasperUnicodeReportFill {
   public static void main(String[] args) {
      String sourceFileName ="C://tools/jasperreports-5.0.1/test/" +
         "jasper_report_template.jasper";

      try {
         JasperFillManager.fillReportToFile(sourceFileName, null,
            new JREmptyDataSource());
      } catch (JRException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }

   }
}

在此处,我们在使用 JREmptyDataSource 填充报告时模拟了一个数据源,其中只有一条记录,但该单条记录中的所有字段都为空。

Here we use an instance of JREmptyDataSource when filling reports to simulate a data source with one record in it, but with all the fields in this single record being null.

Report Generation

我们将使用常规的 ANT 构建过程编译并执行以上文件。文件 build.xml(保存在 C:\tools\jasperreports-5.0.1\test 目录下)的内容如下。

We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are as below.

导入文件 - baseBuild.xml 从第 Environment Setup 章节中选取,且应放置在与 build.xml 相同的目录中。

The import file - baseBuild.xml is picked from chapter Environment Setup and should be placed in the same directory as the build.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewFillReport" basedir = ".">
   <import file = "baseBuild.xml" />

   <target name = "viewFillReport" depends = "compile,compilereportdesing,run"
      description = "Launches the report viewer to preview the report
      stored in the .JRprint file.">

      <java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true">
         <arg value = "-F${file.name}.JRprint" />
         <classpath refid = "classpath" />
      </java>

   </target>

   <target name = "compilereportdesing" description = "Compiles the JXML file and
      produces the .jasper file.">

      <taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask">
         <classpath refid = "classpath" />
      </taskdef>

      <jrc destdir = ".">
         <src>
            <fileset dir = ".">
               <include name = "*.jrxml" />
            </fileset>
         </src>
         <classpath refid = "classpath" />
      </jrc>

   </target>

</project>

接下来,我们打开命令行窗口并转到放置 build.xml 的目录。最后,执行命令 ant -Dmain-class=com.tutorialspoint.JasperUnicodeReportFill (viewFullReport 是默认目标),如下所示:

Next, let’s open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperUnicodeReportFill (viewFullReport is the default target) as follows −

C:\tools\jasperreports-5.0.1\test>ant  -Dmain-class=com.tutorialspoint.JasperUnicodeReportFill
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml

clean-sample:
   [delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint

compile:
   [mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes
   [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28:
   warning: 'includeantruntime' was not set, defaulting t
   [javac] Compiling 1 source file to C:\tools\jasperreports-5.0.1\test\classes

compilereportdesing:
   [jrc] Compiling 1 report design files.
   [jrc] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
   [jrc] log4j:WARN Please initialize the log4j system properly.
   [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
   [jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK.

run:
   [echo] Runnin class : com.tutorialspoint.JasperUnicodeReportFill
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

viewFillReport:
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

BUILD SUCCESSFUL
Total time: 4 minutes 1 second

作为上述编译的结果,一个 JasperViewer 窗口会打开,如以下给出的屏幕截图所示 -

As a result of above compilation, a JasperViewer window opens up as shown in the screen given below −

report unicode example

在这里,我们可以看到显示的文本属于不同的语言。我们还可以看到,这些语言分组在同一页面上,而且还混入同一文本元素中。

Here, we can see that the text being displayed is in different languages. Also we see that the languages are grouped together on the same page and also mixed into the same text element.

Report Styles

JasperReports 提供了一项 <style> 功能,用于控制报告模板中的文本属性。此元素是在报告级别声明的样式设置的集合。诸如前景色、背景色、字体是否加粗、倾斜或正常、字体大小、字体边框以及许多其他属性都受 <style> 元素控制。样式可以扩展其他样式,并且还可以添加或覆盖父样式的属性。

JasperReports has a feature <style> which helps to control text properties in a report template. This element is a collection of style settings declared at the report level. Properties like foreground color, background color, whether the font is bold, italic, or normal, the font size, a border for the font, and many other attributes are controlled by <style> element. Styles can extend other styles, and add to, or override properties of the parent style as well.

Style Properties

<style> 元素包含许多属性。下表列出了一些最常用的属性:

A <style> element has many attributes. Some of the most commonly used are listed in the table given below −

S.NO

Attribute and Description

1

name Is mandatory. It must be unique because it references the corresponding report style throughout the report.

2

isDefault Indicates whether this style is the document’s default style.

3

style Is a reference to the parent style.

4

mode Specifies the element’s transparency. Possible values are Opaque and Transparent.

5

forecolor Is the foreground color of object.

6

backcolor Is the background color of object.

7

fill Determines the fill pattern used to fill the object. At the moment, the single value allowed is Solid.

6

radius Specifies the radius of the rectangle’s corner arc.

7

scaleImage Specifies scale for the images only. Possible values: Clip, FillFrame, RetainShape, RealHeight, and RealSize.

8

hAlign Specifies the horizontal alignment. Possible values: Left, Center, Right, and Justified.

9

vAlign Specifies the vertical alignment. Possible values: Top, Middle, and Bottom.

10

rotation Specifies the element’s rotation. Possible values: None, Left, Right, and UpsideDown.

11

lineSpacing Specifies the line spacing between lines of text. Possible values: Single, 1_1_2, Double.

12

markup Specifies the markup style for styled texts.

13

fontName Specifies the font name.

14

fontSize Specifies the font size.

15

isBold Indicates if the font style is bold.

16

isItalic Indicates if the font style is italic.

17

isUnderline Indicates if the font style is underline.

18

isStrikeThrough Indicates if the font style is strikethrough.

19

pdfFontName Specifies the related PDF font name.

20

pdfEncoding Specifies the character encoding for the PDF output format.

22

isPdfEmbedded Indicates if the PDF font is embedded.

23

pattern Specifies the format pattern for formatted texts.

24

isBlankWhenNull Indicates if an empty string (whitespace) should be shown if the expression evaluates to null.

Conditional Styles

在某些情况下,仅当满足特定条件时才应应用样式(例如,交替显示报表详细信息部分中相邻行的颜色)。这可以通过使用条件样式来实现。

In some situations, a style should be applied only when certain condition is met (for example, to alternate adjacent row colors in a report detail section). This can be achieved using conditional styles.

条件样式有两个元素−

A conditional style has two elements −

  1. a Boolean condition expression

  2. a style

样式仅在条件评估结果为真时使用。

The style is used only if the condition evaluates to true.

Applying Styles to Report Elements

任何类型的报表元素都可以使用 style 属性引用报表样式定义。因此,样式定义中所有适用于当前元素的样式属性都将被继承。要覆盖继承的值,可以使用在报表元素级别指定的样式属性。

Any type of report element can reference a report style definition using the style attribute. Hence, all the style properties declared by the style definition that are applicable to the current element will be inherited. To override the inherited values, style properties specified at the report element level can be used.

Style Templates

可以通过在公共位置定义样式来制作具有共同外观的一组报表。然后,报表模板可以引用此公共样式模板。样式模板是包含一个或多个样式定义的 XML 文件。惯例上样式模板文件使用 *.jrtx 扩展名,但这不是强制性的。

We can make a set of reports with a common look by defining the style at a common place. This common style template can then be referenced by the report templates. A style template is an XML file that contains one or more style definitions. Style template files used by convention the *.jrtx extension, but this is not mandatory.

样式模板包含以下元素 -

A style template contains following elements −

  1. <jasperTemplate> − This is the root element of a style template file.

  2. <template> − This element is used to include references to other template files. The contents of this element are interpreted as the location of the referred template file.

  3. <style> − This element is identical to the element with the same name from report design templates (JRXML files), with the exception that a style in a style template cannot contain conditional styles. This limitation is caused by the fact that conditional styles involve report expressions, and expressions can only be interpreted in the context of a single report definition.

对样式模板的引用作为 <template> 元素包含在 JRXML 报表中。样式模板在报表填充时加载,并在所有模板加载后解析样式名称引用。在加载样式模板和将样式名称解析为样式时,将创建样式模板的树/图,树的顶部是报表中定义的样式集。在此树上,样式名称引用将解析为深度优先遍历中与名称匹配的最后一个样式。

References to style templates are included in JRXML reports as <template> elements. The style templates are loaded at report fill time, and style name references are resolved once all the templates have been loaded. When loading style templates and resolving style names to styles, a tree/graph of style templates is created, the top of the tree being the set of styles defined in the report. On this tree, style name references are resolved to the last style that matches the name in a depth-first traversal.

Example

让我们尝试一下条件样式和样式模板。让我们将 <*style*> 元素 alternateStyle 添加到我们现有的报表模板(章节 Report Designs )。根据条件,偶数计算的字体颜色将变为蓝色。我们还包含了一个样式模板 "styles.jrtx" 。修改后的报表模板 (jasper_report_template.jrxml) 如下所示。将其保存到 C:\tools\jasperreports-5.0.1\test 目录 -

Let’s try out the conditional styles and style templates. Let’s add the <*style*> element alternateStyle to our existing report template (Chapter Report Designs). Based on the condition, font color changes to blue for even count. We have also included a style template "styles.jrtx". The revised report template (jasper_report_template.jrxml) is as follows. Save it to C:\tools\jasperreports-5.0.1\test directory −

<?xml version = "1.0"?>
<!DOCTYPE jasperReport PUBLIC
   "//JasperReports//DTD Report Design//EN"
   "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">

<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
   http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
   name = "jasper_report_template" pageWidth = "595"
   pageHeight = "842" columnWidth = "515"
   leftMargin = "40" rightMargin = "40" topMargin = "50" bottomMargin = "50">

   <template>"styles.jrtx"</template>

   <style name = "alternateStyle" fontName = "Arial" forecolor = "red">
      <conditionalStyle>
         <conditionExpression>
            <![CDATA[new Boolean($V{countNumber}.intValue() % 2 == 0)]]>
         </conditionExpression>

         <style forecolor = "blue" isBold = "true"/>
      </conditionalStyle>
   </style>

   <parameter name = "ReportTitle" class = "java.lang.String"/>
   <parameter name = "Author" class = "java.lang.String"/>

   <queryString>
      <![CDATA[]]>
   </queryString>

   <field name = "country" class = "java.lang.String">
      <fieldDescription><![CDATA[country]]></fieldDescription>
   </field>

   <field name = "name" class = "java.lang.String">
      <fieldDescription><![CDATA[name]]></fieldDescription>
   </field>

   <variable name = "countNumber" class = "java.lang.Integer" calculation = "Count">
      <variableExpression><![CDATA[Boolean.TRUE]]></variableExpression>
   </variable>

   <title>
      <band height = "70">

         <line>
            <reportElement x = "0" y = "0" width = "515" height = "1"/>
         </line>

         <textField isBlankWhenNull = "true" bookmarkLevel = "1">
            <reportElement x = "0" y = "10" width = "515" height = "30"/>

            <textElement textAlignment = "Center">
               <font size = "22"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{ReportTitle}]]>
            </textFieldExpression>

            <anchorNameExpression><![CDATA["Title"]]></anchorNameExpression>
         </textField>

         <textField isBlankWhenNull = "true">
            <reportElement  x = "0" y = "40" width = "515" height = "20"/>

            <textElement textAlignment = "Center">
               <font size = "10"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{Author}]]>
            </textFieldExpression>

         </textField>

      </band>
   </title>

   <columnHeader>
      <band height = "23">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "3"
               width = "535" height = "15" backcolor = "#70A9A9" />

            <box>
               <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" />
            </box>

            <textElement />

            <text>
               <![CDATA[]]>
            </text>

         </staticText>

         <staticText>
            <reportElement x = "414" y = "3" width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>

            <text><![CDATA[Country]]></text>
         </staticText>

         <staticText>
            <reportElement x = "0" y = "3" width = "136" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>

            <text><![CDATA[Name]]></text>
         </staticText>

      </band>
   </columnHeader>

   <detail>
      <band height = "16">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "0"
               width = "535" height = "14" backcolor = "#E5ECF9" />

            <box>
               <bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" />
            </box>

            <textElement />

            <text>
               <![CDATA[]]>
            </text>

         </staticText>

         <textField>
            <reportElement style = "alternateStyle" x = "414" y = "0"
               width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font size = "9" />
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{country}]]>
            </textFieldExpression>
         </textField>

         <textField>
            <reportElement x = "0" y = "0" width = "136" height = "15"
               style = "Strong"/>
            <textElement textAlignment = "Center" verticalAlignment = "Middle" />

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{name}]]>
            </textFieldExpression>
         </textField>

      </band>
   </detail>

</jasperReport>

样式模板 styles.jrtx 的内容如下。将其保存到 C:\tools\jasperreports-5.0.1\test 目录。

The contents of style template styles.jrtx are as follows. Save it to C:\tools\jasperreports-5.0.1\test directory.

<?xml version = "1.0"?>

<!DOCTYPE jasperTemplate PUBLIC "-//JasperReports//DTD Template//EN"
  "http://jasperreports.sourceforge.net/dtds/jaspertemplate.dtd">

<jasperTemplate>
   <style name = "Strong" isBold = "true" pdfFontName = "Helvetica-Bold"
      backcolor = "lightGray forecolor = "green"/>
</jasperTemplate>

报表填充的 java 代码保持不变。文件 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java 的内容如下 -

The java codes for report filling remain unchanged. The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java are as given below −

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class JasperReportFill {
   @SuppressWarnings("unchecked")
   public static void main(String[] args) {
      String sourceFileName =
         "C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper";

      DataBeanList DataBeanList = new DataBeanList();
      ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();

      JRBeanCollectionDataSource beanColDataSource = new
         JRBeanCollectionDataSource(dataList);

      Map parameters = new HashMap();
      /**
       * Passing ReportTitle and Author as parameters
       */
      parameters.put("ReportTitle", "List of Contacts");
      parameters.put("Author", "Prepared By Manisha");

      try {
         JasperFillManager.fillReportToFile(
         sourceFileName, parameters, beanColDataSource);
      } catch (JRException e) {
         e.printStackTrace();
      }
   }
}

POJO 文件 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java 的内容如下:

The contents of the POJO file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java are as below −

package com.tutorialspoint;

public class DataBean {
   private String name;
   private String country;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getCountry() {
      return country;
   }

   public void setCountry(String country) {
      this.country = country;
   }
}

文件 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java 的内容如下 -

The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java are as below −

package com.tutorialspoint;

import java.util.ArrayList;

public class DataBeanList {
   public ArrayList<DataBean> getDataBeanList() {
      ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();

      dataBeanList.add(produce("Manisha", "India"));
      dataBeanList.add(produce("Dennis Ritchie", "USA"));
      dataBeanList.add(produce("V.Anand", "India"));
      dataBeanList.add(produce("Shrinath", "California"));

      return dataBeanList;
   }

   /**
    * This method returns a DataBean object,
    * with name and country set in it.
    */
   private DataBean produce(String name, String country) {
      DataBean dataBean = new DataBean();
      dataBean.setName(name);
      dataBean.setCountry(country);

      return dataBean;
   }
}

Report Generation

我们将使用常规 ANT 构建流程编译并执行上述文件。build.xml 文件(保存在 C:\tools\jasperreports-5.0.1\test 目录下)的内容如下。

We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are as given below.

导入文件 - baseBuild.xml 从第 Environment Setup 章中获取,并应放置在与 build.xml 相同的目录中。

The import file - baseBuild.xml is picked up from the chapter Environment Setup and should be placed in the same directory as the build.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewFillReport" basedir = ".">
   <import file = "baseBuild.xml" />

   <target name = "viewFillReport" depends = "compile,compilereportdesing,run"
      description = "Launches the report viewer to preview the
      report stored in the .JRprint file.">

      <java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true">
         <arg value = "-F${file.name}.JRprint" />
         <classpath refid = "classpath" />
      </java>

   </target>

   <target name = "compilereportdesing" description = "Compiles the JXML file and
      produces the .jasper file.">

      <taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask">
         <classpath refid = "classpath" />
      </taskdef>

      <jrc destdir = ".">
         <src>
            <fileset dir = ".">
               <include name = "*.jrxml" />
            </fileset>
         </src>
         <classpath refid = "classpath" />
      </jrc>

   </target>

</project>

接下来,让我们打开命令行窗口并进入放置 build.xml 的目录。最后,执行命令 ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport 是默认目标),如下所示 −

Next, let’s open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as −

C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml

clean-sample:
   [delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint

compile:
   [mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes
   [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28: warning:
   'includeantruntime' was not set, defaulting to build.sysclasspath=last;
   set to false for repeatable builds
   [javac] Compiling 3 source files to C:\tools\jasperreports-5.0.1\test\classes

compilereportdesing:
   [jrc] Compiling 1 report design files.
   [jrc] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
   [jrc] log4j:WARN Please initialize the log4j system properly.
   [jrc] log4j:WARN See
   http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
   [jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK.

run:
   [echo] Runnin class : com.tutorialspoint.JasperReportFill
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

viewFillReport:
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

作为上述编译的结果,一个 JasperViewer 窗口会打开,如以下给出的屏幕截图所示 -

As a result of above compilation, a JasperViewer window opens up as shown in the screen given below −

style example

在这里,我们可以看到,偶数的字体颜色已变为蓝色(在国家/地区列中)。在名称列中,字体颜色已变为绿色(此样式引用自样式模板)。

Here, we can see that the color of the font is changed to blue for even count (in column country). In the column name, the font color is changed to green (this style is referenced from the style template).

Report Scriptlets

我们在前几章中看到,报告上显示的数据通常从报表参数和字段中获取。可以使用报表变量及其表达式来处理此数据。有时,不能使用报表表达式或变量轻松实现复杂的功能。这方面的示例可能是复杂的字符串操作、构建映射、内存中的对象列表或使用第三方 Java API 执行日期操作。对于这种情况,JasperReports 向我们提供了一种简单而有效的方法,即 Scriptlets

We have seen in our previous chapters, data displayed on the report is usually fetched from report parameters and report fields. This data can be processed using the report variables and their expressions. There are situations when a complex functionality cannot be achieved easily using report expressions or variables. Examples of this may be complex String manipulations, building of Maps, or Lists of objects in memory or manipulations of dates using 3rd party Java APIs. For such situations, JasperReports provides us with a simple and powerful means of doing this with Scriptlets.

脚本是每次发生报告事件时执行的 Java 代码序列。可以通过脚本影响报表变量的值。

Scriptlets are sequences of Java code that are executed every time a report event occurs. Values of report variables can be affected through scriptlets.

Scriptlet Declaration

我们可以通过两种方式声明脚本 -

We can declare a scriptlet in two ways −

  1. Using <*scriptlet*> element. This element has name attribute and class attribute. The class attribute should specify the name of the class, which extends JRAbstractScriptlet class. The class must be available in the classpath at report filling time and must have an empty constructor, so that the engine can instantiate it on the fly.

  2. Using the attribute scriptletClass of the element <*jasperReport*>, in the report template (JRXML). By setting this attribute with fully qualified name of scriptlet (including the entire package name), we indicate that we want to use a scriptlet. The scriptlet instance, created with this attribute, acts like the first scriptlet in the list of scriptlets and has the predefined name REPORT.

Scriptlet class

脚本是 Java 类,它必须扩展以下任一类 -

A scriptlet is a java class, which must extend either of the following classes −

  1. net.sf.jasperreports.engine.JRAbstractScriptlet − This class contains a number of abstract methods that must be overridden in every implementation. These methods are called automatically by JasperReports at the appropriate moment. Developer must implement all the abstract methods.

  2. net.sf.jasperreports.engine.JRDefaultScriptlet − This class contains default empty implementations of every method in JRAbstractScriptlet. A developer is only required to implement those methods he/she needs for his/her project.

下表列出了上面类中的方法。在报表填充阶段,这些方法将在适当的时候由报表引擎调用。

The following table lists the methods in the above class. These methods will be called by the report engine at the appropriate time, during report filling phase.

S.NO

Method and Description

1

public void beforeReportInit() Called before report initialization.

2

public void afterReportInit() Called after report initialization.

3

public void beforePageInit() Called before each page is initialized.

4

public void afterPageInit() Called after each page is initialized.

5

public void beforeColumnInit() Called before each column is initialized.

6

public void afterColumnInit() Called after each column is initialized.

7

public void beforeGroupInit(String groupName) Called before the group specified in the parameter is initialized.

8

public void afterGroupInit(String groupName) Called after the group specified in the parameter is initialized.

9

public void beforeDetailEval() Called before each record in the detail section of the report is evaluated.

10

public void afterDetailEval() Called after each record in the detail section of the report is evaluated.

每个报表可以指定任意数量的脚本。如果未为报表指定脚本,引擎仍会创建单个 JRDefaultScriptlet 实例,并使用内置的 REPORT_SCRIPTLET 参数将其注册。

Any number of scriptlets can be specified per report. If no scriptlet is specified for a report, the engine still creates a single JRDefaultScriptlet instance and registers it with the built-in REPORT_SCRIPTLET parameter.

我们可以向脚本添加我们需要的任何其他方法。报表可以使用内置参数 REPORT_SCRIPTLET 调用这些方法。

We can add any additional methods that we need to our scriptlets. Reports can call these methods by using the built-in parameter REPORT_SCRIPTLET.

Global Scriptlets

我们可以通过另一种方式为报告关联脚本,即全局声明脚本。这使得脚本适用于给定 JasperReports 部署中正在填充的所有报告。由于可以将脚本小程序作为扩展添加到 JasperReports,因此可以轻松实现这一点。脚本扩展点表示为 net.sf.jasperreports.engine.scriptlets.ScriptletFactory 接口。运行时,JasperReports 将加载通过扩展提供的可用脚本工厂。然后,它会向每个脚本工厂询问他们要应用于当前正在运行的报表的脚本实例列表。在询问脚本实例列表时,引擎会提供一些上下文信息,工厂可以使用这些信息来决定哪些脚本实际上适用于当前报表。

We can associate scriptlets in another way to reports, which is by declaring the scriptlets globally. This makes the scriptlets apply to all reports being filled in the given JasperReports deployment. This is made easy by the fact that scriptlets can be added to JasperReports as extensions. The scriptlet extension point is represented by the net.sf.jasperreports.engine.scriptlets.ScriptletFactory interface. JasperReports will load all scriptlet factories available through extensions at runtime. Then, it will ask each one of them for the list of scriptlets instances that they want to apply to the current report that is being run. When asking for the list of scriptlet instances, the engine gives some context information that the factory could use in order to decide, which scriptlets actually apply to the current report.

Report Governors

总督只是全局脚本的扩展,它使我们能够解决在生成报表时报表引擎在运行时进入无限循环的问题。无效的报表模板无法在设计时检测到,因为大多数时候,进入无限循环的条件取决于在运行时馈入引擎的实际数据。报表总督有助于决定某个报表是否进入了无限循环,并且可以停止它。这可以防止为运行报表的机器耗尽资源。

Governors are just an extension of global scriptlets that enable us to tackle a problem of report engine entering infinite loop at runtime, while generating reports. Invalid report templates cannot be detected at design time, because most of the time, the conditions for entering the infinite loops depend on the actual data that is fed into the engine at runtime. Report Governors help in deciding whether a certain report has entered an infinite loop and they can stop it. This prevents resource exhaustion for the machine that runs the report.

JasperReports 具有两个简单的报表总督,它们将根据指定的最大页数或指定的超时间隔来停止报表执行。它们是 −

JasperReports has two simple report governors that would stop a report execution based on a specified maximum number of pages or a specified timeout interval. They are −

  1. net.sf.jasperreports.governors.MaxPagesGovernor − This is a global scriptlet that is looking for two configuration properties to decide if it applies or not to the report currently being run. The configuration properties are − net.sf.jasperreports.governor.max.pages.enabled=[true|false] net.sf.jasperreports.governor.max.pages=[integer]

  2. net.sf.jasperreports.governors.TimeoutGovernor− This is also a global scriptlet that is looking for the following two configuration properties to decide if it applies or not. The configuration properties are − net.sf.jasperreports.governor.timeout.enabled=[true|false] net.sf.jasperreports.governor.timeout=[milliseconds]

这两个调节器的属性可以作为自定义报告属性在 jasperreports.properties 文件中全局设置,或者在报告级别设置。由于不同的报告可以具有不同的估计大小或超时限制,并且你可能希望对所有报告启用调节器,同时对某些报告禁用,反之亦然,因此此功能非常有用。

The properties for both governors can be set globally, in the jasperreports.properties file, or at report level, as custom report properties. This is useful because different reports can have different estimated size or timeout limits and also because you might want turn on the governors for all reports, while turning it off for some, or vice-versa.

Example

我们编写一个脚本小类 ( MyScriptlet )。C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\MyScriptlet.java 文件的内容如下 −

Let’s write a scriptlet class (MyScriptlet). The contents of file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\MyScriptlet.java are as follows −

package com.tutorialspoint;

import net.sf.jasperreports.engine.JRDefaultScriptlet;
import net.sf.jasperreports.engine.JRScriptletException;


public class MyScriptlet extends JRDefaultScriptlet {

   public void afterReportInit() throws JRScriptletException{
      System.out.println("call afterReportInit()");
      // this.setVariableValue("AllCountries", sbuffer.toString());
      this.setVariableValue("someVar", new String("This variable value
         was modified by the scriptlet."));
   }

   public String hello() throws JRScriptletException {
      return "Hello! I'm the report's scriptlet object.";
   }

}

上述脚本小类详细信息如下 −

Details of the above scriptlet class are as follows −

  1. In the afterReportInit method, we set a value to the variable "someVar" this.setVariableValue("someVar", new String("This variable value was modified by the scriptlet.")).

  2. At the end of the class, an extra method called 'hello' has been defined. This is an example of a method that can be added to the Scriptlet that actually returns a value, rather than setting a Variable.

接下来,我们在现有的报告模板(章节 Report Designs )中添加脚本小类引用。修订后的报告模板(jasper_report_template.jrxml)如下。将其保存到 C:\tools\jasperreports-5.0.1\test 目录 −

Next, we will add the scriptlet class reference in our existing report template (Chapter Report Designs). The revised report template (jasper_report_template.jrxml) are as follows. Save it to C:\tools\jasperreports-5.0.1\test directory −

<?xml version = "1.0"?>
<!DOCTYPE jasperReport PUBLIC
   "//JasperReports//DTD Report Design//EN"
   "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">

<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
   http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
   name = "jasper_report_template" pageWidth = "595"
   pageHeight = "842" columnWidth = "515"
   leftMargin = "40" rightMargin = "40" topMargin = "50" bottomMargin = "50"
   scriptletClass = "com.tutorialspoint.MyScriptlet">

   <style name = "alternateStyle" fontName = "Arial" forecolor = "red">

      <conditionalStyle>
         <conditionExpression>
            <![CDATA[new Boolean($V{countNumber}.intValue() % 2 == 0)]]>
         </conditionExpression>

         <style forecolor = "blue" isBold = "true"/>
      </conditionalStyle>
   </style>

   <parameter name = "ReportTitle" class = "java.lang.String"/>
   <parameter name = "Author" class = "java.lang.String"/>

   <queryString>
      <![CDATA[]]>
   </queryString>

   <field name = "country" class = "java.lang.String">
      <fieldDescription>
         <![CDATA[country]]>
      </fieldDescription>
   </field>

   <field name = "name" class = "java.lang.String">
      <fieldDescription>
         <![CDATA[name]]>
      </fieldDescription>
   </field>

   <variable name = "countNumber" class = "java.lang.Integer"
      calculation = "Count">
      <variableExpression><
         ![CDATA[Boolean.TRUE]]>
      </variableExpression>
   </variable>

   <variable name = "someVar" class = "java.lang.String">
      <initialValueExpression>
        <![CDATA["This is the initial variable value."]]>
      </initialValueExpression>
   </variable>

   <title>
      <band height = "100">

         <line>
            <reportElement x = "0" y = "0" width = "515" height = "1"/>
         </line>

         <textField isBlankWhenNull = "true" bookmarkLevel = "1">
            <reportElement x = "0" y = "10" width = "515" height = "30"/>

            <textElement textAlignment = "Center">
              <font size = "22"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
              <![CDATA[$P{ReportTitle}]]>
            </textFieldExpression>

            <anchorNameExpression>
               <![CDATA["Title"]]>
            </anchorNameExpression>
         </textField>

         <textField isBlankWhenNull = "true">
            <reportElement  x = "0" y = "40" width = "515" height = "20"/>

            <textElement textAlignment = "Center">
               <font size = "10"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{Author}]]>
            </textFieldExpression>
         </textField>

         <textField isBlankWhenNull = "true">
            <reportElement  x = "0" y = "50" width = "515"
               height = "30" forecolor = "#993300"/>

            <textElement textAlignment = "Center">
               <font size = "10"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$V{someVar}]]>
            </textFieldExpression>

         </textField>

      </band>
   </title>

   <columnHeader>
      <band height = "23">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "3"
               width = "535" height = "15"
               backcolor = "#70A9A9" />

            <box>
               <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" />
            </box>

            <textElement />

            <text>
               <![CDATA[]]>
            </text>

         </staticText>

         <staticText>
            <reportElement x = "414" y = "3" width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>

            <text><![CDATA[Country]]></text>
         </staticText>

         <staticText>
            <reportElement x = "0" y = "3" width = "136" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>

            <text><![CDATA[Name]]></text>
         </staticText>

      </band>
   </columnHeader>

   <detail>
      <band height = "16">

         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "0"
               width = "535"	height = "14"
               backcolor = "#E5ECF9" />

            <box>
               <bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" />
            </box>

            <textElement />

            <text>
               <![CDATA[]]>
            </text>
         </staticText>

         <textField>
            <reportElement style = "alternateStyle" x="414" y = "0"
               width = "121" height = "15" />

            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font size = "9" />
            </textElement>


            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{country}]]>
            </textFieldExpression>
         </textField>

         <textField>
            <reportElement x = "0" y = "0" width = "136" height = "15" />
            <textElement textAlignment = "Center" verticalAlignment = "Middle" />

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{name}]]>
            </textFieldExpression>
         </textField>

      </band>
   </detail>

   <summary>
      <band height = "45">

         <textField isStretchWithOverflow = "true">
            <reportElement x = "0" y = "10" width = "515" height = "15" />
            <textElement textAlignment = "Center"/>

            <textFieldExpression class = "java.lang.String">
               <![CDATA["There are " + String.valueOf($V{REPORT_COUNT}) +
                  " records on this report."]]>
            </textFieldExpression>
         </textField>

         <textField isStretchWithOverflow = "true">
            <reportElement positionType = "Float" x = "0" y = "30" width = "515"
               height = "15" forecolor = "# 993300" />

            <textElement textAlignment = "Center">
               <font size = "10"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{REPORT_SCRIPTLET}.hello()]]>
            </textFieldExpression>

         </textField>

      </band>
   </summary>

</jasperReport>

修订后的报告模板的详细信息如下 −

The details of the revised report template is given below −

  1. We have referenced the MyScriptlet class in the attribute scriptletClass of <jasperReport> element.

  2. Scriptlets can only access, but not modify the report fields and parameters. However, scriptlets can modify report variable values. This can be accomplished by calling the setVariableValue() method. This method is defined in JRAbstractScriptlet class, which is always the parent class of any scriptlet. Here, we have defined a variable someVar, which will be modified by the MyScriptlet to have the value This value was modified by the scriptlet.

  3. The above report template has a method call in the Summary band that illustrates how to write new methods (in scriptlets) and use them in the report template. ($P{REPORT_SCRIPTLET}.hello())

报表填充的 java 代码保持不变。文件 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java 的内容如下 -

The java codes for report filling remain unchanged. The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java are as given below −

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class JasperReportFill {
   @SuppressWarnings("unchecked")
   public static void main(String[] args) {
      String sourceFileName =
         "C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper";

      DataBeanList DataBeanList = new DataBeanList();
      ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();

      JRBeanCollectionDataSource beanColDataSource = new
         JRBeanCollectionDataSource(dataList);

      Map parameters = new HashMap();
      /**
       * Passing ReportTitle and Author as parameters
       */
      parameters.put("ReportTitle", "List of Contacts");
      parameters.put("Author", "Prepared By Manisha");

      try {
         JasperFillManager.fillReportToFile(
         sourceFileName, parameters, beanColDataSource);
      } catch (JRException e) {
         e.printStackTrace();
      }
   }
}

C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java POJO 文件的内容如下 −

The contents of the POJO file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java are as given below −

package com.tutorialspoint;

public class DataBean {
   private String name;
   private String country;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getCountry() {
      return country;
   }

   public void setCountry(String country) {
      this.country = country;
   }
}

C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java 文件的内容如下 −

The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java are as given below −

package com.tutorialspoint;

import java.util.ArrayList;

public class DataBeanList {
   public ArrayList<DataBean> getDataBeanList() {
      ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();

      dataBeanList.add(produce("Manisha", "India"));
      dataBeanList.add(produce("Dennis Ritchie", "USA"));
      dataBeanList.add(produce("V.Anand", "India"));
      dataBeanList.add(produce("Shrinath", "California"));

      return dataBeanList;
   }

   /**
    * This method returns a DataBean object,
    * with name and country set in it.
    */
   private DataBean produce(String name, String country) {
      DataBean dataBean = new DataBean();
      dataBean.setName(name);
      dataBean.setCountry(country);

      return dataBean;
   }
}

Report Generation

我们将使用常规 ANT 构建流程编译并执行上述文件。build.xml 文件(保存在 C:\tools\jasperreports-5.0.1\test 目录下)的内容如下。

We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are as given below.

导入文件 - baseBuild.xml 从第 Environment Setup 章中获取,并应放置在与 build.xml 相同的目录中。

The import file - baseBuild.xml is picked up from the chapter Environment Setup and should be placed in the same directory as the build.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewFillReport" basedir = ".">
   <import file = "baseBuild.xml" />

   <target name = "viewFillReport" depends = "compile,compilereportdesing,run"
      description = "Launches the report viewer to preview
      the report stored in the .JRprint file.">

      <java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true">
         <arg value = "-F${file.name}.JRprint" />
         <classpath refid = "classpath" />
      </java>
   </target>

   <target name = "compilereportdesing" description = "Compiles the JXML file and
      produces the .jasper file.">

      <taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask">
         <classpath refid = "classpath" />
      </taskdef>

      <jrc destdir = ".">
         <src>
            <fileset dir = ".">
               <include name = "*.jrxml" />
            </fileset>
         </src>
         <classpath refid = "classpath" />
      </jrc>

   </target>

</project>

接下来,让我们打开命令行窗口并进入放置 build.xml 的目录。最后,执行命令 ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport 是默认目标),如下所示 −

Next, let’s open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as −

C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml

clean-sample:
   [delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint

compile:
   [mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes
   [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28:
   warning: 'includeantruntime' was not set, defaulting to bu
   [javac] Compiling 4 source files to C:\tools\jasperreports-5.0.1\test\classes

compilereportdesing:
   [jrc] Compiling 1 report design files.
   [jrc] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
   [jrc] log4j:WARN Please initialize the log4j system properly.
   [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
   [jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK.

run:
   [echo] Runnin class : com.tutorialspoint.JasperReportFill
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.
   [java] call afterReportInit()
   [java] call afterReportInit()

viewFillReport:
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

BUILD SUCCESSFUL
Total time: 18 minutes 49 seconds

作为上述编译的结果,一个 JasperViewer 窗口会打开,如以下给出的屏幕截图所示 -

As a result of above compilation, a JasperViewer window opens up as shown in the screen given below −

report scriptlet example

此处我们看到从 MyScriptlet 类显示了两条消息 −

Here we see two messages are displayed from MyScriptlet class −

  1. In title section − This variable value was modified by the scriptlet

  2. At the bottom − Hello! I’m the report’s scriptlet object.

Create SubReports

子报表是 JasperReports 的一项不错的功能。此功能允许在另一个报表内合并报表,即一个报表可以是另一个报表的子报表。子报表帮助我们保持报表设计简单,因为我们可以创建许多简单的报表并将其封装到一个主报表中。子报表像普通报表一样进行编译和填充。在合并到另一个报表模板时,任何报表模板都可以用作子报表,而无需对(报表模板)中的任何内容进行更改。

Subreports are one of the nice features of the JasperReports. This feature allows incorporating a report within another report, that is, one report can be a subreport of another. Subreports help us keep report designs simple, as we can create many simple reports and encapsulate them into a master report. Subreports are compiled and filled just like normal reports. Any report template can be used as a subreport when incorporated into another report template, without anything changed inside (of the report template).

子报表就像普通报表模板。实际上,它们是 net.sf.jasperreports.engine.JasperReport 对象,在编译 net.sf.jasperreports.engine.design.JasperDesign 对象后获得这些对象。

Subreports are like normal report templates. They are in fact net.sf.jasperreports.engine.JasperReport objects, which are obtained after compiling a net.sf.jasperreports.engine.design.JasperDesign object.

<subreport> Element

在将子报表引入主报表时,会使用 <subreport> 元素。下面是 <subreport> JRXML 元素的子元素列表。

A <subreport> element is used when introducing subreports into master reports. Here is the list of sub-elements in the <subreport> JRXML element.

  1. <reportElement>

  2. <parametersMapExpression> − This is used to pass a map containing report parameters to the subreport. The map is usually obtained from a parameter in the master report, or by using the built-in REPORTS_PARAMETERS_MAP parameter to pass the parent report’s parameters to the subreport. This expression should always return a java.util.Map object in which the keys are the parameter names.

  3. <subreportParameter> − This element is used to pass parameters to the subreport. It has an attribute name, which is mandatory.

  4. <connectionExpression > − This is used to pass a java.sql.Connection to the subreport. It is used only when the subreport template needs a database connection during report filling phase.

  5. <dataSourceExpression> − This is used to pass a datasource to the subreport. This datasource is usually obtained from a parameter in the master report or by using the built-in REPORT_DATA_SOURCE parameter to pass the parent report’s datasource to the subreport.

  6. The elements (connectionExpression and dataSourceExpression) cannot be present at the same time in a <subreport> element declaration. This is because we cannot supply both a data source and a connection to the subreport. We must decide on one of them and stick to it.

  7. <returnValue> − This is used to assign the value of one of the subreport’s variables to one of the master report’s variables. This sub element has attributes as follows − subreportVariable − This attribute specifies the name of the subreport variable whose value is to be returned. toVariable − This attribute specifies the name of the parent report variable whose value is to be copied/incremented with the value from the subreport. calculation − This attribute can take values : Nothing, Count, DistinctCount, Sum, Average, Lowest, Highest, StandardDeviation, Variance. Default value for attribute calculation is "Nothing". incrementerFactoryClass − This attribute specifies the factory class for creating the incrementer instance.

  8. <subreportExpression> − This indicates where to find the compiled report template for the subreport. This element has a class attribute. The class attribute can take any of these values:java.lang.String, java.io.File, java.net.URL, java.io.InputStream, net.sf.jasperreports.engine.JasperReport. Default value is java.lang.String.

  9. isUsingCache − This is an attribute of the <subreport> element. This is a Boolean, when set to true, the reporting engine will try to recognize previously loaded subreport template objects, using their specified source. This caching functionality is available only for subreport elements that have expressions returning java.lang.String objects as the subreport template source, representing file names, URLs, or classpath resources.

Example

让我们举一个简单的示例来说明使用 JRDataSource 创建子报表的步骤。首先,我们编写两个新的报表模板,一个是子报表,另一个是主报表。子报表 (address_report_template.jrxml) 模板的内容如下。将其保存到 C:\tools\jasperreports-5.0.1\test 目录中。

Let take up a simple example to demonstrate creation of subreports using JRDataSource. Let’s first write two new report templates, one being subreport and the other Master report. The contents of the subreport (address_report_template.jrxml) template is as given below. Save it to C:\tools\jasperreports-5.0.1\test directory.

<?xml version = "1.0" encoding = "UTF-8"?>
<jasperReport
   xmlns = "http://jasperreports.sourceforge.net/jasperreports"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
   http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
   name = "address_report_template" pageWidth = "175" pageHeight = "842"
   columnWidth = "175" leftMargin = "0" rightMargin = "0"
   topMargin = "0" bottomMargin = "0">

   <field name = "city" class = "java.lang.String"/>
   <field name = "street" class = "java.lang.String"/>

   <background>
      <band splitType = "Stretch"/>
   </background>

   <title>
      <band height = "20" splitType = "Stretch">

         <staticText>
            <reportElement x = "0" y = "0" width = "100" height = "20"/>

            <textElement>
               <font size = "14" isBold = "true"/>
            </textElement>

            <text><![CDATA[Addresses]]></text>
         </staticText>

      </band>
   </title>

   <pageHeader>
      <band height = "12" splitType = "Stretch"/>
   </pageHeader>

   <columnHeader>
      <band height = "12" splitType = "Stretch"/>
   </columnHeader>

   <detail>
      <band height = "27" splitType = "Stretch">

         <textField>
            <reportElement x = "0" y = "0" width = "120" height = "20"/>

            <textElement>
               <font size = "12" isBold = "true"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{city}+" Address:"]]>
            </textFieldExpression>
         </textField>

         <textField isStretchWithOverflow = "true">
            <reportElement x = "120" y = "0" width = "435" height = "20"/>

            <textElement>
               <font size = "12"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{street}]]>
            </textFieldExpression>
         </textField>

      </band>
   </detail>

   <columnFooter>
      <band height = "8" splitType = "Stretch"/>
   </columnFooter>

   <pageFooter>
      <band height = "11" splitType = "Stretch"/>
   </pageFooter>

   <summary>
      <band height = "9" splitType = "Stretch"/>
   </summary>

</jasperReport>

由于我们使用数据源,因此我们需要编写一个相应的 POJO 文件 *SubReportBean.java *,如下所示。将其保存到目录 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint −

As we use a data source, we need to write a corresponding POJO file *SubReportBean.java * as shown below. Save it to directory C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint −

package com.tutorialspoint;

public class SubReportBean {
   private String city;
   private String street;

   public String getCity() {
      return city;
   }

   public void setCity(String city) {
      this.city = city;
   }

   public String getStreet() {
      return street;
   }

   public void setStreet(String street) {
      this.street = street;
   }
}

在此,我们声明了两个字段 'city' 和 'street',并定义了相应的 getter 和 setter 方法。

Here, we have declared two fields 'city' and 'street' and respective getter and setter methods are defined.

现在,我们来更新现有的 DataBean 文件。我们将添加一个新字段 subReportBeanList,它是一个 java.util.List。此字段将保存 SubReportBean 对象的列表。DataBean 文件的内容如下。将其保存到目录 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint。

Now, let’s update our existing DataBean file. We will add a new field subReportBeanList, which is a java.util.List. This field will hold the list of SubReportBean objects. The contents of the file DataBean are as below. Save it to directory C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint.

package com.tutorialspoint;

import java.util.List;

public class DataBean {
   private String name;
   private String country;
   private List<SubReportBean> subReportBeanList;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getCountry() {
      return country;
   }

   public void setCountry(String country) {
      this.country = country;
   }

   public List<SubReportBean> getSubReportBeanList() {
      return subReportBeanList;
   }

   public void setSubReportBeanList(List<SubReportBean> subReportBeanList) {
      this.subReportBeanList = subReportBeanList;
   }
}

我们现在更新文件 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint*DataBeanList.java*。该文件的内容如下 −

Let’s now update the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint*DataBeanList.java*. The contents of this file are as −

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class DataBeanList {
   public ArrayList<DataBean> getDataBeanList() {

      // Create sub report data
      SubReportBean subBean1 = new SubReportBean();
      subBean1.setCity("Mumbai");
      subBean1.setStreet("M.G.Road");
      SubReportBean subBean2 = new SubReportBean();
      subBean2.setCity("New York");
      subBean2.setStreet("Park Street");
      SubReportBean subBean3 = new SubReportBean();
      subBean3.setCity("San Fransisco");
      subBean3.setStreet("King Street");

      ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();

      // Create master report data
      dataBeanList.add(produce("Manisha", "India",
         Arrays.asList(subBean1)));
      dataBeanList.add(produce("Dennis Ritchie", "USA",
         Arrays.asList(subBean2)));
      dataBeanList.add(produce("V.Anand", "India",
         Arrays.asList(subBean1)));
      dataBeanList.add(produce("Shrinath", "California",
         Arrays.asList(subBean3)));

      return dataBeanList;
   }

   /*
    * This method returns a DataBean object,
    * with name, country and sub report
    * bean data set in it.
    */
   private DataBean produce(String name, String country,
      List<SubReportBean> subBean) {
      DataBean dataBean = new DataBean();

      dataBean.setName(name);
      dataBean.setCountry(country);
      dataBean.setSubReportBeanList(subBean);

      return dataBean;
   }
}

在上述文件中的 produce() 方法中,我们设置了 SubReportBean 的列表。

In the method produce() in the above file, we are setting the list of SubReportBean.

现在,我们来编写一个新的主报表模板(jasper_report_template.jrxml)。将此文件保存到目录 C:\tools\jasperreports-5.0.1\test 。该文件的内容如下 −

Now, let’s write a new master report template (jasper_report_template.jrxml). Save this file to directory C:\tools\jasperreports-5.0.1\test. The contents for this file are as below −

<?xml version = "1.0" encoding = "UTF-8"?>
<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
   http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
   name = "jasper_report_template" language = "groovy" pageWidth = "595"
   pageHeight = "842" columnWidth ="555" leftMargin = "20" rightMargin = "20"
   topMargin = "20" bottomMargin = "20">

   <parameter name = "SUBREPORT_DIR" class = "java.lang.String" isForPrompting = "false">
      <defaultValueExpression>
         <![CDATA["C:\\tools\\jasperreports-5.0.1\\test\\"]]>
      </defaultValueExpression>
   </parameter>

   <field name = "country" class = "java.lang.String"/>
   <field name = "name" class = "java.lang.String"/>
   <field name = "subReportBeanList" class = "java.util.List"/>

   <background>
      <band splitType = "Stretch"/>
   </background>

   <title>
      <band height = "35" splitType = "Stretch">

         <staticText>
            <reportElement x = "0" y = "0" width = "204" height = "34"/>

            <textElement>
               <font size = "26" isBold = "true"/>
            </textElement>

            <text><![CDATA[Contact Report]]></text>
         </staticText>

      </band>
   </title>

   <pageHeader>
      <band height = "17" splitType = "Stretch"/>
   </pageHeader>

   <columnHeader>
      <band height = "21" splitType = "Stretch"/>
   </columnHeader>

   <detail>
      <band height = "112" splitType = "Stretch">

         <staticText>
            <reportElement x = "0" y = "0" width = "100" height = "20"/>

            <textElement>
               <font size = "12" isBold = "true"/>
            </textElement>

            <text><![CDATA[Name:]]></text>
         </staticText>

         <staticText>
            <reportElement x = "0" y = "20" width = "100" height = "20"/>

            <textElement>
               <font size = "12" isBold = "true"/>
            </textElement>

            <text><![CDATA[Country:]]></text>
         </staticText>

         <textField>
            <reportElement x = "104" y = "0" width = "277" height = "20"/>

            <textElement>
               <font size = "12"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{name}]]>
            </textFieldExpression>
         </textField>

         <textField>
            <reportElement x = "104" y = "20" width = "277" height = "20"/>

            <textElement>
               <font size = "12"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{country}]]>
            </textFieldExpression>
         </textField>

         <subreport>
            <reportElement positionType = "Float" x = "335" y = "25" width = "175"
               height = "20" isRemoveLineWhenBlank = "true" backcolor = "#99ccff"/>

            <dataSourceExpression>
               new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource
                  ($F{subReportBeanList})
            </dataSourceExpression>

            <subreportExpression class = "java.lang.String">
               <![CDATA[$P{SUBREPORT_DIR} + "address_report_template.jasper"]]>
            </subreportExpression>
         </subreport>

         <line>
            <reportElement x = "0" y = "50" width = "550" height = "1"/>
         </line>

      </band>
   </detail>

   <columnFooter>
      <band height = "19" splitType = "Stretch"/>
   </columnFooter>

   <pageFooter>
      <band height = "18" splitType = "Stretch"/>
   </pageFooter>

   <summary>
      <band height = "14" splitType = "Stretch"/>
   </summary>

</jasperReport>

在上述模板中,我们定义了一个新参数“SUBREPORT_DIR”,该参数定义了子报表的路径。我们定义了一个类型为 java.util.List 的字段 subReportBeanList,它对应于 DataBean 文件中的属性。元素 <subreport> 有子元素 <dataSourceExpression>。我们已将列表 subReportBeanList 放入 JRBeanCollectionDataSource 的实例中。在子元素 <subreportExpression/> 中,我们给出了子报表名称(AddressReport.jasper)。

In the above template, we have defined a new parameter "SUBREPORT_DIR," which defines the path of the subreport. We have defined a field subReportBeanList of type java.util.List, which corresponds to property in the file DataBean. The element <subreport> has sub-element <dataSourceExpression>. We have put the list subReportBeanList in an instance of JRBeanCollectionDataSource. In the sub-element <subreportExpression/>, we have given the subreport name (AddressReport.jasper).

现在,我们来编写一个新类 CreateReport 来编译和执行我们的报表模板。文件 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\CreateReport.java 的内容如下 −

Now, let’s write a new class CreateReport to compile and execute our report template. The contents of file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\CreateReport.java are as given below −

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class CreateReport {

   public static void main(String[] args) {
      String masterReportFileName = "C://tools/jasperreports-5.0.1/test"
         + "/jasper_report_template.jrxml";
      String subReportFileName = "C://tools/jasperreports-5.0.1/test"
         + "/AddressReport.jrxml";
      String destFileName = "C://tools/jasperreports-5.0.1/test"
         + "/jasper_report_template.JRprint";

      DataBeanList DataBeanList = new DataBeanList();
      ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();
      JRBeanCollectionDataSource beanColDataSource = new
         JRBeanCollectionDataSource(dataList);

      try {
         /* Compile the master and sub report */
         JasperReport jasperMasterReport = JasperCompileManager
            .compileReport(masterReportFileName);
         JasperReport jasperSubReport = JasperCompileManager
            .compileReport(subReportFileName);

         Map<String, Object> parameters = new HashMap<String, Object>();
         parameters.put("subreportParameter", jasperSubReport);
         JasperFillManager.fillReportToFile(jasperMasterReport,
            destFileName, parameters, beanColDataSource);

      } catch (JRException e) {

         e.printStackTrace();
      }
      System.out.println("Done filling!!! ...");
   }
}

此处,可以看到我们在编译主模板和子报表模板,并传递主报表(.jasper)文件以用于报表填充。

Here, we see that we are compiling both the master and sub report templates and passing the master report (.jasper) file for the report filling.

Report Generation

现在,我们的所有文件都准备好了,我们使用常规 ANT 构建流程来编译和执行它们。文件 build.xml 的内容(保存在目录 C:\tools\jasperreports-5.0.1\test 下)如下所示。

Now, all our files are ready, let’s compile and execute them using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are as given below.

导入文件 - baseBuild.xml 从第 Environment Setup 章中获取,并应放置在与 build.xml 相同的目录中。

The import file - baseBuild.xml is picked up from the chapter Environment Setup and should be placed in the same directory as the build.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewFillReport" basedir = ".">
   <import file = "baseBuild.xml" />

   <target name = "viewFillReport" depends = "compile,compilereportdesing,run"
      description = "Launches the report viewer to preview the
      report stored in the .JRprint file.">

      <java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true">
         <arg value = "-F${file.name}.JRprint" />
         <classpath refid = "classpath" />
      </java>
   </target>

   <target name = "compilereportdesing" description = "Compiles the JXML file and
      produces the .jasper file.">

      <taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask">
         <classpath refid = "classpath" />
      </taskdef>

      <jrc destdir = ".">
         <src>
            <fileset dir = ".">
               <include name = "*.jrxml" />
            </fileset>
         </src>
         <classpath refid = "classpath" />
      </jrc>

   </target>

</project>

接下来,让我们打开命令行窗口并转到放置 build.xml 的目录。最后,执行命令 ant -Dmain-class=com.tutorialspoint.CreateReport (viewFullReport 是默认目标),如下所示 −

Next, let’s open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.CreateReport (viewFullReport is the default target) as follows −

Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml

clean-sample:
   [delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes

compile:
   [mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes
   [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28:
      warning: 'includeantruntime' was not set, defaulting to
   [javac] Compiling 7 source files to C:\tools\jasperreports-5.0.1\test\classes

compilereportdesing:
   [jrc] Compiling 1 report design files.
   [jrc] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
   [jrc] log4j:WARN Please initialize the log4j system properly.
   [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig
      for more info.
   [jrc] File : C:\tools\jasperreports-5.0.1\test\
      jasper_report_template.jrxml ... OK.

run:
   [echo] Runnin class : com.tutorialspoint.CreateReport
   [java] Compiling Report Design ...
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
   [java] log4j:WARN Please initialize the log4j system properly.
   [java] Done filling!!! ...

viewFillReport:
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

BUILD SUCCESSFUL
Total time: 72 minutes 13 seconds

作为上述编译的结果,一个 JasperViewer 窗口会打开,如以下给出的屏幕截图所示 -

As a result of above compilation, a JasperViewer window opens up as shown in the screen given below −

subreport example

此处,可以看到显示了属性 Name、Country 和 Address。

Here, we can see that the attributes Name, Country, and Address are displayed.

Creating Charts

此前,人们不得不依赖脚本小类来收集图表数据,并使用报告模板中的图像元素来呈现图表。JasperReports 现在让此过程变得简单,因为它对使用新图表组件的图表内置有支持。

Earlier people had to rely on scriptlets to gather the chart data and render the chart using an image element in the report template. JasperReports makes it simple now, as it has a built-in support for charts using the new chart component.

使用新的图表组件,用户只需要应用视觉设置,并定义有助于构建图表数据集的表达式。JasperReports 使用 JFreeChart 作为底层图表库。在配置新的图表组件时,涉及以下三个组件 −

Using a new chart component, user needs to apply only the visual settings and define expressions that will help build the chart dataset. JasperReports uses JFreeChart as the underlying charting library. When configuring a new chart component, following three components are involved −

  1. The overall chart component.

  2. The chart dataset (which groups chart data-related settings).

  3. The chart plot (which groups visual settings related to the way the chart items are rendered).

JasperReports 目前支持以下类型的图表:饼图、3D 饼图、条形图、3D 条形图、XY 条形图、堆积条形图、3D 堆积条形图、折线图、XY 折线图、面积图、XY 面积图、堆积面积图、散点图、气泡图、时间序列图、高开低收图、蜡烛图、多轴图表、仪表图、温度计和甘特图。

JasperReports currently supports the following types of charts: Pie, Pie 3D, Bar, Bar 3D, XY Bar, Stacked Bar, Stacked Bar 3D, Line, XY Line, Area, XY Area, Stacked Area, Scatter, Bubble, Time Series, High-Low-Open-Close, Candlestick, Multiple Axis, Meter, Thermometer, and Gantt.

Chart Properties

图表是常规报表元素,因此它们与其它的报表元素共享一些属性。有一个名为 <*chart*> 的 JRXML 元素,用于创建所有类型的图表。此元素将适用于所有类型的图表特殊图表相关设置分组。

Charts are normal report elements, so they share some of their properties with all the other report elements. There is a JRXML element called <*chart*>, used to create all type of charts. This element groups special chart-specific settings that apply to all types of charts.

Chart Sub-Elements

<chart> 元素的子元素是:

The sub-elements of <chart> element are −

  1. <reportElement> − These are displayable objects like static texts, text fields, images, lines, and rectangles that you put in your report template sections.

  2. <Box> − This element is used to surround charts by a border that’s customizable on each side.

  3. <chartTitle> − This element is used to place the title of the chart. The position attribute decides the title position of the chart in the report. This element has attributes - Position (Values could be Top, Bottom, Left, Right. Deafult value is Top), color. <chartTitle> has font and titleExpression as subelements.

  4. <chartSubtitle> − This element is used to place the subtitle of the chart. This element has attribute - color. <chartSubtitle> has font and subtitleExpression as subelements.

  5. <chartLegend> − The element can control the font-related properties as well as the text color and the background color of the chart legend using this element. This element has attributes - textColor and backgroundColor.

  6. <anchorNameExpression> − This element creates the target for the anchor.

  7. <hyperlinkReferenceExpression> − This element contains a report expression indicating the name of the external resource (usually a URL).

  8. <hyperlinkAnchorExpression> − Hyperlink points to an anchor in an external resource.

  9. <hyperlinkPageExpression> − Hyperlink points to a page in the current report.

  10. <hyperlinkTooltipExpression> − This element controls the ToolTip of hyperlink. The type of the expression should be java.lang.String.

  11. <hyperlinkParameter> − This element when present generates a final hyperlink depending on the parameter values.

Chart attributes

<chart> 元素中可用于所有图表类型的所有属性:

Attributes in the <chart> element available for all chart types are −

  1. isShowLegend − This attribute is used to determine, if a chart legend will be displayed on the report. Values could be true, or false. Default value is true.

  2. evaluationTime − Determines when the chart’s expression will be evaluated. Values could be Now, Report, Page, Column, Group, Band. Default value is Now.

  3. evaluationGroup − This attribute determines the name of the group to be used to evaluate the chart’s expressions. The value for this attribute must match the name of the group, we would like to use as the chart’s evaluation group.

  4. hyperlinkType − This attribute can hold any text value. Default value is None. This means, neither the text fields nor the images represent hyperlinks, even if the special hyperlink expressions are present.

  5. hyperlinkTarget − This attribute helps to customize the behavior of the specified link when it is clicked in the viewer. Values could be Self, or Blank. Default value is Self.

  6. bookmarkLevel − This attribute when set to a positive integer, generates bookmarks in the reports exported to PDF. Default value is 0.

  7. customizerClass − This is the name of a class (optional) that can be used to customize the chart. The value for this element must be a String containing the name of a customizer class.

Chart customization

如上所述,JasperReports 使用 JFreeChart 作为底层制图库。JFreeChart 包含 JasperReports 不直接支持的功能。我们可以通过 <chart> 元素中的 customizerClass 属性提供自定义器类来利用这些功能。自定义器类不过是 net.sf.jasperreports.engine.JRChartCustomizer 界面的实现。实现此界面的最简单方法是扩展 net.sf.jasperreports.engine.JRAbstractChartCustomizer 类,从而访问参数、字段和变量,以便根据报表数据更灵活地自定义图表。

As mentioned above, JasperReports uses JFreeChart as the underlying charting library. JFreeChart contains features that are directly not supported by JasperReports. We can take advantage of these features by supplying a customizer class via the customizerClass attribute in <chart> element. A customizer class is nothing, but an implementation of the net.sf.jasperreports.engine.JRChartCustomizer interface. The easiest way to implement this interface is by extending the net.sf.jasperreports.engine.JRAbstractChartCustomizer class and thus having access to parameters, fields, and variables for more flexible chart customization based on report data.

Chart Datasets

所有图表类型的一个通用属性是 <*dataset*> 元素。图表数据集有助于映射报表数据并在运行时检索图表数据。每种图表类型包含不同的子元素来定义图表表达式。这些表达式定义用于生成图表的数据。所有这些子元素都包含一个 <dataset> 元素,该元素定义何时对图表表达式进行求值和重置。

One of the common properties across all chart types is <*dataset*> element. Chart datasets help mapping report data and retrieving chart data at runtime. Each chart type contains different sub-elements to define chart’s expressions. These expressions define the data used to generate the chart. All of these sub-elements contain a <dataset> element that defines when the chart’s expressions are evaluated and reset.

JasperReports 中有几种图表数据集类型,因为每种类型的图表都与某些数据集一起使用:Pie、Category、XY、Time Series、Time Period、XYZ 和 High-Low。每种数据集类型都实现了定义图表数据集的 net.sf.jasperreports.engine.JRChartDataset 接口。所有图表数据集都以相同的方式初始化和递增;但是,它们仅在映射的数据或数据序列的类型上有所不同。

Several types of chart datasets are available in JasperReports because each type of chart works with certain datasets: Pie, Category, XY, Time Series, Time Period, XYZ, and High-Low. Each of these dataset types implements net.sf.jasperreports.engine.JRChartDataset interface that define chart datasets. All chart datasets initialize and increment in the same way; however, they differ only in the type of data or data series they map.

Dataset Properties

下表总结了元素 <dataset> 的属性 -

Table given below summarizes the attributes of the element <dataset> −

Attribute

Description

Values

resetType

This attribute determines when the value of the chart expression is to be reset.

None, Report, Page, Column, Group. Default value is Report.

resetGroup

This attribute determines the name of the group at which the chart expression value is reset.

The value for this attribute must match the name of any group declared in the JRXML report template.

incrementType

This attribute determines when to recalculate the value of the chart expression.

None, Report, Page, Column, Group. Default value is "None".

incrementGroup

This attribute determines the name of the group at which the chart expression is recalculated.

The value for this attribute must match the name of a group declared in the JRXML report template.

下表总结了元素 <dataset> 的子元素 -

The following table summarizes the sub-elements of the element <dataset> −

Sub element

Description

<incrementWhenExpression>

The way a chart dataset is incremented can be customized by filtering out unwanted data through the use of this sub element.

<datasetRun>

This contains information required to instantiate a report subdataset.

Dataset Types

特定的数据集类型说明如下 -

Specific dataset types are explained below −

Pie Dataset

饼形图数据集的特征在于以下表达式 -

A pie dataset is characterized by the following expressions −

  1. <keyExpression> − represents the categories that will make up the slices in the pie chart. This expression can return any java.lang.Comparable object.

  2. <valueExpression> − produces the values that correspond to each category/key in the dataset. Values are always java.lang.Number objects.

  3. <labelExpression> − if this expression is missing, the chart will display default labels for each slice in the pie chart. Use this expression, which returns java.lang.String values, to customize the item labels for the pie chart.

  4. <sectionHyperlink> − sets hyperlinks associated with the pie sections.

Category Dataset

类别数据集的特征是 <categorySeries> 元素,其中包含 −

A category dataset is characterized by the <categorySeries> element, which contains −

  1. <seriesExpression> − indicates the name of the series. This expression can return any java.lang.Comparable object.

  2. <categoryExpression> − returns the name of the category for each value inside the series specified by the series expression. Categories are java.lang.Comparable objects.

  3. <valueExpression> − produces the values that correspond to each category in the dataset. Values are always java.lang.Number objects.

  4. <labelExpression> − if this expression is missing, the chart will display default labels for each item in the chart. Use this expression, which returns java.lang.String values, to customize the item labels for the chart.

  5. <itemHyperlink> − sets hyperlinks associated with chart items.

XY Dataset

XY 数据集的特征是 <xySeries> 元素,其中包含 −

An XY dataset is characterized by the <xySeries> element, which contains −

  1. <seriesExpression> − indicates the name of the series. This expression can return any java.lang.Comparable object.

  2. <xValueExpression> − returns the java.lang.Number value representing the X value from the (x, y) pair that will be added to the current data series.

  3. <yValueExpression> − returns the java.lang.Number value representing the Y value from the (x, y) pair that will be added to the current data series.

  4. <labelExpression> − if this expression is missing, the chart will display default labels for each item in the chart. Use this expression, which returns java.lang.String values, to customize the item labels for the chart.

  5. <itemHyperlink> − sets hyperlinks associated with the chart items.

XYZ Dataset

XYZ 数据集的特征是 <xyzSeries> 元素,其中包含 −

An XYZ dataset is characterized by the <xyzSeries> element, which contains −

  1. <seriesExpression> − indicates the name of the series. This expression can return any java.lang.Comparable object.

  2. <xValueExpression> − returns the java.lang.Number value representing the X value from the (x, y, z) item that will be added to the current data series.

  3. <yValueExpression> − returns the java.lang.Number value representing the Y value from the (x, y, z) item that will be added to the current data series.

  4. <zValueExpression> − returns the java.lang.Number value representing the Z value from the (x, y, z) item that will be added to the current data series.

  5. <labelExpression> − if this expression is missing, the chart will display default labels for each item in the chart. Use this expression, which returns java.lang.String values, to customize the item labels for the chart.

  6. <itemHyperlink> − sets hyperlinks associated with the chart items.

Time Series Dataset

时间序列数据集的特征是 timePeriod 属性以及 <timeSeries> 元素。timePeriod 属性指定了数据集中数据系列的类型。时间序列可以包含与天、月、年或其他预定义时间段关联的数字值。可能的值有:年、季度、月、周、日 - 这是默认值、小时、分钟、秒、毫秒。

A time series dataset is characterized by the timePeriod attribute, and the <timeSeries> element. The timePeriod attribute specifies the type of the data series inside the dataset. Time series can contain numeric values associated with days, months, years, or other predefined time periods. Possible values are: Year, Quarter, Month, Week, Day - this is the default value, Hour, Minute, Second, Millisecond.

<timeSeries> 元素包含 −

The <timeSeries> element contains −

  1. <seriesExpression> − indicates the name of the series. This expression can return any java.lang.Comparable object.

  2. <timePeriodExpression> − returns a java.util.Date value from which the engine will extract the corresponding time period depending on the value set for the timePeriod attribute mentioned above.

  3. <valueExpression> − returns the java.lang.Number value to associate with the corresponding time period value when incrementing the current series of the dataset.

  4. <labelExpression> − if this expression is missing, the chart will display default labels for each item in the chart. Use this expression, which returns java.lang.String values, to customize the item labels for the chart.

  5. <itemHyperlink> − sets hyperlinks associated with the chart items.

Time Period Dataset

时间段数据集由<timePeriodSeries>元素表征,其中包含 −

A time period dataset is characterized by the <timePeriodSeries> element, which contains −

  1. <seriesExpression> − indicates the name of the series. This expression can return any java.lang.Comparable object.

  2. <startDateExpression> − specifies the beginning of the date interval with which the numeric value will be associated when it is added to the time period series.

  3. <endDateExpression> − specifies the end of the date interval with which the numeric value will be associated when it is added to the time period series.

  4. <valueExpression> − returns the java.lang.Number value to associate with the current date interval specified by the start date and end date expressions.

  5. <labelExpression> − if this expression is missing, the chart will display default labels for each item in the chart. Use this expression, which returns java.lang.String values, to customize the item labels for the chart.

  6. <itemHyperlink> − sets hyperlinks associated with the chart items.

High Low Dataset

高低数据集由以下表达式表征 −

A high low dataset is characterized by the following expressions −

  1. <seriesExpression> − currently, only one series is supported inside a High-Low or Candlestick chart. However, this single series must be identified by a java.lang.Comparable value returned by this expression, and it must also be used as the series name in the chart’s legend.

  2. <dateExpression> − returns the date to which the current (high, low, open, close, volume) item refers.

  3. <highExpression> − returns a java.lang.Number value, which will be part of the data item added to the series when the dataset gets incremented.

  4. <lowExpression> − returns a java.lang.Number value, which will be part of the data item added to the series when the dataset gets incremented.

  5. <openExpression> − returns a java.lang.Number value, which will be part of the data item added to the series when the dataset gets incremented.

  6. <closeExpression> − returns a java.lang.Number value, which will be part of the data item added to the series when the dataset gets incremented.

  7. <volumeExpression> − a numeric expression that returns the volume value to use for the current data item. It is used only for Candlestick charts.

  8. <itemHyperlink> − sets hyperlinks associated with the chart items.

Value Dataset

这是一种特殊图表数据集实现,包含一个值,且用于渲染计量器和温度计图表。使用<valueExpression>表达式收集值。

This is a special chart dataset implementation that contains a single value and is used for rendering Meter and Thermometer charts. The value is collected using the <valueExpression> expression.

Chart Plots

另一个贯穿所有图表类型的常见JRXML元素是<*plot*>元素。这使我们可以定义图表的多项特征,如方向和背景颜色。根据图表类型,绘图有所不同。

Another common JRXML element through all chart types is the <*plot*> element. This allows us to define several of chart’s characteristics like orientation and background color. Plots differ, based on the type of chart.

Plot Attribute

下表总结了<plot>元素的属性 −

The table given below summarizes the attributes of <plot> element −

Attribute

Description

Values

backcolor

This attribute defines the chart’s background color.

Any six digit hexadecimal value is a valid value for this attribute. The hexadecimal value must be preceded by a #.

orientation

This attribute defines the chart’s orientation.

Horizontal,Vertical Default value is "Vertical"

backgroundAlpha

This attribute defines the transparency of the chart’s background color.

The valid values for this attribute include any decimal number between 0 and 1, inclusive. The higher the number, the less transparent the background will be. Default value is "1."

foregroundAlpha

This attribute defines the transparency of the chart’s foreground colors.

The valid values for this attribute include any decimal number between 0 and 1, inclusive. The higher the number, the less transparent the background will be. Default value is "1."

labelRotation

This attribute allows rotation of text labels on x-axis to rotate clockwise or anti-clockwise. This attribute applies only to charts for which the x axis is not numeric or does not display dates.

Default value is "0.0."

<plot> 元素有一个子元素 <seriesColor>,其属性有:seriesOrder 和 color。此元素自定义系列的颜色及其在颜色序列中的位置。

The <plot> element has a subelement <seriesColor> which attributes are: seriesOrder and color. This element customizes colors for series, and their position within in the color sequence.

Specific Settings for Chart Plots

  1. piePlot − It has no specific settings

  2. pie3DPlot − Contains the depthFactor attribute, a numeric value ranging from 0 to 1 that represents the depth of the pie as a percentage of the height of the plot area.

  3. barPlot − One can show or hide tick labels, tick marks or item labels, and provides settings for both axis.

  4. bar3DPlot − Provides the same settings as the barPlot, and generates a 3D effect using the xOffset and yOffset attributes.

  5. linePlot − One can show or hide lines connecting item points, can show or hide shapes associated with item points, and provides settings for both axis.

  6. scatterPlot − Similar to the linePlot, it can show or hide lines connecting item points, can show or hide shapes associated with item points, and provides settings for both axis.

  7. areaPlot − Provides settings for both axis.

  8. bubblePlot − One can set the bubble dimensions by setting the scaleType attribute, and provides settings for both axis.

  9. timeSeriesPlot − One can show or hide lines connecting item points, can show or hide shapes associated with item points, and provides settings for both axis.

  10. highLowPlot − One can show or hide open ticks, can show or hide close ticks, and provides settings for both axis.

  11. candlestickPlot − One can show or hide the volume, and provides settings for both axis.

  12. meterPlot − Contains specific settings for the dial shape, scale angle, measurement units, tick interval, dial color, needle color, tick color, value display font, color and format pattern, data range, and meter intervals.

  13. thermometerPlot − Contains specific settings for the value location, mercury color, show/hide value lines, value display font, color and format pattern, data range, low range, medium range, and high range.

  14. multiAxisChart − Contains specific settings for axis included in the plot.

Types of Charts

JasperReports 提供对多种图表类型的内置支持。它们如下所列 −

JasperReports offers built-in support for several chart types. They are listed as below −

  1. pieChart − A combination of a Pie dataset and a Pie plot.

  2. pie3DChart − Groups a Pie dataset and a Pie 3D plot.

  3. barChart − A basic combination of a Category dataset and a Bar plot.

  4. bar3DChart − Wraps a Category dataset and a Bar 3D plot.

  5. xyBarChart − Supports Time Period datasets, Time Series datasets, and XY datasets, and uses a Bar plot to render the axis and the items.

  6. stackedBarChart − Uses data from a Category dataset and renders its content using a Bar plot.

  7. stackedBar3DChart − Uses data from a Category dataset and renders its content using a Bar 3D plot.

  8. lineChart − Groups a Category dataset and a Line plot.

  9. xyLineChart − Groups an XY dataset and a Line plot.

  10. areaChart − Items from a Category dataset are rendered using an Area plot.

  11. stackedAreaChart − Items from a Category dataset are rendered using an Area plot.

  12. xyAreaChart − Uses data from an XY dataset and renders it through an Area plot.

  13. scatterChart − Wraps an XY dataset with a Scatter plot.

  14. bubbleChart − Combines an XYZ dataset with a Bubble plot.

  15. timeSeriesChart − Groups a Time Series dataset and a Time Series plot.

  16. highLowChart − A combination of a High-Low dataset and a High-Low plot.

  17. candlestickChart − Uses data from a High-Low dataset but with a special Candlestick plot.

  18. meterChart − Displays a single value from a Value dataset on a dial, using rendering options from a Meter plot.

  19. thermometerChart − Displays the single value in a Value dataset using rendering options from a Thermometer plot.

  20. multiAxisChart − Contains multiple range axes, all sharing a common domain axis.

Example

为了演示图表,我们编写一个新的报表模板 (jasper_report_template.jrxml)。在此,我们将 <*barChart*> 元素添加到 <pageHeader> 部分,将 <*pieChart*> 添加到 <summary> 部分。我们将以图表形式显示每门功课获得的分数。将其保存到目录 C:\tools\jasperreports-5.0.1\test 。该文件的内容如下所述 −

To demonstrate the charts, let’s write a new report template (jasper_report_template.jrxml). Here, we will add the <*barChart*> element to the <pageHeader> section and <*pieChart*> to <summary> section. We would be displaying in charts the marks obtained for each subject. Save it to the directory C:\tools\jasperreports-5.0.1\test. The contents of the file are as given below −

<?xml version = "1.0" encoding = "UTF-8"?>

<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
   http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
   name = "jasper_report_template" pageWidth = "595" pageHeight = "860"
   columnWidth = "515" leftMargin = "40" rightMargin = "40"
   topMargin = "50" bottomMargin = "50">

   <field name = "subjectName" class = "java.lang.String"/>
   <field name = "marks" class = "java.lang.Integer"/>

   <variable name = "countNumber" class = "java.lang.Integer" calculation = "Count">
      <variableExpression>
         <![CDATA[Boolean.TRUE]]>
      </variableExpression>
   </variable>

   <background>
      <band splitType = "Stretch"/>
   </background>

   <title>
      <band height = "79" splitType = "Stretch"/>
   </title>

   <pageHeader>
      <band height = "200">

         <barChart>
            <chart evaluationTime = "Report">
               <reportElement x = "0" y = "0" width = "555" height = "200"/>

               <chartTitle>
                  <titleExpression>
                     <![CDATA["My First JR Bar Chart"]]>
                  </titleExpression>
               </chartTitle>
            </chart>

            <categoryDataset>
               <dataset incrementType = "None"/>

               <categorySeries>
                  <seriesExpression>
                     <![CDATA[$F{subjectName}]]>
                  </seriesExpression>

                  <categoryExpression>
                     <![CDATA[$F{subjectName}]]>
                  </categoryExpression>

                  <valueExpression>
                     <![CDATA[$F{marks}]]>
                  </valueExpression>

               </categorySeries>
            </categoryDataset>

            <barPlot isShowTickMarks = "false">
               <plot/>
            </barPlot>
         </barChart>

      </band>
   </pageHeader>

   <columnHeader>
      <band height = "20" splitType = "Stretch"/>
   </columnHeader>

   <detail>
      <band height = "20" splitType = "Stretch"/>
   </detail>

   <columnFooter>
      <band height = "20" splitType = "Stretch"/>
   </columnFooter>

   <pageFooter>
      <band height = "20" splitType = "Stretch"/>
   </pageFooter>

   <summary>
      <band height = "400" splitType = "Stretch">

         <pieChart>
            <chart evaluationTime = "Report">
               <reportElement x = "135" y = "0" width = "270" height = "300"/>

               <chartTitle>
                  <titleExpression>
                     <![CDATA["My First JR Pie Chart"]]>
                  </titleExpression>
               </chartTitle>
            </chart>

            <pieDataset>
               <dataset incrementType = "None"/>

               <keyExpression>
                  <![CDATA[$F{subjectName}]]>
               </keyExpression>

               <valueExpression>
                  <![CDATA[$F{marks}]]>
               </valueExpression>
            </pieDataset>

            <piePlot>
               <plot/>
               <itemLabel/>
            </piePlot>
         </pieChart>

      </band>
   </summary>

</jasperReport>

以上文件的内容如下所述 −

The details of the above file are as given below −

  1. The JRXML element used to create a bar chart is </barChart> in the <pageHeader>. It contains a </chart> sub-element, which contains a <reportElement> sub-element defining the chart’s dimensions and position.

  2. The <dataset> element in a bar chart must be enclosed between <categoryDataset> and </categoryDataset> JRXML elements.

  3. <categoryDataset> must contain a <categorySeries> element. This element defines what data element the bars will represent (subject names, in this example).

  4. <categoryDataset> must also contain an element, which defines how the data will be separated into categories for comparison. Here, data is separated by subject names.

  5. The <valueExpression> element defines that what expression is used to determine the value of each bar in the chart. Here, we are using "marks".

  6. For the pie chart, we have used the element <pieChart> under the <summary> section. It contains a </chart> sub-element.

  7. The sub-element contains a report expression indicating what to use as a key in the chart. Here, we have used subjectName.

  8. The sub-element contains an expression used to calculate the value for the key. Here, we have used marks.

用于填充报告的 Java 代码保持不变。文件 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java 的内容如下 -

The java codes for report filling remains unchanged. The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java are as given below −

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class JasperReportFill {
   @SuppressWarnings("unchecked")
   public static void main(String[] args) {
      String sourceFileName =
         "C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper";

      DataBeanList DataBeanList = new DataBeanList();
      ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();

      JRBeanCollectionDataSource beanColDataSource = new
         JRBeanCollectionDataSource(dataList);

      Map parameters = new HashMap();

      try {
         JasperFillManager.fillReportToFile( sourceFileName,
            parameters, beanColDataSource);
      } catch (JRException e) {
         e.printStackTrace();
      }
   }
}

由于我们要显示每门功课获得的分数,因此需要更改 POJO。文件 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java 内容如下所述 −

As we would be displaying the marks obtained for each subject, POJO needs to be changed. The file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java contents are as given below −

package com.tutorialspoint;

public class DataBean {
   private String subjectName;
   private Integer marks;

   public String getSubjectName() {
      return subjectName;
   }

   public void setSubjectName(String subjectName) {
      this.subjectName = subjectName;
   }

   public Integer getMarks() {
      return marks;
   }

   public void setMarks(Integer marks) {
      this.marks = marks;
   }

}

甚至文件 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java 的内容也需要按如下所示进行更新 −

Even the contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java need to be updated as given below −

package com.tutorialspoint;

import java.util.ArrayList;

public class DataBeanList {
   public ArrayList<DataBean> getDataBeanList() {
      ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();

      dataBeanList.add(produce("English", 58));
      dataBeanList.add(produce("SocialStudies", 68));
      dataBeanList.add(produce("Maths", 38));
      dataBeanList.add(produce("Hindi", 88));
      dataBeanList.add(produce("Scince", 78));

      return dataBeanList;
   }

   /*
    * This method returns a DataBean object, with subjectName ,
    * and marks set in it.
    */
   private DataBean produce(String subjectName, Integer marks) {
      DataBean dataBean = new DataBean();

      dataBean.setSubjectName(subjectName);
      dataBean.setMarks(marks);

      return dataBean;
   }
}

Report Generation

接下来,让我们使用我们的常规 ANT 构建过程编译和执行上述文件。文件 build.xml(保存在目录 C:\tools\jasperreports-5.0.1\test 中)的内容如下所示。

Next, let’s compile and execute the above files using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are as given below.

导入文件 - baseBuild.xml 从第 Environment Setup 章中获取,并应放置在与 build.xml 相同的目录中。

The import file - baseBuild.xml is picked up from the chapter Environment Setup and should be placed in the same directory as the build.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewFillReport" basedir = ".">
   <import file = "baseBuild.xml" />

   <target name = "viewFillReport" depends = "compile,compilereportdesing,run"
      description = "Launches the report viewer to preview the
      report stored in the .JRprint file.">

      <java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true">
         <arg value = "-F${file.name}.JRprint" />
         <classpath refid = "classpath" />
      </java>
   </target>

   <target name = "compilereportdesing" description = "Compiles the JXML file and
      produces the .jasper file.">

      <taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask">
         <classpath refid = "classpath" />
      </taskdef>

      <jrc destdir = ".">
         <src>
            <fileset dir = ".">
               <include name = "*.jrxml" />
            </fileset>
         </src>

         <classpath refid = "classpath" />
      </jrc>
   </target>

</project>

接下来,让我们打开命令行窗口并转到放置 build.xml 的目录。最后,执行以下命令 ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport 是默认目标) -

Next, let’s open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as follows −

C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml

clean-sample:
   [delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint

compile:
   [mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes
   [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28:
   warning: 'includeantruntime' was not set, defaulting to bu
   [javac] Compiling 3 source files to C:\tools\jasperreports-5.0.1\test\classes

compilereportdesing:
   [jrc] Compiling 1 report design files.
   [jrc] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
   [jrc] log4j:WARN Please initialize the log4j system properly.
   [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig
      for more info.
   [jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK.

run:
   [echo] Runnin class : com.tutorialspoint.JasperReportFill
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

viewFillReport:
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

BUILD SUCCESSFUL
Total time: 19 minutes 45 seconds

以上编译的结果是在屏幕下方打开一个 JasperViewer 窗口−

As a result of above compilation, a JasperViewer window opens up as in the screen below −

report bar chart example
report pie chart example

在此,我们看到条形图是在 pageheader 中创建的,饼图是在 summary 部分中创建的。

Here, we see that the bar chart is created in the pageheader and the pie chart is created in the summary sections.

JasperReports - Crosstabs

交叉表(交叉制表)报告是包含以表格形式排列数据(行和列)的表的报告。Crosstab 对象用于在主报告中插入交叉表报告。交叉表可与任何级别的数据(名义、序数、间隔或比率)协同使用,通常将存储在报告变量中的汇总数据显示为动态表格的形式。变量用于显示汇总数据,如合计、计数、平均值。

Crosstab (cross-tabulation) reports are the reports containing tables that arrange data across rows and columns in a tabular form. Crosstab object is used for inserting a crosstab report within the main report. Crosstabs can be used with any level of data (nominal, ordinal, interval, or ratio), and usually display the summarized data, contained in the report variables, in the form of a dynamic table. Variables are used to display aggregate data such as sums, counts, average values.

Crosstab Properties

JRXML 元素 <*crosstab*> 用于将交叉表插入报告。

JRXML element <*crosstab*> is used to insert a crosstab into a report.

Attribute

以下是一些 <*crosstab*> 元素的属性列表 -

Following is a list of attribute of a <*crosstab*> element −

  1. isRepeatColumnHeaders − Indicates whether the column headers should be reprinted after a page break. The default value is true.

  2. isRepeatRowHeaders − Indicates whether the row headers should be reprinted after a crosstab column break. The default value is true.

  3. columnBreakOffset − When a column break occurs, indicates the amount of vertical space, measured in pixels, before the subsequent crosstab piece to be placed below the previous one on the same page. The default value is 10.

  4. runDirection − Indicates whether the crosstab data should be filled from left to right (LTR) or from right to left (RTL). The default value is LTR.

  5. ignoreWidth − Indicates whether the crosstab will stretch beyond the initial crosstab width limit and don’t generate column breaks. Else it will stop rendering columns within the crosstab width limit and continue with the remaining columns only after all rows have started rendering. The default value is false.

Sub Elements

<crosstab> 元素下有以下子元素 -

A <crosstab> element has following sub elements −

  1. <reportElement> − This element defines the position, width, and height of the crosstab within its enclosing. Attributes for this element include all standard <reportElement> attributes.

  2. <crosstabParameter> − This element is used to access report variables and parameters from within the crosstab. Attributes for this element include − name − This defines the parameter name. class − This indicates the parameter class.

  3. <parametersMapExpression> − This element is used to pass a report variable or parameter containing an instance of java.util.Map, as a set of parameters for the crosstab. This element contains no attributes.

  4. <crosstabDataset> − This element defines the dataset to use to populate the crosstab (see next section for a detailed explanation). Attributes for this element include − isDataPreSorted − This indicates whether the data in the dataset is pre-sorted. Default value is false.

  5. <crosstabHeaderCell> − This element defines the content of the region found at the upper-left corner of the crosstab where column headers and row headers meet. The size of this cell is calculated automatically based on the defined row and column widths and heights.

  6. <rowGroup> − This element defines a group used to split the data into rows. Attributes for this element include − name − This defines the name of the row group. width − This defines the width of the row group. headerPosition − This defines the position of the header contents (Top, Middle, Bottom, Stretch). totalPosition − This defines the position of the entire column (Start, End, None). This element contains the following sub elements − <bucket> <crosstabRowHeader> <crosstabTotalRowHeader>

  7. <columnGroup> − This element defines a group used to split the data into columns. Attributes for this element include − name − This defines the column group name. height − This defines the height of the column group header. headerPosition − This defines the position of the header contents (Right, Left, Center, Stretch). totalPosition − This defines the position of the entire column (Start, End, None). This element contains the following sub elements − <bucket> <crosstabColumnHeader> <crosstabTotalColumnHeader>

  8. <measure> − This element defines the calculation to be performed across rows and columns. Attributes for this element include − name − This defines the measure name. class − This indicates the measure class. calculation − This indicates the calculation to be performed between crosstab cell values. Its values could be any of these - Nothing, Count, DistinctCount, Sum, Average, Lowest, Highest, StandardDeviation, Variance, and First. Default value is Nothing.

  9. <crosstabCell> − This element defines how data in non-header cells will be laid out. Attributes for this element include − columnTotalGroup − This indicates the group to use to calculate the column total. height − This defines the height of the cell. rowTotalGroup − This indicates the group to use to calculate the row total. width − This defines the width of the cell.

  10. <whenNoDataCell> − This element defines what to display on an empty crosstab cell. This element contains no attributes.

Data Grouping in Crosstab

交叉表计算引擎通过遍历关联数据集记录来聚合数据。要聚合数据,首先需要对数据进行分组。在交叉表中,行和列基于特定的组项(称为 buckets )。存储段定义应包含 -

The crosstab calculation engine aggregates data by iterating through the associated dataset records. In order to aggregate data, one needs to group them first. In a crosstab, rows and columns are based on specific group items, called buckets. A bucket definition should contain −

  1. bucketExpression − The expression to be evaluated in order to obtain data group items.

  2. comparatorExpression − Needed in the case the natural ordering of the values is not the best choice.

  3. orderByExpression − Indicates the value used to sort data.

交叉表中的行和列组(上述定义)依赖于 buckets

Row and column groups (defined above) in a crosstab rely on buckets.

Built-In Crosstab Total Variables

下面是按名称命名的变量中可访问的与单元格对应的当前度量值和不同级别的总计列表:

Below is a list of current value of measure and totals of different levels corresponding to the cell can be accessed through variables named according to the following scheme −

  1. The current value of a measure calculation is stored in a variable having the same name as the measure.

  2. <Measure>_<Column Group>_ALL − This yields the total for all the entries in the column group from the same row.

  3. <Measure>_<Row Group>_ALL − This yields the total for all the entries in the row group from the same column.

  4. <Measure>_<Row Group>_<Column Group>_ALL − This yields the combined total corresponding to all the entries in both row and column groups.

Example

为了演示交叉表,让我们编写一个新的报表模板(jasper_report_template.jrxml)。在此处,我们将交叉表添加到摘要部分。将其保存到目录 C:\tools\jasperreports-5.0.1\test 。该文件的具体内容如下:

To demonstrate the crosstabs, let’s write a new report template (jasper_report_template.jrxml). Here, we will add the crosstab to summary section. Save it to the directory C:\tools\jasperreports-5.0.1\test. The contents of the file are as given below −

<?xml version = "1.0" encoding = "UTF-8"?>

<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN"
   "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">

<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
   http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
   name = "jasper_report_template" language = "groovy" pageWidth = "595"
   pageHeight = "842" columnWidth = "555" leftMargin = "20" rightMargin = "20"
   topMargin = "20" bottomMargin = "20">

   <parameter name = "ReportTitle" class = "java.lang.String"/>
   <parameter name = "Author" class = "java.lang.String"/>

   <field name = "name" class = "java.lang.String"/>
   <field name = "country" class = "java.lang.String"/>

   <title>
      <band height = "70">

         <line>
            <reportElement x = "0" y = "0" width = "515" height = "1"/>
         </line>

         <textField isBlankWhenNull = "true" bookmarkLevel = "1">
            <reportElement x = "0" y = "10" width = "515" height = "30"/>

            <textElement textAlignment = "Center">
               <font size = "22"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{ReportTitle}]]>
            </textFieldExpression>

            <anchorNameExpression>
               <![CDATA["Title"]]>
            </anchorNameExpression>
         </textField>

         <textField isBlankWhenNull = "true">
            <reportElement  x = "0" y = "40" width = "515" height = "20"/>

            <textElement textAlignment = "Center">
               <font size = "10"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{Author}]]>
            </textFieldExpression>
         </textField>

      </band>
   </title>

   <summary>
      <band height = "60">

      <crosstab>
         <reportElement width = "782" y = "0" x = "0" height = "60"/>

         <rowGroup name = "nameGroup" width = "100">

            <bucket>
               <bucketExpression class = "java.lang.String">
                  <![CDATA[$F{name}]]>
               </bucketExpression>
            </bucket>

            <crosstabRowHeader>

               <cellContents>
                  <box border = "Thin" borderColor = "black"/>

                  <textField>
                     <reportElement width = "100" y = "0" x = "0" height = "20"/>
                     <textElement textAlignment = "Right"
                        verticalAlignment = "Middle"/>

                     <textFieldExpression>
                        <![CDATA[$V{nameGroup}]]>
                     </textFieldExpression>
                  </textField>

               </cellContents>

            </crosstabRowHeader>

         </rowGroup>

         <columnGroup name = "countryGroup" height = "20">
            <bucket>

               <bucketExpression class = "java.lang.String">
                  $F{country}
               </bucketExpression>
            </bucket>

            <crosstabColumnHeader>
               <cellContents>
                  <box border = "Thin" borderColor = "black"/>
                  <textField isStretchWithOverflow = "true">
                     <reportElement width = "60" y = "0" x = "0" height = "20"/>
                     <textElement verticalAlignment = "Bottom"/>
                     <textFieldExpression>
                        <![CDATA[$V{countryGroup}]]>
                     </textFieldExpression>
                  </textField>
               </cellContents>
            </crosstabColumnHeader>

         </columnGroup>

         <measure name = "tailNumCount" class = "java.lang.Integer"
            calculation = "Count">
            <measureExpression>$F{country}</measureExpression>
         </measure>

         <crosstabCell height = "20" width = "60">
            <cellContents backcolor = "#FFFFFF">
               <box borderColor = "black" border = "Thin"/>
               <textField>
                  <reportElement x = "5" y = "0" width = "55" height = "20"/>
                  <textElement textAlignment = "Left"
                     verticalAlignment = "Bottom"/>
                  <textFieldExpression class = "java.lang.Integer">
                      $V{tailNumCount}
                  </textFieldExpression>
               </textField>
            </cellContents>
         </crosstabCell>

      </crosstab>

      </band>
   </summary>

</jasperReport>

上述文件的详细信息如下:

The details of the above file are as follows −

  1. Crosstab is defined by the <crosstab> element.

  2. <rowGroup> element defines a group to split the data into rows. Here, each row will display data for a different name.

  3. The <bucket> and <bucketExpression> elements define what report expression to use as a group delimiter for <rowGroup>. Here, we used the name field as a delimiter, in order to split the rows by name.

  4. The <crosstabRowHeader> element defines the expression to be used as a row header. It contains a single sub-element, namely <cellContents>, which acts like an inner band inside crosstab. Instead of defining variable name for the text field inside <crosstabRowHeader>, we have assigned the name to <rowGroup> (via its name attribute), hence it creates an implicit variable. The <crosstabRowHeader> element defines the contents of the header cell for the entire row. It takes a single <cellContents> element as its only sub-element.

  5. The <columnGroup> element as well as its sub-elements is analogous to the <rowGroup> element, except that it influences columns instead of rows.

  6. The <measure> element defines the calculation to be performed across rows and columns. The calculation attribute is set to Count.

  7. The <crosstabCell> element defines how data in non-header cells will be laid out. This element also contains a single <crosstabCell> element as its only sub-element.

用于填充报告的 Java 代码保持不变。文件 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java 的内容如下 -

The java codes for report filling remains unchanged. The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java are as given below −

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class JasperReportFill {
   @SuppressWarnings("unchecked")
   public static void main(String[] args) {
      String sourceFileName =
         "C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper";

      DataBeanList DataBeanList = new DataBeanList();
      ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();

      JRBeanCollectionDataSource beanColDataSource =
      new JRBeanCollectionDataSource(dataList);

      Map parameters = new HashMap();
      /**
       * Passing ReportTitle and Author as parameters
       */
      parameters.put("ReportTitle", "List of Contacts");
      parameters.put("Author", "Prepared By Manisha");

      try {
         JasperFillManager.fillReportToFile(
         sourceFileName, parameters, beanColDataSource);
      } catch (JRException e) {
         e.printStackTrace();
      }
   }
}

文件 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java 的内容如下 -

The contents of the POJO file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java are as follows −

package com.tutorialspoint;

public class DataBean {
   private String name;
   private String country;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getCountry() {
      return country;
   }

   public void setCountry(String country) {
      this.country = country;
   }
}

文件 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java 的内容如下 -

The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java are as follows −

package com.tutorialspoint;

import java.util.ArrayList;

public class DataBeanList {
   public ArrayList<DataBean> getDataBeanList() {
      ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();

      dataBeanList.add(produce("Manisha", "India"));
      dataBeanList.add(produce("Dennis Ritchie", "USA"));
      dataBeanList.add(produce("V.Anand", "India"));
      dataBeanList.add(produce("Shrinath", "California"));

      return dataBeanList;
   }

   /**
    * This method returns a DataBean object,
    * with name and country set in it.
    */
   private DataBean produce(String name, String country) {
      DataBean dataBean = new DataBean();
      dataBean.setName(name);
      dataBean.setCountry(country);

      return dataBean;
   }
}

Report Generation

接下来,让我们使用我们的常规 ANT 构建过程编译和执行上述文件。文件 build.xml(保存在目录 C:\tools\jasperreports-5.0.1\test 中)的内容如下所示。

Next, let’s compile and execute the above files using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are as given below.

导入文件 - baseBuild.xml 从第 Environment Setup 章中获取,并应放置在与 build.xml 相同的目录中。

The import file - baseBuild.xml is picked up from the chapter Environment Setup and should be placed in the same directory as the build.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewFillReport" basedir = ".">
   <import file = "baseBuild.xml" />

   <target name = "viewFillReport" depends = "compile,compilereportdesing,run"
      description = "Launches the report viewer to preview the
      report stored in the .JRprint file.">

      <java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true">
         <arg value = "-F${file.name}.JRprint" />
         <classpath refid = "classpath" />
      </java>
   </target>

   <target name = "compilereportdesing" description = "Compiles the JXML file and
      produces the .jasper file.">

      <taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask">
         <classpath refid = "classpath" />
      </taskdef>

      <jrc destdir = ".">
         <src>
            <fileset dir = ".">
               <include name = "*.jrxml" />
            </fileset>
         </src>
         <classpath refid = "classpath" />
      </jrc>

   </target>

</project>

接下来,让我们打开命令行窗口并转到放置 build.xml 的目录。最后,执行以下命令 ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport 是默认目标) -

Next, let’s open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as follows −

C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml

clean-sample:
   [delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper

compile:
   [mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes
   [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28:
   warning: 'includeantruntime' was not set, defaulting to
   [javac] Compiling 3 source files to C:\tools\jasperreports-5.0.1\test\classes

compilereportdesing:
   [jrc] Compiling 1 report design files.
   [jrc] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
   [jrc] log4j:WARN Please initialize the log4j system properly.
   [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig
      for more info.
   [jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK.

run:
   [echo] Runnin class : com.tutorialspoint.JasperReportFill
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

viewFillReport:
   [java] log4j:WARN No appenders could be found for logger (
   net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

BUILD SUCCESSFUL
Total time: 20 minutes 53 seconds

作为上述编译的结果,一个 JasperViewer 窗口会打开,如以下给出的屏幕截图所示 -

As a result of above compilation, a JasperViewer window opens up as shown in the screen given below −

report crosstab example

在这里,我们看到每个国家和名称都被制成表格。

Here, we see that each country and name are tabulated.

JasperReports - Internationalization

有时,我们需要不同语言的报表。针对每种不同的语言编写相同的报表意味很多冗余工作。只有不同于不同语言的文本部分才应该单独编写,并在运行时根据语言环境设置加载到文本元素中。这就是报表国际化的目的。一旦编写了国际化报表,就可以在任何地方运行。

Sometimes, we need reports in different languages. Writing the same report for each different language implies a lot of redundant work. Only pieces of text differing from language to language should be written separately, and loaded into text elements at runtime, depending on locale settings. This is the purpose of the report internationalization. Internationalized reports, once written can run everywhere.

在下面的步骤中,我们列出了如何用不同的语言生成报表以及报表国际化的其他一些特性 -

In the following steps, we have listed how to generate a report in different languages and also some other features of report internationalization −

  1. Associate a resource bundle java.util.ResourceBundle with the report template. There are two ways to associate the java.util.ResourceBundle object with the report template. At design time, by setting the resourceBundle attribute of the report template object to the base name of the target resource bundle. A dynamic/runtime association can be made by supplying a java.util.ResourceBundle object as the value for the REPORT_RESOURCE_BUNDLE parameter at report-filling time. If the report needs to be generated in a locale that is different from the current one, the built-in REPORT_LOCALE parameter can be used to specify the runtime locale when filling the report.

  2. To facilitate report internationalization, a special syntax $R{} is available inside report expressions to reference java.lang.String resources placed inside a java.util.ResourceBundle object associated with the report. The $R{} character syntax extracts the locale-specific resource from the resource bundle based on the key that must be put between the brackets −

<textFieldExpression>
   $R{report.title}
</textFieldExpression>

上面的文本字段通过基于运行时提供的语言环境和 report.title 键从与报表模板关联的资源包中提取 String 值来显示报表的标题。

The above text field displays the title of the report by extracting the String value from the resource bundle associated with the report template based on the runtimesupplied locale and the report.title key.

  1. Formatting messages in different languages based on the report locale, there’s a built-in method inside the reports net.sf.jasperreports.engine.fill.JRCalculator. This method offers functionality similar to the java.text.MessageFormat class. This method, msg(), has three convenient signatures that allow you to use up to three message parameters in the messages.

  2. A built-in str() method (the equivalent of the $R{} syntax inside the report expressions), which gives access to the resource bundle content based on the report locale.

  3. For date and time formatting, the built-in REPORT_TIME_ZONE parameter can be used to ensure proper time transformations.

  4. In the generated output, the library keeps information about the text run direction so that documents generated in languages that have right-to-left writing (like Arabic and Hebrew) can be rendered properly.

  5. If an application relies on the built-in Swing viewer to display generated reports, then it needs to be internationalized by adapting the button ToolTips or other texts displayed. This is very easy to do since the viewer relies on a predefined resource bundle to extract locale-specific information. The base name for this resource bundle is net.sf.jasperreports.view.viewer.

Example

为了演示国际化,让我们编写新的报表模板(jasper_report_template.jrxml)。JRXML 的内容如下所示。将其保存到 C:\tools\jasperreports-5.0.1\test 目录。

To demonstrate internationalization, let’s write new report template (jasper_report_template.jrxml). The contents of the JRXML are as given below. Save it to C:\tools\jasperreports-5.0.1\test directory.

<?xml version = "1.0" encoding = "UTF-8"?>

<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN"
   "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">

<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
   http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
   name = "jasper_report_template" language = "groovy" pageWidth = "595"
   pageHeight = "842" columnWidth = "555" leftMargin = "20" rightMargin = "20"
   topMargin = "20" bottomMargin = "20" resourceBundle = "localizationdemo">

   <title>
      <band height = "552">

         <textField>
            <reportElement positionType = "Float" x = "150" y = "20"
               width = "400" height = "50"/>

            <textElement>
               <font size = "24"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{REPORT_LOCALE}.getDisplayName ($P{REPORT_LOCALE})]]>
            </textFieldExpression>
         </textField>

         <textField isStretchWithOverflow = "true" isBlankWhenNull = "true">
            <reportElement positionType = "Float" x = "20" y = "125"
               width = "530" height = "20"/>

            <textElement textAlignment = "Justified">
               <font size = "14"/>
            </textElement>

            <textFieldExpression class = "java.lang.String">
               <![CDATA[$R{localization.text1}]]>
            </textFieldExpression>

         </textField>

      </band>
   </title>

</jasperReport>

在上面的文件中,<jasperReport> 元素的 resourceBundle 属性告诉 JasperReports 到哪里去获取供报表使用的本地化字符串。我们需要创建一个属性文件,其根名称与该属性值相匹配。填充报表时,此文件必须存在于 CLASSPATH 中的任意位置。在此示例中,属性文件 localizationdemo.properties 保存到目录 C:\tools\jasperreports-5.0.1\test 下。此文件的内容如下 -

In the above file, the resourceBundle attribute of the <jasperReport> element tells JasperReports where to get the localized strings to use for the report. We need to create a property file with a root name matching the value of the attribute. This file must exist anywhere in the CLASSPATH when filling the report. In this example, the property file localizationdemo.properties is saved under the directory C:\tools\jasperreports-5.0.1\test. The contents of this file are as follows −

localization.text1 = This is English text.

要使用不同的语言环境,该文件的文件名必须是 localizationdemo[locale].properties。在此,我们为西班牙语语言环境编写一个文件。将此文件另存为 - C:\tools\jasperreports-5.0.1\test\localizationdemo_es.properties 。此文件的内容如下 -

To use a different locale, the name of the file must be localizationdemo[locale].properties. Here, we will write a file for spanish locale. Save this file as − C:\tools\jasperreports-5.0.1\test\localizationdemo_es.properties. The contents of this file are as follow −

localization.text1 = Este texto es en Español.

获取 resourceBundle 属性值的语法为 $R{key}。

The syntax to obtain the value for resourceBundle properties is $R{key}.

为了让 JasperReports 知道我们希望使用的语言环境,我们需要给内置参数分配一个值。此参数的名称定义为一个常量 REPORT_LOCALE,此常量在 net.sf.jasperreports.engine.JRParameter 类中定义。此常量的值必须是 java.util.Locale 的一个实例。此逻辑被纳入到用于填充和生成报表的 Java 代码中。让我们将此文件 JasperReportFillI18.java 保存到目录 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint 下。该文件的内容如下 -

To let JasperReports know what locale we wish to use, we need to assign a value to a built-in parameter. This parameter’s name is defined as a constant called REPORT_LOCALE, and this constant is defined in the net.sf.jasperreports.engine.JRParameter class. The constant’s value must be an instance of java.util.Locale. This logic is incorporated in java code to fill and generate the report. Let’s save this file JasperReportFillI18.java to C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint directory. The contents of the file are as follows −

package com.tutorialspoint;

import java.util.HashMap;
import java.util.Locale;

import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperFillManager;

public class JasperReportFillI18 {

   public static void main(String[] args) {
      String sourceFileName = "C://tools/jasperreports-5.0.1/test/"
         + "jasper_report_template.jasper";
      HashMap parameterMap = new HashMap();
      if (args.length > 0) {
         parameterMap.put(JRParameter.REPORT_LOCALE, new Locale(args[0]));
      }
      try {
         JasperFillManager.fillReportToFile(sourceFileName, null,
            new JREmptyDataSource());
      } catch (JRException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }

   }
}

Report Generation

我们将使用常规 ANT 构建流程编译并执行上述文件。build.xml 文件(保存在 C:\tools\jasperreports-5.0.1\test 目录下)的内容如下。

We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are as given below.

导入文件 - baseBuild.xml 从第 Environment Setup 章中获取,并应放置在与 build.xml 相同的目录中。

The import file - baseBuild.xml is picked up from the chapter Environment Setup and should be placed in the same directory as the build.xml.

<?xml version = "1.0" encoding = "UTF-8"?>

<project name = "JasperReportTest" default = "viewFillReport" basedir = ".">
   <import file = "baseBuild.xml" />

   <target name = "viewFillReport" depends = "compile,compilereportdesing,run"
      description = "Launches the report viewer to preview the report stored
      in the .JRprint file.">

      <java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true">
         <arg value = "-F${file.name}.JRprint" />
         <classpath refid = "classpath" />
      </java>
   </target>

   <target name = "compilereportdesing" description = "Compiles the JXML file and
      produces the .jasper file.">

      <taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask">
         <classpath refid="classpath" />
      </taskdef>

      <jrc destdir = ".">
         <src>
            <fileset dir = ".">
               <include name = "*.jrxml" />
            </fileset>
         </src>
         <classpath refid = "classpath" />
      </jrc>

   </target>

</project>

接下来,让我们打开命令行窗口并转到放置 build.xml 的目录。最后,执行命令 ant -Dmain-class=com.tutorialspoint.JasperReportFillI18 (viewFullReport 是默认目标),如下所示 -

Next, let’s open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFillI18 (viewFullReport is the default target) as follows −

C:\tools\jasperreports-5.0.1\test>ant  -Dmain-class=com.tutorialspoint.JasperReportFillI18
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml

clean-sample:
   [delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint

compile:
   [mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes
   [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28:
   warning: 'includeantruntime' was not set, defaulting to
   [javac] Compiling 1 source file to C:\tools\jasperreports-5.0.1\test\classes
   [javac] Note: C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\
      JasperReportFillI18.java
   uses unchecked or u
   [javac] Note: Recompile with -Xlint:unchecked for details.

compilereportdesing:
   [jrc] Compiling 1 report design files.
   [jrc] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
   [jrc] log4j:WARN Please initialize the log4j system properly.
   [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig
      for more info.
   [jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK.

run:
   [echo] Runnin class : com.tutorialspoint.JasperReportFillI18
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

viewFillReport:
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

BUILD SUCCESSFUL
Total time: 3 minutes 28 seconds

作为上述编译的结果,一个 JasperViewer 窗口会打开,如以下给出的屏幕截图所示 -

As a result of above compilation, a JasperViewer window opens up as shown in the screen given below −

report i18 example