第十二章 BIRT報表的部署與配置

12.1 報表的工作模式以及相應的部署和配置

雖然爲了示例的需要,在前文的第二章講過BIRT的配置,以及在文本類報表,網格報表,圖表中用過birt jsp tag,也做過一些說明。但報表的工作模式,不僅僅包含這兩種。實際上,BIRT有五種工作模式,

第一種是用jsp或者javascript訪問url,這個url遵循特定的格式,例如url/frameset?__report=&__paraname=paravalue

第二種方式是在jsp頁面中嵌入birt tag

第三種模式是在servlet或者java class中打開用報表設計器設計的報表,導出一個htmlpdf或者其它格式的文檔的輸出到既定的目錄;

第四種是擴展報表展示器birt web viewer,也即是改寫birt web viewerservlet,配置訪問路徑,並用它來展示先前在報表設計器中設計的報表;

第五種模式即是在java class中利用報表設計API,生成報表設計文檔,並用報表引擎API打開並生成htmlpdf或者其它格式的文檔。

本章先詳細說明前文用到的兩種工作模式,後面的三種,我們會在第十三章及之後的章節詳細描述。

第一種工作模式:url

Url的一個例子如下:

http://localhost:8080/birt/frameset?__report=test.rptdesign&__bookmark=bk&__isreportlet=true

說明:

http://localhost:8080:代表訪問的服務器地址

/birt :代表訪問的app的根目錄

/frameset: 代表訪問的servlet的模式,在web.xml中有配置的說明

__report=test.rptdesign&__bookmark=bk&__isreportlet=true 代表訪問的參數,其中birt保留的參數以兩個下劃線開頭,例如__report指定報表的名稱;__bookmark指定報表的書籤;報表參數不需要以__開頭。

報表訪問servlet的模式,主要有以下幾種:

 frameset ---- 採用Ajax框架,可以顯示工具條,導航條和TOC面板,實現複雜的操作,如分頁處理,導出數據,導出報表,打印等。該模式下會自動生成report document文件(預覽report design文件)到特定的目錄(用戶可以用參數指定,也可以定義在web.xml)。採用Ajax,速度較慢。

run ---- 也採用Ajax框架,但不實現frameset的複雜功能,不會生成臨時的report document文件(預覽report design文件),也不支持分頁,這個主要是應用在BIRT Designer裏的preview tab裏,可以支持cancel操作,其它不怎麼常用。採用Ajax,速度較慢。

preview --- 沒有用到Ajax框架,直接調用底層Engine API對報表進行render,把生成的報表內容直接輸出到瀏覽器。這種模式和run模式調用的是相同的Engine API,唯一區別在於run採用Ajax獲取報表內容,而preview直接輸出到瀏覽器。如果要支持分頁,用戶需要在URL上定義__page__pagerange參數。需要特別說明的是,在這幾種預覽模式中,preview的速度是最快的。

download --- 用於導出報表數據,當你使用frameset工具條裏的導出數據功能時,會用到這個模式。

這個模式會直接調用瀏覽器的下載功能彈出下載框或者調用默認的下載工具打開下載目錄地址指定輸入框。

output --- 該模式類似於frameset,會自動生成report document文件(預覽report design文件),區別在於output不採用Ajax,而是將生成的報表內容直接輸出到瀏覽器。不支持分頁。

下面說說最主要的保留參數的含義:

__report”  定義要預覽的rptdesign文件路徑,支持相對路徑和絕對路徑,相對路徑是相對於web.xml中定義的工作目錄。

__document” 定義要預覽的rptdocument文件路徑,同樣支持相對和絕對路徑。相對路徑是相對於web.xml中定義的工作目錄。在同時定義了__report__document參數時,以__document爲優先,如未找到相應的document文件,纔會從design文件生成document文件(frameset/output)或是直接去render這個design文件(preview/run)

__title”   定義報表顯示的標題。

__showtitle”  是否顯示frameset模式下上方的標題部分。true | false

__toolbar”   是否顯示frameset模式下的工具條。true | false

