第十三章 BIRT报表引擎API及报表API (续)-自定义web BIRT展示器

来源:互联网 发布:java杨辉三角形 编辑:程序博客网 时间:2024/05/15 19:59

13.2  自定义BIRT viewer(报表展示器)

前面我们提到了可以通过java定制报表查看器,通过servlet访问webreport,方便系统集成。下面我详细讲解如何实现这个过程

首先实现自定义报表引擎ReportEngine

[java] view plaincopy
  1. package birtbird;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.util.Properties;  
  6. import java.util.logging.Level;  
  7.   
  8. import javax.servlet.ServletContext;  
  9.   
  10. import org.eclipse.birt.core.exception.BirtException;  
  11. import org.eclipse.birt.core.framework.IPlatformContext;  
  12. import org.eclipse.birt.core.framework.Platform;  
  13. import org.eclipse.birt.core.framework.PlatformServletContext;  
  14. import org.eclipse.birt.report.engine.api.EngineConfig;  
  15. import org.eclipse.birt.report.engine.api.EngineConstants;  
  16. import org.eclipse.birt.report.engine.api.IReportEngine;  
  17. import org.eclipse.birt.report.engine.api.IReportEngineFactory;  
  18.   
  19. public class BirtEngine {  
  20.   
  21.     private static IReportEngine birtEngine = null;  
  22.   
  23.     private static Properties configProps = new Properties();  
  24.   
  25.     private final static String configFile = "BirtConfig.properties";  
  26.   
  27.     public static synchronized void initBirtConfig() {  
  28.         loadEngineProps();  
  29.     }  
  30.   
  31.     public static synchronized IReportEngine getBirtEngine(ServletContext sc) {  
  32.         if (birtEngine == null) {  
  33.             EngineConfig config = new EngineConfig();  
  34.             if (configProps != null) {  
  35.                 String logLevel = configProps.getProperty("logLevel");  
  36.                 Level level = Level.OFF;  
  37.                 if ("SEVERE".equalsIgnoreCase(logLevel)) {  
  38.                     level = Level.SEVERE;  
  39.                 } else if ("WARNING".equalsIgnoreCase(logLevel)) {  
  40.                     level = Level.WARNING;  
  41.                 } else if ("INFO".equalsIgnoreCase(logLevel)) {  
  42.                     level = Level.INFO;  
  43.                 } else if ("CONFIG".equalsIgnoreCase(logLevel)) {  
  44.                     level = Level.CONFIG;  
  45.                 } else if ("FINE".equalsIgnoreCase(logLevel)) {  
  46.                     level = Level.FINE;  
  47.                 } else if ("FINER".equalsIgnoreCase(logLevel)) {  
  48.                     level = Level.FINER;  
  49.                 } else if ("FINEST".equalsIgnoreCase(logLevel)) {  
  50.                     level = Level.FINEST;  
  51.                 } else if ("OFF".equalsIgnoreCase(logLevel)) {  
  52.                     level = Level.OFF;  
  53.                 }  
  54.   
  55.                 config.setLogConfig(configProps.getProperty("logDirectory"),  
  56.                         level);  
  57.             }  
  58.   
  59.             config.getAppContext().put(  
  60.                     EngineConstants.APPCONTEXT_CLASSLOADER_KEY,  
  61.                     Thread.currentThread().getContextClassLoader());  
  62.             config.setEngineHome("");  
  63.             IPlatformContext context = new PlatformServletContext(sc);  
  64.             config.setPlatformContext(context);  
  65.   
  66.             try {  
  67.                 Platform.startup(config);  
  68.             } catch (BirtException e) {  
  69.                 e.printStackTrace();  
  70.             }  
  71.   
  72.             IReportEngineFactory factory = (IReportEngineFactory) Platform  
  73.                     .createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);  
  74.             birtEngine = factory.createReportEngine(config);  
  75.   
  76.         }  
  77.         return birtEngine;  
  78.     }  
  79.   
  80.     public static synchronized void destroyBirtEngine() {  
  81.         if (birtEngine == null) {  
  82.             return;  
  83.         }  
  84.         birtEngine.destroy();  
  85.         Platform.shutdown();  
  86.         birtEngine = null;  
  87.     }  
  88.   
  89.     public Object clone() throws CloneNotSupportedException {  
  90.         throw new CloneNotSupportedException();  
  91.     }  
  92.   
  93.     private static void loadEngineProps() {  
  94.         try {  
  95.             // Config File must be in classpath  
  96.             ClassLoader cl = Thread.currentThread().getContextClassLoader();  
  97.             InputStream in = null;  
  98.             in = cl.getResourceAsStream(configFile);  
  99.             configProps.load(in);  
  100.             in.close();  
  101.   
  102.         } catch (IOException e) {  
  103.             e.printStackTrace();  
  104.         }  
  105.   
  106.     }  
  107.   
  108. }  

