JasperReports - 國際化



有時,我們需要不同語言的報表。為每種不同的語言編寫相同的報表意味著大量冗餘工作。只有語言之間不同的文字片段應該單獨編寫,並在執行時根據區域設定載入到文字元素中。這就是報表國際化的目的。國際化的報表,一旦編寫完畢,就可以在任何地方執行。

在以下步驟中,我們列出瞭如何生成不同語言的報表以及報表國際化的其他一些功能:

  • 將資源包java.util.ResourceBundle與報表模板關聯。有兩種方法可以將java.util.ResourceBundle物件與報表模板關聯。

    • 在設計時,透過將報表模板物件的resourceBundle屬性設定為目標資源包的基名稱。

    • 可以在報表填充時,提供一個java.util.ResourceBundle物件作為REPORT_RESOURCE_BUNDLE引數的值,從而實現動態/執行時關聯。

    • 如果報表需要在與當前區域設定不同的區域設定中生成,則可以使用內建的REPORT_LOCALE引數在填充報表時指定執行時區域設定。

  • 為了方便報表國際化,在報表表示式中可以使用特殊的語法$R{}來引用放置在與報表關聯的java.util.ResourceBundle物件中的java.lang.String資源。$R{}字元語法根據必須放在括號中的鍵從資源包中提取特定於區域設定的資源:

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

上面的文字欄位透過根據執行時提供的區域設定和report.title鍵從與報表模板關聯的資源包中提取String值來顯示報表的標題。

  • 根據報表區域設定格式化不同語言的訊息,報表中有一個內建方法net.sf.jasperreports.engine.fill.JRCalculator。此方法提供的功能類似於java.text.MessageFormat類。此方法msg()具有三個方便的簽名,允許您在訊息中使用最多三個訊息引數。

  • 一個內建的str()方法(報表表示式中$R{}語法的等效項),它允許根據報表區域設定訪問資源包內容。

  • 對於日期和時間格式化,可以使用內建的REPORT_TIME_ZONE引數來確保正確的時區轉換。

  • 在生成的輸出中,庫會保留有關文字執行方向的資訊,以便可以正確呈現以從右到左書寫語言(如阿拉伯語和希伯來語)生成的文件。

  • 如果應用程式依賴於內建的Swing檢視器來顯示生成的報表,則需要透過調整按鈕工具提示或顯示的其他文字來對其進行國際化。這很容易做到,因為檢視器依賴於預定義的資源包來提取特定於區域設定的資訊。此資源包的基名稱為net.sf.jasperreports.view.viewer.

示例

為了演示國際化,讓我們編寫新的報表模板(jasper_report_template.jrxml)。JRXML的內容如下所示。將其儲存到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" 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下。此檔案的內容如下:

localization.text1 = This is English text.

要使用不同的區域設定,檔名稱必須為localizationdemo[locale].properties。在這裡,我們將為西班牙語區域設定編寫一個檔案。將此檔案儲存為:C:\tools\jasperreports-5.0.1\test\localizationdemo_es.properties。此檔案的內容如下:

localization.text1 = Este texto es en Español.

獲取resourceBundle屬性值的語法為$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目錄。檔案內容如下:

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();
      }

   }
}

報表生成

我們將使用常規的ANT構建過程編譯並執行上述檔案。檔案build.xml(儲存在目錄C:\tools\jasperreports-5.0.1\test下)的內容如下所示。

匯入檔案 - baseBuild.xml 從章節環境設定中獲取,應該放在與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是預設目標)如下:

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視窗,如下圖所示:

Jasper Report Example
廣告