__navigationbar”  是否顯示frameset模式下的導航條。true | false

__parameterpage”  是否強制彈出或不彈出報表參數對話框。true | false

__format”   輸出報表的格式,默認爲html。現在支持:pdf | doc | xls | postscript | ppt

__locale”   設置Locale信息,如 __locale=zh_CN, 注意必須是國家加語言。

__bookmark”   置頁面要定位的書籤名字。

__page”       指定要輸出的報表頁數,這個依賴於報表的分頁設計(page break)

__pagerange”  指定要輸出的報表頁數範圍。如1,3,5-9

__clean”       BIRT裏臨時生成的一些文件都是和session相關的,比如臨時document文件,還有image文件。這些文件也可以通過session進行管理,這個參數就是指定是否需要在session timeout的時候清除這些臨時文件。默認值是true。 

Document文件夾用於緩存frameset的文檔,session退了之後由系統自動刪除,也可由用戶刪除文件夾,對程序不造成影響。

Logs文件夾用於生成系統出現錯誤時的日誌文件。可以刪除。

Report文件夾用於放置rptdesign文件,也可以放置在根目錄,由url指定

Scriptlib文件夾用於放置用戶自定義的腳本,也可以放置在根目錄,由報表配置

WEB-INF文件夾用於配置報表運行時環境的各個參數,第二章已經有非常詳細的描述,這兒強調一下JNDI的配置

1.tomcat配置jndi連接池

在 {tomcat目錄}\webapps\{項目名}\WEB-INF 中新增context.xml文件,配置代碼如下

  1. <?xml version="1.0" encoding="UTF-8"?><Context> <Resource auth="Container"   name="jdbc/travel_agency" type="javax.sql.DataSource" maxIdle="5" maxWait="-1" driverClassName="com.mysql.jdbc.Driver" username="itravel" password="709394" url="jdbc:mysql://192.168.1.100/travel_agency?useUnicode=true&characterEncoding=UTF-8" maxActive="10"/></Context>  

2.web.xml中加入配置

  1. <resource-ref> <description>Database Source</description> <res-ref-name>jdbc/travel_agency</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth></resource-ref>  

如果weblogic已經配置了連接池(jdbc/myjndi),那麼只需要在\{應用名}\WEB-INF 下新建context.xml用於配置報表訪問JNDI內容如下:

  1. <resource-ref>  
  2. <description>Database Source</description>  
  3. <res-ref-name>jdbc/myjndi</res-ref-name>  
  4. <res-type>javax.sql.DataSource</res-type>  
  5. <res-auth>Container</res-auth>  
  6. </resource-ref>  

第二種工作模式jsp tag

JSP birt tag的一個例子在第五章

  1. <birt:viewer id="birtViewer1"  
  2.                 reportDesign="orders.rptdesign"  
  3.                 baseURL="<%= request.getContextPath( )%>"  
  4.                 pattern="run"  
  5.                 height="367"  
  6.                 width="645"  
  7.                 format="html"  
  8.                 frameborder="false"  
  9.                 isHostPage="false"  
  10.                 isReportlet="true"  
  11.                 showParameterPage="false"  
  12.             >  
  13.             </birt:viewer>  

在\webapps\WebViewerExample\WEB-INF\tlds\birt.tld中有詳細的定義。內容的一小部分如下文所示:

  1. <name>viewer</name>  
  2.         <tag-class>org.eclipse.birt.report.taglib.ViewerTag</tag-class>  
  3.         <body-content>JSP</body-content>  
  4.         <description>  
  5.             The viewer tag is to specify how to import and control BIRT Report Viewer into JSP page.  
  6.             This tag will use Ajax framework to retrieve report content.  
  7.         </description>  
  8.   
  9.         <attribute>  
  10.             <name>id</name>  
  11.             <required>true</required>  
  12.             <rtexprvalue>true</rtexprvalue>  
  13.             <description>  
  14.                 Specifies the current viewer id. It should be unique.  
  15.                 It can contain number,letter or underline.  
  16.             </description>              
  17.         </attribute>    
  18.   
  19.         <attribute>  
  20.             <name>pattern</name>  
  21.             <required>false</required>  
  22.             <rtexprvalue>true</rtexprvalue>  
  23.             <description>  
  24.                 Specifies which servlet pattern to be used to preview report.  
  25.                 Default value is frameset.  
  26.                 ( frameset or run )  
  27.             </description>  
  28.         </attribute>  