再其次实现自定义birtviewer selvlet,下面的代码很重要,直接决定了报表展示器的外观

[java] view plaincopy
  1. package birtbird;  
  2. import java.io.ByteArrayOutputStream;  
  3. import java.io.IOException;  
  4. import java.util.ArrayList;  
  5. import java.util.Collection;  
  6. import java.util.Enumeration;  
  7. import java.util.HashMap;  
  8. import java.util.Iterator;  
  9. import java.util.logging.Logger;  
  10. import javax.servlet.ServletContext;  
  11. import javax.servlet.ServletException;  
  12. import javax.servlet.ServletOutputStream;  
  13. import javax.servlet.http.HttpServlet;  
  14. import javax.servlet.http.HttpServletRequest;  
  15. import javax.servlet.http.HttpServletResponse;  
  16. import org.eclipse.birt.report.engine.api.HTMLRenderOption;  
  17. import org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask;  
  18. import org.eclipse.birt.report.engine.api.IParameterDefnBase;  
  19. import org.eclipse.birt.report.engine.api.IReportEngine;  
  20. import org.eclipse.birt.report.engine.api.IReportRunnable;  
  21. import org.eclipse.birt.report.engine.api.IRunAndRenderTask;  
  22. import org.eclipse.birt.report.engine.api.IScalarParameterDefn;  
  23. import org.eclipse.birt.report.engine.api.PDFRenderOption;  
  24. import org.eclipse.birt.report.engine.api.RenderOption;  
  25. public class ReportServlet extends HttpServlet {  
  26.  /** 
  27.   *  
  28.   */  
  29.  private static final long serialVersionUID = 1L;  
  30.  /** 
  31.   * Constructor of the object. 
  32.   */  
  33.  private IReportEngine birtReportEngine = null;  
  34.  protected static Logger logger = Logger.getLogger("org.eclipse.birt");  
  35.  public ReportServlet() {  
  36.   super();  
  37.  }  
  38.  /** 
  39.   * Destruction of the servlet. 
  40.   */  
  41.  public void destroy() {  
  42.   super.destroy();  
  43.   BirtEngine.destroyBirtEngine();  
  44.  }  
  45.  /** 
  46.   * The doGet method of the servlet. 
  47.   *  
  48.   */  
  49.  public void doGet(HttpServletRequest req, HttpServletResponse resp)  
  50.    throws ServletException, IOException {  
  51.   resp.setCharacterEncoding("utf-8");  
  52. try {  
  53.  String reportName = req.getParameter("ReportName");  
  54. String baseUrl = req.getContextPath() + "/webReport?ReportName="  
  55.   + reportName;  
  56. String imgBaseUrl = req.getContextPath() + "/reports/images";  
  57. String outFormat = "html";  
  58. // 处理页面传过来的参数  
  59. HashMap<String, String> paramMap = new HashMap<String, String>();  
  60. Enumeration en = req.getParameterNames();  
  61. while (en.hasMoreElements()) {  
  62.  String pName = (String) en.nextElement();  
  63.  String pValue = req.getParameter(pName);  
  64.  if (pName.equals("O_FORMAT")) {  
  65.   outFormat = pValue;  
  66.  } else {  
  67.   paramMap.put(pName, pValue);  
  68.  }  
  69. }  
  70. ServletContext sc = req.getSession().getServletContext();  
  71. this.birtReportEngine = BirtEngine.getBirtEngine(sc);  
  72. IReportRunnable design = birtReportEngine.openReportDesign(sc  
  73.   .getRealPath("/reports") + "/" + reportName);  
  74. HashMap<String, Object> parameters = new HashMap<String, Object>();  
  75. // 以打开的报表设计文件为参数,创建一个获取参数的对象  
  76. IGetParameterDefinitionTask paramTask = birtReportEngine  
  77.   .createGetParameterDefinitionTask(design);  
  78. // 获取报表设计文件中的参数定义  
  79. Collection paramDefns = paramTask.getParameterDefns(false);  
  80. // 为获取的参数定义赋值  
  81. Iterator iter = paramDefns.iterator();  
  82. while (iter.hasNext()) {  
  83.  IParameterDefnBase pBase = (IParameterDefnBase) iter.next();  
  84.  if (pBase instanceof IScalarParameterDefn) {  
  85.   IScalarParameterDefn paramDefn = (IScalarParameterDefn) pBase;  
  86.   String pName = paramDefn.getName();// 报表参数名称  
  87.   // int pType = paramDefn.getDataType( );  
  88.   String pValue = paramMap.get(pName);// 页面传过来的值  
  89.   if (pValue == null) {  
  90.    pValue = "";  
  91.   } else {  
  92.    baseUrl += "&" + pName + "=" + pValue;  
  93.   }  
  94.   // Object pObject = stringToObject( pType, pValue );  
  95.   parameters.put(pName, pValue);  
  96.  }  
  97. }  
  98. if (outFormat.equals("html")) {// 页面展示  
  99.  resp.setContentType("text/html");  
  100.  HTMLRenderOption htmlOptions = new HTMLRenderOption();  
  101.  htmlOptions.setOutputFormat(RenderOption.OUTPUT_FORMAT_HTML);  
  102.  // setup image directory  
  103.  // HTMLRenderContext renderContext = new HTMLRenderContext();  
  104.  // renderContext.setBaseImageURL(req.getContextPath() +  
  105.  // "/images");  
  106.  // renderContext.setImageDirectory(sc.getRealPath("/images"));  
  107.  // logger.log(Level.FINE, "image directory " +  
  108.  // sc.getRealPath("/images"));  
  109.  // HashMap contextMap = new HashMap();  
  110.  // contextMap.put(EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT,  
  111.  // renderContext);  
  112.  // htmlOptions.setImageDirectory("output/image");  
  113.  // htmlOptions.setMasterPageContent(true);  
  114.  // htmlOptions.setPageFooterFloatFlag(true);  
  115.  ByteArrayOutputStream ostream = new ByteArrayOutputStream();  
  116.  htmlOptions.setOutputStream(ostream);  
  117.  htmlOptions.setHtmlPagination(true);// 加入分页条  
  118.  htmlOptions.setEmbeddable(true);// 去除html、head、body标记  
  119.  IRunAndRenderTask task = birtReportEngine  
  120.    .createRunAndRenderTask(design);  
  121.  if (parameters != null && !parameters.isEmpty()) {  
  122.   task.setParameterValues(parameters);  
  123.   task.validateParameters();  
  124.  }  
  125.  String maxRow = req.getParameter("MaxRowsPerQuery");  
  126.  if (maxRow != null && maxRow.length() > 0) {  
  127.   task.setMaxRowsPerQuery(Integer.parseInt(maxRow));// 设置每次查询最大行数  
  128.  }  
  129.  task.setRenderOption(htmlOptions);  
  130.  task.run();  
  131.  task.close();  
  132.  ServletOutputStream out = resp.getOutputStream();  
  133.  out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");  
  134.  out.println("<html>");  
  135.  out.println("  <head>");  
  136.  out.println("  <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");  
  137.  out.println(" <style type=text/css>");  
  138.  // out.println("  td{border:1px solid #9EBFE0;font-Size:12px;}");  
  139.  // out.println("  th{background-color:#C3D5ED;border:1px solid #9EBFE0;font-Size:12px;font-weight:bold;text-align:center;}");  
  140.  out.println("  img { vertical-align:middle;}");  
  141.  out.println(" </style>");  
  142.  out.println("  </head>");  
  143.  out.println("  <body>");  
  144.  // String ostr = ostream.toString("ISO-8859-1");  
  145.  String ostr = ostream.toString("utf-8");  
  146.  if (ostr.length() > 1048576) {// 大于1M则分好页再传到浏览器端,减少网络流量,减轻浏览器压力  
  147.   ArrayList<Integer> indexArray = new ArrayList<Integer>();  
  148.   for (int i = 0; ostr.indexOf("page separator", i) != -1;) {  
  149.    int index = ostr.indexOf("page separator", i);  
  150.    indexArray.add(index);  
  151.    i = index + 1;  
  152.   }  
  153.   int totalPage = indexArray.size() + 1;  
  154.   int curPage = 1;  
  155.   if (totalPage > 1) {  
  156.    String strCurPage = req.getParameter("PB_PAGE");  
  157.    if (strCurPage != null && strCurPage.length() > 0) {  
  158.     curPage = Integer.parseInt(strCurPage);  
  159.    }  
  160.    if (curPage <= 1) {  
  161.     curPage = 1;  
  162.     int index = indexArray.get(curPage - 1);  
  163.     int subIndex = ostr.lastIndexOf("<", index);  
  164.     ostr = ostr.substring(0, subIndex);  
  165.    } else if (curPage >= totalPage) {  
  166.     curPage = totalPage;  
  167.     int index = indexArray.get(curPage - 2);  
  168.     int subIndex = ostr.indexOf(">", index) + 1;  
  169.     ostr = ostr.substring(subIndex);  
  170.    } else {  
  171.     int beginIndex = indexArray.get(curPage - 2);  
  172.     int bgSubIndex = ostr.indexOf(">", beginIndex) + 1;  
  173.     int endIndex = indexArray.get(curPage - 1);  
  174.     int enSubIndex = ostr.lastIndexOf("<", endIndex);  
  175.     ostr = ostr.substring(bgSubIndex, enSubIndex);  
  176.    }  
  177.   }  
  178.   out.println("<div style= 'width:100%;overflow:auto '>");  
  179.   out.println(ostr);  
  180.   out.println("</div>");  
  181.   out.println("<table width='100%' height='32' border='1' align='left' cellpadding='0' cellspacing='0'>");  
  182.   out.println(" <tr valign='middle' style='background-color:#C3D5ED;'>");  
  183.   out.println("  <td width='10' style='border-width:0px'> </td>");  
  184.   out.println("  <td id='btnFirst' width='20' style='border-width:0px'>");  
  185.   if (curPage > 1) {  
  186.    out.println("  <a href='" + baseUrl  
  187.      + "&PB_PAGE=1'><img src='" + imgBaseUrl  
  188.      + "/icon_page_frist.gif' border='0'></a>");  
  189.   } else {  
  190.    out.println("  <img src='" + imgBaseUrl  
  191.      + "/icon_page_frist1.gif' border='0'>");  
  192.   }  
  193.   out.println("</td>");  
  194.   out.println("  <td id='btnPrev' width='20' style='border-width:0px'>");  
  195.   if (curPage > 1) {  
  196.    out.println("  <a href='" + baseUrl + "&PB_PAGE="  
  197.      + (curPage - 1) + "'><img src='" + imgBaseUrl  
  198.      + "/icon_page_prev.gif' border='0'></a>");  
  199.   } else {  
  200.    out.println("  <img src='" + imgBaseUrl  
  201.      + "/icon_page_prev1.gif' border='0'>");  
  202.   }  
  203.   out.println("</td>");  
  204.   out.println("  <td width='150' style='border-width:0px;font-Size:12px;'>");  
  205.   // out.println(new  
  206.   // String("第".getBytes("utf-8"),"ISO-8859-1")  
  207.   out.println("第"  
  208.     // +"<input id='curPage' type='text' style='width:35px;height:18px;' value='"+curPage+"' readOnly>"+new  
  209.     // String("页".getBytes("utf-8"),"ISO-8859-1")+" ");  
  210.     + "<input id='curPage' type='text' style='width:35px;height:18px;' value='"  
  211.     + curPage + "' readOnly>" + "页" + " ");  
  212.   // out.println(new  
  213.   // String("共".getBytes("utf-8"),"ISO-8859-1")  
  214.   out.println("共"  
  215.     // +"<input id='totalPage' type='text' style='width:35px;height:18px;' value='"+totalPage+"' readOnly>"+new  
  216.     // String("页".getBytes("utf-8"),"ISO-8859-1"));  
  217.     + "<input id='totalPage' type='text' style='width:35px;height:18px;' value='"  
  218.     + totalPage + "' readOnly>" + "页");  
  219.   out.println("  </td>");  
  220.   out.println("  <td id='btnNext' width='20' style='border-width:0px'>");  
  221.   if (curPage < totalPage) {  
  222.    out.println("  <a href='" + baseUrl + "&PB_PAGE="  
  223.      + (curPage + 1) + "'><img src='" + imgBaseUrl  
  224.      + "/icon_page_next.gif' border='0'></a>");  
  225.   } else {  
  226.    out.println("  <img src='" + imgBaseUrl  
  227.      + "/icon_page_next1.gif' border='0'>");  
  228.   }  
  229.   out.println("</td>");  
  230.   out.println("  <td id='btnLast' width='30' style='border-width:0px'>");  
  231.   if (curPage < totalPage) {  
  232.    out.println("  <a href='" + baseUrl + "&PB_PAGE="  
  233.      + totalPage + "'><img src='" + imgBaseUrl  
  234.      + "/icon_page_last.gif' border='0'></a>");  
  235.   } else {  
  236.    out.println("  <img src='" + imgBaseUrl  
  237.      + "/icon_page_last1.gif' border='0'>");  
  238.   }  
  239.   out.println("</td>");  
  240.   out.println("  <td width='140' style='border-width:0px;font-Size:12px;'>");  
  241.   // out.println(new  
  242.   // String("转到第".getBytes("utf-8"),"ISO-8859-1")  
  243.   out.println("转到第"  
  244.     // +"<input id='gotoPage' type='text' style='width:35px;height:18px;' value=''>"+new  
  245.     // String("页".getBytes("utf-8"),"ISO-8859-1"));  
  246.     + "<input id='gotoPage' type='text' style='width:35px;height:18px;' value=''>"  
  247.     + "页");  
  248.   out.println("   <img src='"  
  249.     + imgBaseUrl  
  250.     + "/application_go.png' onclick='javascript:gotoPage()'/></td>");  
  251.   out.println("  <td width='30' style='border-width:0px'><img src='"  
  252.     + imgBaseUrl  
  253.     + "/print.gif' style='cursor:pointer' onclick='window.print()'/></td>");  
  254.   out.println("  <td width='30' style='border-width:0px'><a href='"  
  255.     + baseUrl  
  256.     + "&O_FORMAT=pdf' target='_blank'><img border='0' src='"  
  257.     + imgBaseUrl + "/pdf.gif'/></a></td>");  
  258.   out.println("  <td width='30' style='border-width:0px'><a href='"  
  259.     + baseUrl  
  260.     + "&O_FORMAT=xls' target='_blank'><img border='0' src='"  
  261.     + imgBaseUrl + "/xls.gif'/></a></td>");  
  262.   out.println("  <td width='30' style='border-width:0px'><a href='"  
  263.     + baseUrl  
  264.     + "&O_FORMAT=doc' target='_blank'><img border='0' src='"  
  265.     + imgBaseUrl + "/doc.gif'/></a></td>");  
  266.   out.println("  <td style='border-width:0px'> </td>");  
  267.   out.println(" </tr>");  
  268.   out.println("</table>");  
  269.   out.println("<script type=\"text/javascript\">");  
  270.   out.println(" String.prototype.trim=function(){");  
  271.   out.println("  return this.replace(/(^\\s*)|(<a href="file://\\s*$)/g,''">\\s*$)/g,''</a>);");  
  272.   out.println(" }");  
  273.   out.println(" function gotoPage(){");  
  274.   out.println("  var spage = document.getElementById('gotoPage').value.trim();");  
  275.   out.println("  if(spage=='' || spage.indexOf('.')!=-1 || isNaN(spage)) {");  
  276.   // out.println("   alert('"+new  
  277.   // String("请输入整数".getBytes("utf-8"),"ISO-8859-1")+"');");  
  278.   out.println("   alert('" + "请输入整数" + "');");  
  279.   out.println("   return;");  
  280.   out.println("  }");  
  281.   out.println("  var ipage = parseInt(spage);");  
  282.   out.println("  window.location.href = \"" + baseUrl  
  283.     + "&PB_PAGE=\"+ipage;");  
  284.   out.println(" }");  
  285.   out.println("</script> ");  
  286.  } else { // 在浏览器端用js实现分页,提高访问速度,减轻对服务器的压力  
  287.   out.println("<div style= 'width:100%;overflow:auto '>");  
  288.   out.println(ostr);  
  289.   out.println("</div>");  
  290.   out.println("<table width='100%' height='32' border='1' align='left' cellpadding='0' cellspacing='0'>");  
  291.   out.println(" <tr valign='middle' style='background-color:#C3D5ED;'>");  
  292.   out.println("  <td width='10' style='border-width:0px'> </td>");  
  293.   out.println("  <td id='btnFirst' width='20' style='border-width:0px'><img src='"  
  294.     + imgBaseUrl + "/icon_page_frist1.gif'/></td>");  
  295.   out.println("  <td id='btnPrev' width='20' style='border-width:0px'><img src='"  
  296.     + imgBaseUrl + "/icon_page_prev1.gif'/></td>");  
  297.   out.println("  <td width='150' style='border-width:0px;font-Size:12px;'>");  
  298.   // out.println(new  
  299.   // String("第".getBytes("utf-8"),"ISO-8859-1")+"<input id='curPage' type='text' style='width:35px;height:18px;' readOnly>"+new  
  300.   // String("页".getBytes("utf-8"),"ISO-8859-1")+" ");  
  301.   out.println("第"  
  302.     + "<input id='curPage' type='text' style='width:35px;height:18px;' readOnly>"  
  303.     + "页" + " ");  
  304.   // out.println(new  
  305.   // String("共".getBytes("utf-8"),"ISO-8859-1")+"<input id='totalPage' type='text' style='width:35px;height:18px;' readOnly>"+new  
  306.   // String("页".getBytes("utf-8"),"ISO-8859-1"));  
  307.   out.println("共"  
  308.     + "<input id='totalPage' type='text' style='width:35px;height:18px;' readOnly>"  
  309.     + "页");  
  310.   out.println("  </td>");  
  311.   out.println("  <td id='btnNext' width='20' style='border-width:0px'><img src='"  
  312.     + imgBaseUrl + "/icon_page_next1.gif'/></td>");  
  313.   out.println("  <td id='btnLast' width='30' style='border-width:0px'><img src='"  
  314.     + imgBaseUrl + "/icon_page_last1.gif'/></td>");  
  315.   out.println("  <td width='140' style='border-width:0px;font-Size:12px;'>");  
  316.   // out.println(new  
  317.   // String("转到第".getBytes("utf-8"),"ISO-8859-1")+"<input id='gotoPage' type='text' style='width:35px;height:18px;' value=''>"+new  
  318.   // String("页".getBytes("utf-8"),"ISO-8859-1"));  
  319.   out.println("转到第"  
  320.     + "<input id='gotoPage' type='text' style='width:35px;height:18px;' value=''>"  
  321.     + "页");  
  322.   out.println("   <img src='"  
  323.     + imgBaseUrl  
  324.     + "/application_go.png' onclick='javascript:gotoPage()'/></td>");  
  325.   out.println("  <td width='30' style='border-width:0px'><img src='"  
  326.     + imgBaseUrl  
  327.     + "/print.gif' style='cursor:pointer' onclick='window.print()'/></td>");  
  328.   out.println("  <td width='30' style='border-width:0px'><a href='"  
  329.     + baseUrl  
  330.     + "&O_FORMAT=pdf' target='_blank'><img border='0' src='"  
  331.     + imgBaseUrl + "/pdf.gif'/></a></td>");  
  332.   out.println("  <td width='30' style='border-width:0px'><a href='"  
  333.     + baseUrl  
  334.     + "&O_FORMAT=xls' target='_blank'><img border='0' src='"  
  335.     + imgBaseUrl + "/xls.gif'/></a></td>");  
  336.   out.println("  <td width='30' style='border-width:0px'><a href='"  
  337.     + baseUrl  
  338.     + "&O_FORMAT=doc' target='_blank'><img border='0' src='"  
  339.     + imgBaseUrl + "/doc.gif'/></a></td>");  
  340.   out.println("  <td style='border-width:0px'> </td>");  
  341.   out.println(" </tr>");  
  342.   out.println("</table>");  
  343.   out.println("<script type=\"text/javascript\">");  
  344.   out.println(" var pageArray = [];");  
  345.   out.println(" var div_list = document.getElementsByTagName('div');");  
  346.   out.println(" for(var i=0; i<div_list.length; i++){  ");  
  347.   out.println("  if(div_list[i].innerHTML=='page separator')  {");  
  348.   out.println("   div_list[i].style.display='none';");  
  349.   out.println("   if(pageArray.length==0){");  
  350.   out.println("    pageArray[0] = div_list[i].previousSibling;");  
  351.   out.println("   }");  
  352.   out.println("   pageArray[pageArray.length] = div_list[i].nextSibling;");  
  353.   out.println("  }");  
  354.   out.println(" }");  
  355.   out.println(" function displayPage(ipage){");  
  356.   out.println("  if(pageArray.length==1){");  
  357.   out.println("   ipage = 1;");  
  358.   out.println("   document.getElementById('btnFirst').innerHTML= \"<img src='"  
  359.     + imgBaseUrl  
  360.     + "/icon_page_frist1.gif' style='cursor:default'/>\";");  
  361.   out.println("   document.getElementById('btnPrev').innerHTML = \"<img src='"  
  362.     + imgBaseUrl  
  363.     + "/icon_page_prev1.gif' style='cursor:default'/>\";");  
  364.   out.println("   document.getElementById('btnNext').innerHTML = \"<img src='"  
  365.     + imgBaseUrl  
  366.     + "/icon_page_next1.gif' style='cursor:default'/>\";");  
  367.   out.println("   document.getElementById('btnLast').innerHTML = \"<img src='"  
  368.     + imgBaseUrl  
  369.     + "/icon_page_last1.gif' style='cursor:default'/>\";");  
  370.   out.println("  }else{");  
  371.   out.println("   if(ipage<=1){");  
  372.   out.println("    ipage = 1;");  
  373.   out.println("    document.getElementById('btnFirst').innerHTML= \"<img src='"  
  374.     + imgBaseUrl  
  375.     + "/icon_page_frist1.gif' style='cursor:default'/>\";");  
  376.   out.println("    document.getElementById('btnPrev').innerHTML = \"<img src='"  
  377.     + imgBaseUrl  
  378.     + "/icon_page_prev1.gif' style='cursor:default'/>\";");  
  379.   out.println("    document.getElementById('btnNext').innerHTML = \"<img src='"  
  380.     + imgBaseUrl  
  381.     + "/icon_page_next.gif' style='cursor:pointer' onclick='javascript:nextPage()'/>\";");  
  382.   out.println("    document.getElementById('btnLast').innerHTML = \"<img src='"  
  383.     + imgBaseUrl  
  384.     + "/icon_page_last.gif' style='cursor:pointer' onclick='javascript:lastPage()'/>\";");  
  385.   out.println("   }else if(ipage>=pageArray.length){");  
  386.   out.println("    ipage = pageArray.length;");  
  387.   out.println("    document.getElementById('btnFirst').innerHTML= \"<img src='"  
  388.     + imgBaseUrl  
  389.     + "/icon_page_frist.gif' style='cursor:pointer' onclick='javascript:firstPage()'/>\";");  
  390.   out.println("    document.getElementById('btnPrev').innerHTML = \"<img src='"  
  391.     + imgBaseUrl  
  392.     + "/icon_page_prev.gif' style='cursor:pointer' onclick='javascript:prevPage()'/>\";");  
  393.   out.println("    document.getElementById('btnNext').innerHTML = \"<img src='"  
  394.     + imgBaseUrl  
  395.     + "/icon_page_next1.gif' style='cursor:default'/>\";");  
  396.   out.println("    document.getElementById('btnLast').innerHTML = \"<img src='"  
  397.     + imgBaseUrl  
  398.     + "/icon_page_last1.gif' style='cursor:default'/>\";");  
  399.   out.println("   }else{");  
  400.   out.println("    document.getElementById('btnFirst').innerHTML= \"<img src='"  
  401.     + imgBaseUrl  
  402.     + "/icon_page_frist.gif' style='cursor:pointer' onclick='javascript:firstPage()'/>\";");  
  403.   out.println("    document.getElementById('btnPrev').innerHTML = \"<img src='"  
  404.     + imgBaseUrl  
  405.     + "/icon_page_prev.gif' style='cursor:pointer' onclick='javascript:prevPage()'/>\";");  
  406.   out.println("    document.getElementById('btnNext').innerHTML = \"<img src='"  
  407.     + imgBaseUrl  
  408.     + "/icon_page_next.gif' style='cursor:pointer' onclick='javascript:nextPage()'/>\";");  
  409.   out.println("    document.getElementById('btnLast').innerHTML = \"<img src='"  
  410.     + imgBaseUrl  
  411.     + "/icon_page_last.gif' style='cursor:pointer' onclick='javascript:lastPage()'/>\";");  
  412.   out.println("   }");  
  413.   out.println("  }");  
  414.   out.println("  for(var i=0; i<pageArray.length;i++){");  
  415.   out.println("   if(i==(ipage-1)){");  
  416.   out.println("    pageArray[i].style.display='inline';");  
  417.   out.println("   }else{");  
  418.   out.println("    pageArray[i].style.display='none';");  
  419.   out.println("   }");  
  420.   out.println("  }");  
  421.   out.println("  document.getElementById('curPage').value = ipage;");  
  422.   out.println(" }");  
  423.   out.println(" function firstPage(){");  
  424.   out.println("  displayPage(1);");  
  425.   out.println(" }");  
  426.   out.println(" function prevPage(){");  
  427.   out.println("  var spage = document.getElementById('curPage').value;");  
  428.   out.println("  var ipage = parseInt(spage)-1;");  
  429.   out.println("  displayPage(ipage);");  
  430.   out.println(" }");  
  431.   out.println(" function nextPage(){");  
  432.   out.println("  var spage = document.getElementById('curPage').value;");  
  433.   out.println("  var ipage = parseInt(spage)+1;");  
  434.   out.println("  displayPage(ipage);");  
  435.   out.println(" }");  
  436.   out.println(" function lastPage(){");  
  437.   out.println("  displayPage(pageArray.length);");  
  438.   out.println(" }");  
  439.   out.println(" String.prototype.trim=function(){");  
  440.   out.println("  return this.replace(/(^\\s*)|(<a href="file://\\s*$)/g,''">\\s*$)/g,''</a>);");  
  441.   out.println(" }");  
  442.   out.println(" function gotoPage(){");  
  443.   out.println("  var spage = document.getElementById('gotoPage').value.trim();");  
  444.   out.println("  if(spage=='' || spage.indexOf('.')!=-1 || isNaN(spage)) {");  
  445.   // out.println("   alert('"+new  
  446.   // String("请输入整数".getBytes("utf-8"),"ISO-8859-1")+"');");  
  447.   out.println("   alert('" + "请输入整数" + "');");  
  448.   out.println("   return;");  
  449.   out.println("  }");  
  450.   out.println("  var ipage = parseInt(spage);");  
  451.   out.println("  displayPage(ipage);");  
  452.   out.println(" }");  
  453.   out.println(" document.getElementById('totalPage').value=pageArray.length;");  
  454.   out.println(" firstPage();");  
  455.   out.println("</script> ");  
  456.  }  
  457.  out.println("</body>");  
  458.  out.println("</html>");  
  459.  out.flush();  
  460.  out.close();  
  461.  ostream.close();  
  462. else {// 导出文件  
  463.  RenderOption options;  
  464.  if (outFormat.equals("pdf")) {  
  465.   resp.setContentType("application/pdf");  
  466.   resp.setHeader("Content-Disposition",  
  467.     "attachment; filename=export.pdf");  
  468.   options = new PDFRenderOption();  
  469.   options.setOutputFormat(RenderOption.OUTPUT_FORMAT_PDF);  
  470.  } else {  
  471.   if (outFormat.equals("xls")) {  
  472.    resp.setContentType("application/msexcel");  
  473.    resp.setHeader("Content-disposition",  
  474.      "attachment; filename=export.xls");  
  475.   } else if (outFormat.equals("doc")) {  
  476.    resp.setContentType("application/msword");  
  477.    resp.setHeader("Content-disposition",  
  478.      "attachment; filename=export.doc");  
  479.   } else {  
  480.    resp.setContentType("text/html");  
  481.   }  
  482.   options = new HTMLRenderOption();  
  483.   options.setOutputFormat(RenderOption.OUTPUT_FORMAT_HTML);  
  484.  }  
  485.  options.setOutputStream(resp.getOutputStream());  
  486.  IRunAndRenderTask task = birtReportEngine  
  487.    .createRunAndRenderTask(design);// 不生成document文件  
  488.  if (parameters != null && !parameters.isEmpty()) {  
  489.   task.setParameterValues(parameters);// 设置报表参数  
  490.   task.validateParameters();  
  491.  }  
  492.  task.setRenderOption(options);  
  493.  task.run();  
  494.  task.close();  
  495. }  
  496. catch (Exception e) {  
  497.  e.printStackTrace();  
  498.  throw new ServletException(e);  
  499. }  
  500. }  
  501.  /** 
  502.   * The doPost method of the servlet. 
  503.   *  
  504.   */  
  505.  public void doPost(HttpServletRequest request, HttpServletResponse response)  
  506.    throws ServletException, IOException {  
  507.   this.doGet(request, response);  
  508.  }  
  509.  /** 
  510.   * Initialization of the servlet. 
  511.   *  
  512.   * @throws ServletException 
  513.   *             if an error occure 
  514.   */  
  515.  public void init() throws ServletException {  
  516.   BirtEngine.initBirtConfig();  
  517.  }  
  518. }  

这个servlet其实很简单,就是调用自定义的report engine往客户端输出了HTML格式的报表render显示,还在网客户端打印了一些资源,其中包含一些用于导航的图表文件,放置在report/reports/images下

WEB-INF下面的文件如下:

其中classes放置定制的BirtEngineReportServlet,lib用于放置runtime ReportEngine类库,web.xml内容如下:

[html] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"   
  3. "http://java.sun.com/dtd/web-app_2_3.dtd">  
  4. <web-app id="WebApp">  
  5.         <servlet>  
  6.         <servlet-name>WebReport</servlet-name>  
  7.         <servlet-class>birtbird.ReportServlet</servlet-class>  
  8.     </servlet>  
  9.     <servlet-mapping>  
  10.         <servlet-name>WebReport</servlet-name>  
  11.         <url-pattern>/webReport</url-pattern>  
  12.     </servlet-mapping>  
  13. </web-app>  


这样我们可以访问/report/webReport?ReportName=customerOrders.rptdesign&customerno=114来访问customer.rptdesign,也可以用如下的方式:

[java] view plaincopy
  1. <%@ page contentType="text/html;charset=GBK" %>  
  2. <%@ page import = "javax.servlet.http.*" %>  
  3. <%@ include file="/includes/jsp/init.jsp"%>  
  4. <%   
  5. String report_url = "/report/webReport?ReportName=customerOrders.rptdesign&customerno=114";  
  6. %>  
  7. <script language="javascript">  
  8.     location.href="<%=report_url%>";  
  9. </script>  

源码中我们把报表的访问路径设置成了report/reports下,

customerOrders.rptdesign报表的设计如下:

其中包含参数customerno,默认值是114

在自定义的报表查看器中预览如下(注意导航栏和工具栏在一起,都在下面):

翻到第4

导出的excel

导出的word

实际上我们还能利用报表展示器的扩展点开发一个自定义的eclipse插件类型的报表展示器,这种方式能直接调用BIRT已经封装好的viewer

plugin.xml的内容如下:

[html] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <?eclipse version="3.2"?>  
  3. <plugin>  
  4.    <extension  
  5.          id="application"  
  6.          point="org.eclipse.core.runtime.applications">  
  7.       <application>  
  8.          <run  
  9.                class="org.eclipse.birt.examples.rcpviewer.Application">  
  10.          </run>  
  11.       </application>  
  12.    </extension>  
  13.    <extension  
  14.          point="org.eclipse.ui.perspectives">  
  15.       <perspective  
  16.             name="Perspective"  
  17.             class="org.eclipse.birt.examples.rcpviewer.Perspective"  
  18.             id="org.eclipse.birt.examples.rcpviewer.perspective">  
  19.       </perspective>  
  20.    </extension>  
  21.    <extension  
  22.          point="org.eclipse.ui.views">  
  23.       <view  
  24.             name="View"  
  25.             class="org.eclipse.birt.examples.rcpviewer.View"  
  26.             id="org.eclipse.birt.examples.rcpviewer.view">  
  27.       </view>  
  28.    </extension>  
  29.    <extension  
  30.          point="org.eclipse.birt.report.viewer.appcontext">  
  31.       <appcontext  
  32.             class="org.eclipse.birt.examples.rcpviewer.MyAppContext">  
  33.       </appcontext>  
  34.    </extension>  
  35. </plugin>  

RCP客户端程序最终运行效果如下:


至于如何扩展BIRT报表的API,第十四章会详细描述。

0 0
原创粉丝点击