• EMP框架下使用ireport生成PDF报表


    使用宇信EMP的人现在貌似挺小众的,不过不影响,我想大多数情况下,不管什么框架下都是可以通用的。

    本人开发环境:JDK1.4+weblogic8.0

    1.需要的jar包:jasperreports-1.1.1.jar、itext-1.3.1.jar、itextasian.jar、jdt-compiler-3.1.1.jar

    2.必不可少的工具是报表神器ireport (http://www.onlinedown.net/soft/176160.htm)。关于如何利用ireport生成jrxml,我这不多说,教程地址 http://www.doc88.com/p-317622550528.html  在这里  我们只需要得到一个简单的***.jrxml文件就行。

    3.下载页面:

    <html>
    <head>
    </head>
    <body>
    <a href="creatPdfFile.do">生成PDF报表</a>
    </body>
    </html>

    4.获取数据action 下面把最后调用生成方法的JSP页面贴出来,获取数据的过程省略。

    <%@ page contentType="text/html;charset=GBK" %><%@ page import="java.util.*" %><%@page import="com.bos.cash.action.account.Czg111CreatPDF"%><%@page import="com.ecc.emp.core.*"%><%@page import="com.ecc.emp.data.*"%><%@page import="com.bos.cash.init.SystemHelper"%>
    <%    
        Context context = (Context) request.getAttribute("context");
        Map p = new HashMap();
        List list = new ArrayList();
        p.put("PRINT_DATE",SystemHelper.getServerTime("yyyy-MM-dd HH:mm:ss"));
        p.put("LOGO",Czg111CreatPDF.getFilePath("bankofshanghai-logo.jpg"));
        p.put("SEAL",Czg111CreatPDF.getFilePath("bankofshanghai-receiptseal.gif"));
        IndexedCollection indexedCollection = (IndexedCollection) context.getDataElement("ECInfoSession");
        String checkListStr = (String)context.getDataValue("PrintCode");
        String[] checkList = checkListStr.split("@");
        for(int i = 0;i < checkList.length-1;i++){
            for(int j = 0;j<indexedCollection.size();j++){
                KeyedCollection indexedCollectionKC = (KeyedCollection) indexedCollection.get(j);
                String no = (String)indexedCollectionKC.getDataValue("ECBillCode");
                if(no.equals(checkList[i+1])){
                    list.add(no);
                }
            }
        }
    //上面的代码全部是对数据的操作 无需理睬 最终其作用的是下面这句方法的调用。
    //makePdfReport第一个参数为传过去需要生成报表的jasper文件名,第二个参数为MAP集合,在ireport中为单个字段,
    //第三个参数
    indexedCollection 为EMP框架内的List集合类型,在后面的操作中需要将他解析。第四个参数List,过滤第三个参数的集合参照,无需理会。
    //第四个参数pageContext,jsp内置对象,第四个参数,
    Czg111CreatPDF.makePdfReport("Receipt",p,indexedCollection,pageContext,list); %>

    5.生成PDF文件的JAVA类  大体流程是 获取jrxml文件--编译成jasper文件--生成PDF报表

    Czg111CreatPDF.java

    package com.bos.cash.action.account;
    
    import java.io.File;
    import java.io.IOException;
    import java.io.Serializable;
    import java.text.SimpleDateFormat;
    import java.util.Collection;
    import java.util.Date;
    import java.util.List;
    import java.util.Map;
    
    import javax.servlet.ServletOutputStream;
    import javax.servlet.ServletResponse;
    import javax.servlet.jsp.PageContext;
    
    import net.sf.jasperreports.engine.JRDataSource;
    import net.sf.jasperreports.engine.JRException;
    import net.sf.jasperreports.engine.JasperCompileManager;
    import net.sf.jasperreports.engine.JasperExportManager;
    import net.sf.jasperreports.engine.JasperFillManager;
    import net.sf.jasperreports.engine.JasperPrint;
    import net.sf.jasperreports.engine.JasperRunManager;
    import net.sf.jasperreports.engine.util.JRProperties;
    
    import com.bos.cash.action.zxxt.AccAcountReportFile;
    
    /**
     * ireport报表生成类
     * @author 夏星
     *
     */
    
    public class Czg111CreatPDF implements Serializable {
        
        private static final long serialVersionUID = 1L;
    
        /**
         * 生成PDF
         * @param fileName
         * @param para
         * @param resultset
         * @param page
         * @return
         * @throws JRException
         */
          public static byte[] makePdfReport(String fileName, Map para, Collection resultset, PageContext page,List list) throws JRException
          {
            if (page == null) return null;
            ServletResponse response = page.getResponse();
            String jasperf = getAddress01(fileName);
            response.reset();
            if (jasperf == null) {
                return null;
              }
            File reportF = new File(jasperf);
            if (reportF == null) {
              return null;
            }
            JRDataSource jrds = getJRData(resultset,list);
                
            byte[] bytes = null;
            try {
                bytes = JasperRunManager.runReportToPdf(reportF.getPath(), para, jrds);
            } catch (JRException e1) {
                e1.printStackTrace();
            }
            
            String contentType = "application/pdf";
            response.setContentType(contentType);
            response.setContentLength(bytes.length);
           
            try {
              ServletOutputStream ouputStream = response.getOutputStream();
              ouputStream.write(bytes, 0, bytes.length);
              ouputStream.flush();
              ouputStream.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
            return bytes;
            
          }
          
          /**
           * 解析数据
           * @param resultset
           * @return
           */
          private static JRDataSource getJRData(Collection resultset,List list)
          {
            Czg111JRData data1 = new Czg111JRData();
            data1.setBeans(resultset,list);
            return data1;
          }
          
          /**
           * 获取jasper路径
           * @param fileName 文件名
           * @return locleFilePath jasper绝对路径
           */
          public static String getAddress01 (String fileName){
              
            String bash=AccAcountReportFile.class.getResource("").getFile();
            String bash2[] = bash.split("WEB-INF");
            String locleFilePath = bash2[0]+"WEB-INF/jasper/"+fileName+".jrxml";
            
    // 将jrxml文件编译成jasper文件  生产中直接使用编译后的jasper文件  ps:此项目中commons-digester.jar包版本过低
    // 编译jrxml需要commons-digester-1.7.jar包
            String jasperf = "";
            JRProperties.setProperty("net.sf.jasperreports.compiler.classpath", bash2[0]+"WEB-INF/lib/jasperreports-1.1.1.jar");
            JRProperties.setProperty("net.sf.jasperreports.compiler.temp.dir", bash2[0]+"WEB-INF/");
            
            try {
                jasperf = JasperCompileManager.compileReportToFile(locleFilePath);
            } catch (JRException e) {
                e.printStackTrace();
            }
            
            return jasperf;
          }
          
          /**
           * 获取文件绝对路径
           * @param fileName 文件名(加后缀)
           * @return
           */
          public static String getFilePath(String fileName){
              String bash=AccAcountReportFile.class.getResource("").getFile();
              String bash2[] = bash.split("WEB-INF");
              String locleFilePath = bash2[0]+"images/"+fileName;
              return locleFilePath;
          }
          
          /**
             * 下载PDF
             * @param fileName
             * @param para
             * @param resultset
             * @param page
             * @return
             * @throws JRException
             */
              public static String[] downloadPdf(String fileName, Map para, Collection resultset, PageContext page,List list) throws JRException
              {
                JasperPrint jasperPrint = null;
                String jasperf = getAddress01(fileName);
                File reportF = new File(jasperf);
                JRDataSource jrds = getJRData(resultset,list);
                try {
                    jasperPrint = JasperFillManager.fillReport(reportF.getPath(), para, jrds);
                } catch (JRException e1) {
                    e1.printStackTrace();
                }
                 String localPath = AccAcountReportFile.class.getResource("").getFile();
                 String localPathArray[] = localPath.split("WEB-INF");
                 String locleFilePath = localPathArray[0]+"WEB-INF/jasper";
                 
                 String fileNames = fileName+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".pdf";       
                 File fi = new File(locleFilePath+"/pdf");  
                 if(!fi.exists()){  
                    fi.mkdir();  
                 }             
                    //生成方法1
    //                JRPdfExporter exporter = new JRPdfExporter();  
    //                exporter.setParameter(JRPdfExporterParameter.JASPER_PRINT, jasperPrint);  
    //                exporter.setParameter(JRPdfExporterParameter.CHARACTER_ENCODING,"UTF-8");  
    //                exporter.setParameter(JRPdfExporterParameter.OUTPUT_FILE_NAME, path+"/pdf/"+fileNames);  
    //                exporter.exportReport(); 
                    
                    //生成方法2
                    try {                     
                        JasperExportManager.exportReportToPdfFile(jasperPrint,locleFilePath+"/pdf/"+fileNames); 
                    } catch (Exception e) {  
                        e.printStackTrace();  
                    }  
                return new String[]{fileNames,locleFilePath+"/pdf/"+fileNames};
              }
              
    }

     解析Collection类型

    Czg111JRData.java

    package com.bos.cash.action.account;
    
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.List;
    
    import net.sf.jasperreports.engine.JRDataSource;
    import net.sf.jasperreports.engine.JRException;
    import net.sf.jasperreports.engine.JRField;
    
    import com.ecc.emp.core.EMPConstance;
    import com.ecc.emp.data.KeyedCollection;
    import com.ecc.emp.log.EMPLog;
    
    /**
     * 解析数据类
     * 
     * @author 夏星
     * 
     */
    public class Czg111JRData implements JRDataSource {
        private Collection beans = null;
        private Object bean = null;
        private Iterator it = null;
        private List list = null;
    
        /**
         * 
         * @param theBeans 完整集合
         * @param list     需要下载的回单号集合
         */
        public void setBeans(Collection theBeans, List list) {
            this.list = list;
            this.beans = theBeans;
            this.it = this.beans.iterator();
        }
    
        public boolean next() throws JRException {
            if (this.it.hasNext()) {
                try {
                    this.bean = this.it.next();
                    
                    if(list!=null){
                        String receiptNo = (String) ((KeyedCollection) bean).getDataValue("ECBillCode");
                        if(!list.contains(receiptNo))
                            return next();
                    }
                    
                } catch (Throwable e) {
                    EMPLog.log("jasper", EMPLog.INFO, 0, e.toString());
                    throw new JRException(e);
                }
                return true;
            }
            return false;
        }
    
        public Object getFieldValue(JRField field) throws JRException {
            KeyedCollection kc = (KeyedCollection) this.bean;
            try {
                return kc.getDataValue(field.getName());
            } catch (Exception e) {
                //EMPLog.log("jasper", EMPLog.INFO, 0, e.toString());
                return "";
            }
        }
    }

    6.大功告成!

    PS:在Czg111CreatPDF.java中我分别写了一个预览PDF和直接下载PDF的方法,如果需要实现在线下载PDF功能的话,需要另外写个jsp页面

    czg111_PdfFileDownload.jsp<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <%@page language="java" contentType="text/html; charset=UTF-8"%>
    <%@page import="com.ecc.emp.core.Context" %>
    <%@page import="java.io.File" %>
    <%@page import="com.bos.cash.action.account.Czg111CreatPDF"%>
    <%@page import="java.util.Map"%>
    <%@page import="java.util.HashMap"%>
    <%@page import="com.ecc.emp.data.IndexedCollection"%>
    <%@page import="java.io.FileInputStream"%>
    <%@page import="com.bos.cash.init.SystemHelper"%>
    <%@page import="com.ecc.emp.data.KeyedCollection"%>
    <%@page import="java.util.List"%>
    <%@page import="java.util.ArrayList"%>
    <%@page import="com.ecc.emp.log.EMPLog"%>
    <%@page import="com.ecc.emp.core.EMPConstance"%>
    <%@ include file="http://www.cnblogs.com/head.jsp"%>
    
    <%
        Context context = (Context) request.getAttribute("context");
        Map p = new HashMap();
        File file = null;
        List list = new ArrayList();
        p.put("PRINT_DATE",SystemHelper.getServerTime("yyyy-MM-dd HH:mm:ss"));
        p.put("LOGO",Czg111CreatPDF.getFilePath("bankofshanghai-logo.jpg"));
        p.put("SEAL",Czg111CreatPDF.getFilePath("bankofshanghai-receiptseal.gif"));
        IndexedCollection indexedCollection = (IndexedCollection) context.getDataElement("ECInfoSession");
        String checkListStr = (String)context.getDataValue("PrintCode");
        String[] checkList = checkListStr.split("@");
        for(int i = 0;i < checkList.length-1;i++){
            for(int j = 0;j<indexedCollection.size();j++){
                KeyedCollection indexedCollectionKC = (KeyedCollection) indexedCollection.get(j);
                String no = (String)indexedCollectionKC.getDataValue("ECBillCode");
                if(no.equals(checkList[i+1])){
                    list.add(no);
                }
            }
        }
    //此处调用下载方法 返回值为数组 分别为生成的文件名称以及文件物理路径 String[] fileNames
    = Czg111CreatPDF.downloadPdf("Receipt",p,indexedCollection,pageContext,list); ServletOutputStream ou = null; FileInputStream fis = null; try{ String displayFileName = fileNames[0]; String accountFilePath = fileNames[1]; String fullPath =accountFilePath; response.reset(); response.setContentType("charset=UTF-8"); response.setContentType("application/pdf"); String filename = new String(displayFileName.getBytes("gb2312"), "ISO8859-1"); response.setHeader("Content-Disposition","attachment; filename=" + filename); //解决HTTPS不能下载的问题 response.setHeader("Cache-Control","public"); ou = response.getOutputStream(); file = new File(fullPath); fis = new FileInputStream(file); try { if (fis != null) { int filelen = fis.available(); byte a[] = new byte[filelen]; fis.read(a); ou.write(a); ou.flush(); } } catch (Exception e) { EMPLog.log("pdfDownload", EMPLog.INFO, 0, e.toString()); } out = pageContext.pushBody(); }catch(Exception e){ e.printStackTrace(); }finally{ try { fis.close(); ou.close();
          //文件下载至本地后,删除服务器上的文件
    if(file != null){
                    file.delete();
                }
                ou = null;
                response.flushBuffer();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    %>
    AccAcountReportFile
  • 相关阅读:
    图片剪纸刀:批量切割图片工具
    Photosynth软件试用(将照片拼接成实景)
    制作一份简单的网络地图(世博地图的配准和切割)
    Discuz论坛地图插件(通过自定义Discuz Code实现)
    Maven Settings.xml 配置模板
    CentOS 7 firewalld 配置详解 (转)
    Silverlight学习笔记八右键菜单控件
    Silverlight学习笔记十三关于SilverLight的打印
    Silverlight学习笔记十二动态加载图片和显示提示(ToolTip)
    Silverlight学习笔记十一动态创建TabContro的TabItem
  • 原文地址:https://www.cnblogs.com/xiaxinggege/p/2947812.html
Copyright © 2020-2023  润新知