在此說明如下:

birt標籤分爲: viewer, report, param,parameterPage,paramDef這四個標籤。

一、viewer標籤

示例:

<birt:viewer  id="1"

             pattern="run"    

             reportDesign="test1.rptdesign"

             position="absolute"

             width="800"

             height="500"

             left="50"

             top="50"

             format="html"

             svg="false">

    <birt:param name="sample" value="abc"/>

    <birt:param name="Cust" value="<%=110%>"/>         

</birt:viewer>

id:  必須指定,

pattern: 不一定 要指定,指定運行使用的servlet, 默認爲frameset

reportDesign:  指定報表文件名

title : 可選,指定報表的標題,其實這不是設計報表的標題,而是報表運行時顯示在報表上面的標題。

isHostPage: 可選,默認爲false,指定報表是否全屏顯示,此屬性設置,則width,height,scrolling 屬性作廢。

scrolling :可選,是否出現滾動條

position: 可選,報表相對於頁面的位置,值爲static | absolute | fixed | relative,如果設置了isHostPage,該屬性作廢。

style : 可選,報表顯示的樣式,沒多說的。,如果設置了isHostPage,該屬性作廢

width,heigth,top,left: 分別設置報表顯示的寬,高,上邊距,左邊距

frameborder :可選,設置報表所在的iframe是否顯示邊框,默認不顯示。值爲yes/no

reportDocument : 可選,指定報表文檔,只支持file:url,這樣的格式。

reportlet : 可選,使用reportDocument ,可指定這個屬性,只是指定reportlet 實例的id, 另frameset不支持此屬性。

bookmark : 可選,指定目標書籤名稱

locale : 指定Locale信息,指定語言環境

svg : 可選,指定是否支持輸出svg格式文檔。

format : 可選,指定報表的輸出格式

pageOverflow : 可選,當輸出格式爲pdf時,指定頁面溢出樣式,0 表示自動,1表示實際大小,2表示適合頁面的大小

pageNum: 可選,指定是否顯示頁碼

pageRange:  指定頁面範圍。當運行文檔文件時指定這個屬性。

resourceFolder : 指定相關的資源文件,默認識別web.xml定義的資源文件夾。

showTitle: 是否顯示報表標題,默認爲true

showToolBar: 是否顯示工具條,默認爲true

showNavigationBar: 是否顯示導航條,默認爲true,但是如果allowPageBreak設置爲false,該屬性作廢。

showParameterPage: 是否顯示參數對話框。默認爲true,

二、report標籤

和view標籤差不多,但是report沒有使用ajax支持,而是直接將內容顯示在頁面。 內部應該使用了preview。

另有一個特別的屬性reportContainer,有兩個可選值,iframe,和div,默認爲iframe. 指定使用report的容器。

其他屬性和view都差不多。

<birt:report id="2"

             reportDesign="test.rptdesign"

             position="absolute"

             width="400"

             height="300"

             left="900"

             top="100"

             format="pdf"

             reportContainer="iframe">

    <birt:param name="sample" value="abc"/>         

</birt:report>    

三、param

報表參數相關的標籤。

name: 指定報表參數名稱

value; 參數值

pattern: 參數格式

displayText: 顯示文字

isLocale: 指定參數是否本地化字符

四、parameterPage

配置參數頁面。

id : 必選。指定參數頁面的id

name : 指定參數頁面name,如果isCustom設置爲true,則此屬性一定要寫,且唯一。

isCustom : 指定是否使用用戶自定義參數頁面。默認爲false;

