Jasper Reports 简明教程

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.