target : 指定請求打開窗口的位置。

其他屬性與view相似,給個例子:

<birt:parameterPage id="parameterPage"

                pattern="run"

                reportDesign="test.rptdesign"

                target="myiframe"

                width="600"

                height="400"

                format="html"/>

<iframe name="myiframe" width="600" height="400"></iframe>

五、paramDef

這個標籤用來生成參數參數頁面定義的參數的html代碼。

有以下幾個屬性

id,name,value,pattern,displayText,isLocale,title,style,cssClass.

<birt:parameterPage

        id="report2" 

        name="page2"

        reportDesign="test.rptdesign"

        isCustom="true"                  //指定自定義頁面

        pattern="frameset">

        id: <birt:paramDef id="id" name="id" title="這是設置id的區域"/>        

        <br><br>        

        

        sex: <birt:paramDef id="sex" name="sex"/>

        <br><br>        

        <input type="submit" name="submit" value="Sumbit form"/>

        <br><br>        

</birt:parameterPage>

假如你的text報表裏有兩個參數,一個參數爲id,另一個參數爲sex,這時候假如id是一列值,sex是checkbox.

那麼這個參數頁面就會把這個id要選擇的值顯示出來,把sex這個checkbox也顯示出來。

第三種工作模式——在servlet或者java class中打開用報表設計器設計的報表,導出一個htmlpdf或者其它格式的文檔的輸出到既定的目錄;需要新建JAVA project或者java web project,導入report engine庫,也就是birt-runtime-3_7_2\ReportEngine\lib目錄下的包,如下:

爲了便於大家理解,我把啓動平臺,打開報表,關閉平臺分別放置在一個類的三個方法中,並做了相應的註釋:

  1. package birt;  
  2. import org.eclipse.birt.core.framework.Platform;  
  3. import org.eclipse.birt.report.engine.api.EngineConfig;  
  4. import org.eclipse.birt.report.engine.api.HTMLRenderOption;  
  5. import org.eclipse.birt.report.engine.api.IReportEngine;  
  6. import org.eclipse.birt.report.engine.api.IReportEngineFactory;  
  7. import org.eclipse.birt.report.engine.api.IReportRunnable;  
  8. import org.eclipse.birt.report.engine.api.IRunAndRenderTask;  
  9. public class HtmlReport  
  10. {  
  11. IReportEngine engine=null;  
  12. EngineConfig config = null;  
  13.   
  14. HtmlReport ()  
  15. {  
  16. }  
  17. //用於運行報表  
  18. public void runReport()  
  19. {  
  20. try{  
  21. IReportRunnable design = null;  
  22. //Open the report design  
  23. design = engine.openReportDesign("d:\\CustomerOrdersFinal.rptdesign");  
  24. //Create task to run and render the report,  
  25. IRunAndRenderTask task = engine.createRunAndRenderTask(design);  
  26. HTMLRenderOption options = new HTMLRenderOption();  
  27. options.setOutputFileName("D:\\TEST.html");  
  28. options.setOutputFormat("html");  
  29. options.setEmbeddable(true);  
  30. task.setRenderOption(options);  
  31. task.run();  
  32. task.close();  
  33. }catch( Exception ex){  
  34. ex.printStackTrace();  
  35. }  
  36. }  
  37. //用於啓動報表平臺  
  38. public void startPlatform(){  
  39. try{  
  40. config = new EngineConfig( );  
  41. config.setBIRTHome("");//低版本的需要在此指定BIRT engine home地址  
  42. Platform.startup( config );  
  43. IReportEngineFactory factory = (IReportEngineFactory) Platform  
  44. .createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY );  
  45. engine = factory.createReportEngine( config );  
  46. }catch( Exception e){  
  47. e.printStackTrace();  
  48. }  
  49. }  
  50. //用於停止報表平臺  
  51. public void stopPlatform(){  
  52. engine.destroy();  
  53. Platform.shutdown();  
  54. }  
  55. public static void main (String[] args)  
  56. {  
  57. HtmlReport html = new HtmlReport ();  
  58. html.startPlatform();  
  59. System.out.println("Started");  
  60. html.runReport();  
  61. html.stopPlatform();  
  62. System.out.println("Finished");  
  63. }  
  64. }  

其中已經設計好的報表佈局如下:

運行報表,我們會在D盤下看到生成的TEST.html文件,打開內容如下:

第四種工作模式,擴展birt web viewer

首先我們需要改寫birt engine,內容如下:

  1. package birt;  
  2. import java.util.logging.Level;  
  3. import javax.servlet.ServletContext;  
  4. import org.eclipse.birt.core.exception.BirtException;  
  5. import org.eclipse.birt.core.framework.IPlatformContext;  
  6. import org.eclipse.birt.core.framework.Platform;  
  7. import org.eclipse.birt.core.framework.PlatformServletContext;  
  8. import org.eclipse.birt.report.engine.api.EngineConfig;  
  9. import org.eclipse.birt.report.engine.api.HTMLActionHandler;  
  10. import org.eclipse.birt.report.engine.api.HTMLEmitterConfig;  
  11. import org.eclipse.birt.report.engine.api.HTMLServerImageHandler;  
  12. import org.eclipse.birt.report.engine.api.IReportEngine;  
  13. import org.eclipse.birt.report.engine.api.IReportEngineFactory;  
  14.   
  15. public class BirtEngine {  
  16.     private static IReportEngine birtEngine = null;  
  17.     public static synchronized void initBirtConfig() {        
  18.     }  
  19.   
  20.     public static synchronized IReportEngine getBirtEngine(ServletContext sc) {       
  21.         EngineConfig config = new EngineConfig();  
  22.         config.setLogConfig(sc.getRealPath("\\logs"), Level.FINE);    
  23.         config.setEngineHome("");  
  24.         IPlatformContext context = new PlatformServletContext(sc);  
  25.         config.setPlatformContext(context);  
  26.           
  27.         //Register new image handler 解決了讀取圖片時的路徑問題  
  28.         HTMLEmitterConfig emitterConfig = new HTMLEmitterConfig( );  
  29.         emitterConfig.setActionHandler( new HTMLActionHandler( ) );  
  30.         HTMLServerImageHandler imageHandler = new HTMLServerImageHandler( );  
  31.         emitterConfig.setImageHandler( imageHandler );  
  32.         config.getEmitterConfigs( ).put( "html", emitterConfig ); //-NLS-1$  
  33.   
  34.         try {  
  35.             Platform.startup(config);  
  36.         } catch (BirtException e) {  
  37.             e.printStackTrace();  
  38.         }  
  39.   
  40.         IReportEngineFactory factory = (IReportEngineFactory) Platform  
  41.                 .createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);  
  42.         birtEngine = factory.createReportEngine(config);  
  43.         return birtEngine;  
  44.     }  
  45.   
  46.     public static synchronized void destroyBirtEngine() {  
  47.         if (birtEngine == null) {  
  48.             return;  
  49.         }  
  50.         birtEngine.shutdown();  
  51.         Platform.shutdown();  
  52.         birtEngine = null;  
  53.     }  
  54.   
  55.     public Object clone() throws CloneNotSupportedException {  
  56.         throw new CloneNotSupportedException();  
  57.     }     
  58. }  

然後我們在servlet中調用這個自定義的birt engine;

  1. package birt;  
  2. import java.io.IOException;  
  3. import java.io.PrintWriter;  
  4. import java.util.ArrayList;  
  5. import java.util.Collection;  
  6. import java.util.Date;  
  7. import java.util.HashMap;  
  8. import java.util.Iterator;  
  9. import java.util.List;  
  10. import java.util.logging.Logger;  
  11.   
  12. import javax.servlet.ServletContext;  
  13. import javax.servlet.ServletException;  
  14. import javax.servlet.http.HttpServlet;  
  15. import javax.servlet.http.HttpServletRequest;  
  16. import javax.servlet.http.HttpServletResponse;  
  17.   
  18. import org.eclipse.birt.report.engine.api.EngineConstants;  
  19. import org.eclipse.birt.report.engine.api.HTMLRenderContext;  
  20. import org.eclipse.birt.report.engine.api.HTMLRenderOption;  
  21. import org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask;  
  22. import org.eclipse.birt.report.engine.api.IParameterDefnBase;  
  23. import org.eclipse.birt.report.engine.api.IReportEngine;  
  24. import org.eclipse.birt.report.engine.api.IReportRunnable;  
  25. import org.eclipse.birt.report.engine.api.IRunAndRenderTask;  
  26. import org.eclipse.birt.report.engine.api.IScalarParameterDefn;  
  27.   
  28. public class birtServlet extends HttpServlet {  
  29.   
  30.       
  31.     private static final long serialVersionUID = 1L;  
  32.     private IReportEngine birtReportEngine = null;  
  33.     protected static Logger logger = Logger.getLogger("org.eclipse.birt");  
  34.   
  35.     public birtServlet () {  
  36.         super();  
  37.     }  
  38.   
  39.     public void destroy() {  
  40.         super.destroy();  
  41.         BirtEngine.destroyBirtEngine();  
  42.     }  
  43.   
  44.     public void doGet(HttpServletRequest req, HttpServletResponse resp)  
  45.             throws ServletException, IOException {  
  46.   
  47.         HashMap parmDetails = new HashMap();  
  48.   
  49.           
  50.         // get report name and launch the engine  
  51.         resp.setContentType("text/html");  
  52.         // resp.setContentType( "application/pdf" );  
  53.         // resp.setHeader ("Content-Disposition","inline; filename=test.pdf");  
  54.         //得到參數並放入paramsList集合  
  55.         String reportName = req.getParameter("ReportName");  
  56.         String bm = new String(req.getParameter("bm").getBytes("ISO8859_1"),"GB2312");  
  57.         String sj1 = req.getParameter("sj1");  
  58.         String sj2 = req.getParameter("sj2");  
  59.         List paramsList = new ArrayList();  
  60.         if (bm != null && !bm.equals("") && !bm.equals("null"))  
  61.             paramsList.add(bm);  
  62.         paramsList.add(sj1);  
  63.         paramsList.add(sj2);  
  64.           
  65.         ServletContext sc = req.getSession().getServletContext();  
  66.         this.birtReportEngine = BirtEngine.getBirtEngine(sc);  
  67.           
  68.         // 設置圖片地址  
  69.         HTMLRenderContext renderContext = new HTMLRenderContext();  
  70.         renderContext.setBaseImageURL(req.getContextPath() + "\\report\\images");  
  71.         renderContext.setImageDirectory(sc.getRealPath("\\report\\images"));  
  72.   
  73.         //logger.log(Level.FINE, "image directory "  
  74.         //      + sc.getRealPath("\\report\\images"));  
  75.         //System.out.println(renderContext.getBaseImageURL());  
  76.         //System.out.println(renderContext.getImageDirectory());  
  77.   
  78.         HashMap<String, HTMLRenderContext> contextMap = new HashMap<String, HTMLRenderContext>();  
  79.         contextMap.put(EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT,  
  80.                 renderContext);  
  81.   
  82.         IReportRunnable design;  
  83.         try {  
  84.             // Open report design  
  85.             design = birtReportEngine.openReportDesign(sc  
  86.                     .getRealPath("")  
  87.                     + "\\" + reportName);  
  88.               
  89.             //以下是將報表裏的參數和傳遞進來的參數匹配然後放到parmDetails集合中  
  90.             IGetParameterDefinitionTask taskParam = birtReportEngine.createGetParameterDefinitionTask( design );  
  91.             Collection params = taskParam.getParameterDefns( true );  
  92.   
  93.             Iterator iter = params.iterator();  
  94.             Iterator iterList = paramsList.iterator();  
  95.             // Iterate over all parameters  
  96.             while ( iter.hasNext() && iterList.hasNext() )  
  97.             {  
  98.                 IParameterDefnBase param = (IParameterDefnBase) iter.next( );  
  99.                 // Parameters are not in a group  
  100.                 IScalarParameterDefn scalar = (IScalarParameterDefn) param;  
  101.                 if(scalar.getName().equals("bm")){  
  102.                     String paramList = (String)iterList.next();  
  103.                     parmDetails.put( scalar.getName(),paramList);  
  104.                     //System.out.println(scalar.getName() + " " + paramList);  
  105.                 }else{  
  106.                     Date paramList = new Date();  
  107.                     parmDetails.put( scalar.getName(),paramList);  
  108.                     //System.out.println(scalar.getName() + " " + paramList);  
  109.                 }  
  110.             }  
  111.             taskParam.close();  
  112.             //  
  113.               
  114.             // create task to run and render report  
  115.             IRunAndRenderTask task = birtReportEngine  
  116.                     .createRunAndRenderTask(design);  
  117.             task.setAppContext(contextMap);  
  118.             task.setParameterValues(parmDetails);  
  119.   
  120.             // set output options  
  121.             HTMLRenderOption options = new HTMLRenderOption();  
  122.             options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_HTML);  
  123.             // options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_PDF);  
  124.             options.setOutputStream(resp.getOutputStream());  
  125.             task.setRenderOption(options);  
  126.   
  127.             // 運行報表  
  128.             task.run();  
  129.             task.close();  
  130.         } catch (Exception e) {  
  131.   
  132.             e.printStackTrace();  
  133.             throw new ServletException(e);  
  134.         }  
  135.     }  
  136.   
  137.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  138.             throws ServletException, IOException {  
  139.           
  140.     }  
  141.   
  142.     public void init() throws ServletException {  
  143.     }  
  144. }  

最後,配置birt engine的訪問地址,在web.xml中配置如下:

  1. <servlet>  
  2.         <servlet-name>birtServlet </servlet-name>  
  3.         <servlet-class>birt.birtServlet</servlet-class>  
  4.     </servlet>  
  5.       
  6.     <servlet-mapping>  
  7.         <servlet-name>birtServlet </servlet-name>  
  8.         <url-pattern>/myBirtFrame</url-pattern>  
  9.     </servlet-mapping>  

這樣,我們可以以這樣的方式訪問自己的birt viewer

http://localhost:8080/birt/myBirtFrame?ReportName=CustomerOrdersFinal.rptdesign

注意:如果是在linux或者unix環境運行,則以上地址的”\\”都必須改成”/”,windowslinux的區別,大家都懂的。

以上參數的訪問方式也是需要完善的,後面的章節會詳細講解如何擴展birt web viewer

第五種方式,運用報表設計API產生報表,運行並輸出報表。

下面是一個簡單的案例

  1. package birt;  
  2. import java.io.IOException;  
  3. import org.eclipse.birt.core.framework.Platform;  
  4. import org.eclipse.birt.report.model.api.CellHandle;  
  5. import org.eclipse.birt.report.model.api.DesignConfig;  
  6. import org.eclipse.birt.report.model.api.DesignElementHandle;  
  7. import org.eclipse.birt.report.model.api.ElementFactory;  
  8. import org.eclipse.birt.report.model.api.GridHandle;  
  9. import org.eclipse.birt.report.model.api.IDesignEngine;  
  10. import org.eclipse.birt.report.model.api.IDesignEngineFactory;  
  11. import org.eclipse.birt.report.model.api.ImageHandle;  
  12. import org.eclipse.birt.report.model.api.LabelHandle;  
  13. import org.eclipse.birt.report.model.api.ReportDesignHandle;  
  14. import org.eclipse.birt.report.model.api.RowHandle;  
  15. import org.eclipse.birt.report.model.api.SessionHandle;  
  16. import org.eclipse.birt.report.model.api.activity.SemanticException;   
  17. import com.ibm.icu.util.ULocale;  
  18. public class SimpleCreate {   
  19.   
  20.        public static void main( String[] args )  
  21.        {  
  22.            try  
  23.            {  
  24.                buildReport( );  
  25.            }  
  26.            catch( IOException e )  
  27.            {  
  28.                e.printStackTrace();  
  29.            }  
  30.            catch( SemanticException e )  
  31.            {  
  32.                e.printStackTrace();  
  33.            }  
  34.        }  
  35.           
  36.        // This method shows how to build a very simple BIRT report with a  
  37.        // minimal set of content: a simple grid with an image and a label.  
  38.           
  39.        static void buildReport() throws IOException, SemanticException  
  40.        {  
  41.            // Create a session handle. This is used to manage all open designs.  
  42.            // Your app need create the session only once.  
  43.               
  44.            //Configure the Engine and start the Platform   
  45.            DesignConfig config = new DesignConfig( );  
  46.   
  47.            config.setProperty("BIRT_HOME""E:\\birt漢化包\\birt-runtime-3_7_2\\ReportEngine");  
  48.            IDesignEngine engine = null;  
  49.            try  
  50.            {  
  51.                Platform.startup( config );  
  52.                IDesignEngineFactory factory = (IDesignEngineFactory) Platform.createFactoryObject( IDesignEngineFactory.EXTENSION_DESIGN_ENGINE_FACTORY );  
  53.                engine = factory.createDesignEngine( config );  
  54.            }  
  55.            catch( Exception ex )  
  56.            {  
  57.                ex.printStackTrace();  
  58.            }          
  59.                       
  60.            SessionHandle session = engine.newSessionHandle( ULocale.ENGLISH ) ;  
  61.               
  62.            // Create a new report design.  
  63.            ReportDesignHandle design = session.createDesign( );  
  64.               
  65.            // The element factory creates instances of the various BIRT elements.  
  66.            ElementFactory efactory = design.getElementFactory( );  
  67.               
  68.            // Create a simple master page that describes how the report will appear when printed.  
  69.            //  
  70.            // Note: The report will fail to load in the BIRT designer unless you create a master page.  
  71.            DesignElementHandle element = efactory.newSimpleMasterPage( "Page Master" );   
  72.            design.getMasterPages( ).add( element );  
  73.               
  74.            // Create a grid and add it to the "body" slot of the report design.  
  75.            GridHandle grid = efactory.newGridItem( null2 /* cols */1 /* row */ );  
  76.         design.getBody( ).add( grid );  
  77.               
  78.            // Note: Set the table width to 100% to prevent the label  
  79.            // from appearing too narrow in the layout view.  
  80.            grid.setWidth( "100%" );   
  81.               
  82.            // Get the first row.  
  83.            RowHandle row = (RowHandle) grid.getRows( ).get( 0 );  
  84.               
  85.            // Create an image and add it to the first cell.  
  86.            ImageHandle image = efactory.newImage( null );  
  87.            CellHandle cell = (CellHandle) row.getCells( ).get( 0 );  
  88.            cell.getContent( ).add( image );  
  89.      image.setURL( "\"https://img-my.csdn.net/uploads/201301/09/1357690895_3463.png\"" );   
  90.               
  91.            // Create a label and add it to the second cell.  
  92.            LabelHandle label = efactory.newLabel( null );  
  93.            cell = (CellHandle) row.getCells( ).get( 1 );  
  94.            cell.getContent( ).add( label );  
  95.            label.setText( "Hello, world!" );   
  96.               
  97.            // Save the design and close it.  
  98.            design.saveAs( "d:\\sample.rptdesign" );   
  99.            design.close( );  
  100.            System.out.println("Finished");  
  101.               
  102.            // We're done!  
  103.        }  
  104.     }   

運行,我們即可在D盤看到sample.rptdesign

在設計器中預覽這個報表,我們看到:

打開並展示報表見第三種報表運行模式,後面章節會更詳細的講解如何運用報表API生成報表設計文件,並運行產生輸出。

 

發佈了57 篇原創文章 · 獲贊 3 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章