此文章是基于  EasyUI+Knockout实现经典表单的查看、编辑

一. 准备工作

  1. 点击此下载相关的文件,并把 ims 文件夹放到 ims 工程对应的路劲下

  2. 参考网址:杰创打印控件

二. 安装ant

  1. 解压apache-ant-1.9.4-bin到任意地方

  2. 配置环境变量ANT_HOME为apache-ant-1.9.4-bin解压后的目录地址,如D:\Download\apache-ant-1.9.4

  3. 在环境变量CLASSPATH中加入%ANT_HOME%\lib;

  4. 在环境变量Path中加入%ANT_HOME%\bin;

  5. 在cmd下测试ant是否安装正确,命令:ant -version     安装成功显示ant的版本号,出错,自己网上查

三. 安装iReport,制作报表的工具

  1. 直接双击iReport-5.6.0-windows-installer.exe进行安装

四. jasperreports源码与例子

  1. 解压jasperreports-5.6.0-project.zip

  2. 在含有build.xml文件的目录执行ant -p 命令可查看可执行哪些ant命令

  3. /jasperreports-5.6.0/src下是源码,可在/jasperreports-5.6.0/目录下执行ant jar来编译源代码,

    最后在/jasperreports-5.6.0/dist/下生成jasperreports-5.6.0.jar包

  4. /jasperreports-5.6.0/demo/samples/下是实例

  5. /jasperreports-5.6.0/demo/samples/webapp/下是标准的实例,可在其目录下执行ant war命令生成war包,可在tomcat下直接部署运行

五. 制作一张报表

iReport设计报表应注意:在含有中文的地方,设置如下,防止pdf导出中文无法显示:

      Font  name:    宋体 (中文字体)

      PDF font name:   STSong-Light

      PDF  Encoding:  UniGB-UCS2-H(Chinese Siplified)

      PDF   Embeded: √

六. 报表在项目中的应用

  1. 将制作好的报表(以jrxml结尾的文件)拷贝到\WebContent\report\jasperreport\ 目录下

  2. jasperreports-5.6.0-project 的 lib 和 dist 目录下可找到如下jar包:

groovy-all-2.0.1.jar
iText-2.1.7.js2.jar
iTextAsian.jar
jackson-annotations-2.1.4.jar
jackson-core-2.1.4.jar
jackson-databind-2.1.4.jar
jasperreports-5.6.0.jar

  3. 添加报表的数据源类

    BaseJRDataSource.java,数据源接口  

package com.ims.interfaces.report.datasource;

import java.util.Map;

import net.sf.jasperreports.engine.JRDataSource;

public interface BaseJRDataSource extends JRDataSource{
    public JRDataSource getInstance(Map parameters);
    public Map<String,Object> getReportParams(Map parameters);
}

    ReceiveDataSource.java,材料收料单报表的数据源类

package com.ims.interfaces.report.datasource.mms;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.ims.interfaces.report.datasource.BaseJRDataSource;
import com.ims.service.mms.ReceiveBS;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;

public class ReceiveDataSource implements BaseJRDataSource{
    @Autowired
    private ReceiveBS receiveBS;

    private List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();
    private int index = -1;

    @Override
    public Object getFieldValue(JRField field) throws JRException {
        Object value = null;
        String fieldName = field.getName();

        if ("billNo".equals(fieldName)){
            value = data.get(index).get("billNo");
        }else if ("rownum".equals(fieldName)){
            value = index+1;
        }else if ("supplierName".equals(fieldName)){
            value = data.get(index).get("supplierName");
        }else if ("warehouseName".equals(fieldName)){
            value = data.get(index).get("warehouseName");
        }else if("receiveDate".equals(fieldName)){
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            value = (null!=data.get(index).get("receiveDate")?formatter.format(data.get(index).get("receiveDate")):"");
        }else if("totalMoney".equals(fieldName)){
            value = data.get(index).get("totalMoney");
        }

        return value;
    }

    @Override
    public boolean next() throws JRException {
        index++;
        return (index < data.size());
    }

    @Override
    public JRDataSource getInstance(Map parameters) {
        data = receiveBS.findPage(parameters).getRows();
        index = -1;
        return this;
    }

    @Override
    public Map<String, Object> getReportParams(Map parameters) {
        parameters.put("dataCount", data.size());
        return parameters;
    }

}

  4. applicationInterface.xml,在spring的配置文件中添加数据源类的bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">  

    <!-- jasperreport -->
    <bean id="mmsReceiveDataSource" class="com.ims.interfaces.report.datasource.mms.ReceiveDataSource" />
    <!-- jasperreport -->
</beans>

  5. showReport.jsp,报表显示页面;打印控件采用jatoolsPrinter.cab,需要tomcat服务以进程的方式启动 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page errorPage="error.jsp" %>
<%@ page import="com.ims.common.ServiceLocator" %>
<%@ page import="com.ims.interfaces.report.datasource.BaseJRDataSource" %>
<%@ page import="net.sf.jasperreports.engine.*" %>
<%@ page import="net.sf.jasperreports.engine.util.*" %>
<%@ page import="net.sf.jasperreports.engine.export.*" %>
<%@ page import="net.sf.jasperreports.j2ee.servlets.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%
    String report = request.getParameter("jasper");
    String dataSource = request.getParameter("ds");
    String args = request.getParameter("args");
    String fileName = new String(request.getParameter("fileName").replaceAll(" ", "").getBytes("utf-8"),"iso8859-1");
    Map parameters = new HashMap();

    JSONObject jsonMap = JSONObject.parseObject(args);
    Iterator<String> it = jsonMap.keySet().iterator();
    while(it.hasNext()) {
        String key = (String)it.next();
        parameters.put(key, jsonMap.get(key));
    }  

    String appmap = request.getContextPath();

    File reportFile = new File(application.getRealPath("/report/jasperreport/"+report+".jasper"));
    if (!reportFile.exists()){
        JasperCompileManager.compileReportToFile(application.getRealPath("/report/jasperreport/"+report+".jrxml"));
        reportFile = new File(application.getRealPath("/report/jasperreport/"+report+".jasper"));
    }

    JasperReport jasperReport = (JasperReport)JRLoader.loadObjectFromFile(reportFile.getPath());
    BaseJRDataSource  baseJRDataSource=    ((BaseJRDataSource)ServiceLocator.getService(dataSource));
    JRDataSource jRDataSource = baseJRDataSource.getInstance(parameters);
    JasperPrint jasperPrint =
            JasperFillManager.fillReport(
                jasperReport,
                baseJRDataSource.getReportParams(parameters),
                jRDataSource
            );

    session.setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);

    int pageIndex = 0;
    int lastPageIndex = 0;
    if (jasperPrint.getPages() != null){
        lastPageIndex = jasperPrint.getPages().size() - 1;
    }

    String pageStr = request.getParameter("page");
    try{
        pageIndex = Integer.parseInt(pageStr);
    }
    catch(Exception e){}

    if (pageIndex < 0){
        pageIndex = 0;
    }

    if (pageIndex > lastPageIndex){
        pageIndex = lastPageIndex;
    }

    HtmlExporter exporter = new HtmlExporter();
    StringBuffer sbuffer = new StringBuffer();

    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
    exporter.setParameter(JRExporterParameter.OUTPUT_STRING_BUFFER, sbuffer);
    exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, "../servlets/image?image=");
    //exporter.setParameter(JRExporterParameter.PAGE_INDEX, Integer.valueOf(pageIndex));
    exporter.setParameter(JRHtmlExporterParameter.HTML_HEADER, "");
    exporter.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, "");
    exporter.setParameter(JRHtmlExporterParameter.HTML_FOOTER, "");

    exporter.exportReport();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
  <title>报表</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <%@ include file="/common/basePath.jsp"%>
  <style type="text/css">
    a {text-decoration: none}
  </style>
  <OBJECT ID="jatoolsPrinter" CLASSID="CLSID:B43D3361-D075-4BE2-87FE-057188254255" codebase="jatoolsPrinter.cab#version=5,7,0,0" width="0" height="0"></OBJECT>
</head>
<body topmargin=0 leftmargin=0 rightmargin=0 bottomMargin=0>
<table id=titleTable width=100% cellspacing=0 cellpadding=0 border=0 ><tr>
    <td height="25" width=100% valign="middle"  style="font-size:13px" background="content/images/toolbar/toolbar-bg.gif">
        <table width="100%">
            <tr >
                <td width="100%" align="right" valign="middle"   style="font-size:12px; line-height:12px; margin:3px 0 0 0 ;" >&nbsp;
                <span style=" margin:0 10px 0 0 ; padding:5px 0 0 0 ; background: url('content/images/toolbar/toolbar-line.gif') no-repeat right top;">
                <a href="#" onClick="doPrint('printPreview');return false;"><img src='content/images/icon/icon/printer.png' border=no ></a>
                <!--
                <a href="<%=appmap%>/servlets/xls?fileName=<%=fileName %>" target="_blank"><img src='content/images/icon/doc/xls.gif' border=no ></a>
                -->
                <a href="<%=appmap%>/servlets/pdf" target="_blank"><img src='content/images/icon/doc/pdf.gif' border=no ></a>
                <a href="<%=appmap%>/servlets/docx?fileName=<%=fileName %>" target="_blank"><img src='content/images/icon/doc/doc.gif' border=no ></a>
                </span>
                <!--
                <%
                    if (pageIndex > 0){
                %>
                <a href='showReport.jsp?page=0&jasper=<%= report%>&ds=<%= dataSource%>&args=<%= args%>'><img src="../resource/image/common/firstpage.gif" border="0"></a>
                <a href='showReport.jsp?page=<%=pageIndex - 1%>&jasper=<%= report%>&ds=<%= dataSource%>&args=<%= args%>'><img src="../resource/image/common/prevpage.gif" border="0"></a>
                <%
                    }else{
                %>
                <img src="../resource/image/common/firstpage.gif" border="0">
                <img src="../resource/image/common/prevpage.gif" border="0">
                <%
                    }
                    if (pageIndex < lastPageIndex){
                %>
                <a href='showReport.jsp?page=<%=pageIndex + 1%>&jasper=<%= report%>&ds=<%= dataSource%>&args=<%= args%>'><img src="../resource/image/common/nextpage.gif" border="0"></a>
                <a href='showReport.jsp?page=<%=lastPageIndex%>&jasper=<%= report%>&ds=<%= dataSource%>&args=<%= args%>'><img src="../resource/image/common/lastpage.gif" border="0"></a>
                <%
                    }else{
                %>
                <img src="../resource/image/common/nextpage.gif" border="0">
                <img src="../resource/image/common/lastpage.gif" border="0">
                <%
                    }
                %>
                &nbsp;&nbsp;第<%=pageIndex+1 %>页/共<%=jasperPrint.getPages().size() %>页
                 -->
                </td>
            </tr>
      </table>
    </td>
</table>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<td align="center">
<%=sbuffer.toString()%>
</td>
<script type="text/javascript">
function doPrint(how)
{
    //打印文档对象
    var myDoc ={
        documents: document,    // 打印页面(div)们在本文档中
        copyrights :    '杰创软件拥有版权  www.jatools.com'      // 版权声明,必须
    };

    // 调用打印方法
    if(how == 'printPreview')
        jatoolsPrinter.printPreview(myDoc);  // 打印预览
    else if(how == 'printDialog')
        jatoolsPrinter.print(myDoc ,true);   // 打印前弹出打印设置对话框
    else
        jatoolsPrinter.print(myDoc ,false);  // 不弹出对话框打印
}
</script>

</table>
</body>
</html>

  6. web.xml,若要支持pdf、img、excel、doc导出,需添加servlet

 <?xml version="1.0" encoding="UTF-8"?>
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:web="http://xmlns.jcp.org/xml/ns/javaee"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_4.xsd http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
     version="2.4">

   <servlet>
     <servlet-name>PdfServlet</servlet-name>
     <servlet-class>net.sf.jasperreports.j2ee.servlets.PdfServlet</servlet-class>
   </servlet>
   <servlet>
     <servlet-name>ImageServlet</servlet-name>
     <servlet-class>net.sf.jasperreports.j2ee.servlets.ImageServlet</servlet-class>
   </servlet>
   <servlet>
     <servlet-name>XlsServlet</servlet-name>
     <servlet-class>net.sf.jasperreports.j2ee.servlets.XlsServlet</servlet-class>
   </servlet>
   <servlet>
     <servlet-name>DocxServlet</servlet-name>
     <servlet-class>net.sf.jasperreports.j2ee.servlets.DocxServlet</servlet-class>
   </servlet>

   <servlet-mapping>
     <servlet-name>PdfServlet</servlet-name>
     <url-pattern>/servlets/pdf</url-pattern>
   </servlet-mapping>
   <servlet-mapping>
     <servlet-name>ImageServlet</servlet-name>
     <url-pattern>/servlets/image</url-pattern>
   </servlet-mapping>
   <servlet-mapping>
     <servlet-name>XlsServlet</servlet-name>
     <url-pattern>/servlets/xls</url-pattern>
   </servlet-mapping>
   <servlet-mapping>
     <servlet-name>DocxServlet</servlet-name>
     <url-pattern>/servlets/docx</url-pattern>
   </servlet-mapping>

 </web-app>

  7. report.js

/***
 * 参数说明:{jasper:"report01.jasper",args:arr}
 * param.jasper:jasper文件名称,最好不要用中文
 * param.ds:dataSource文件名称,最好不要用中文
 * param.args:*格式待定*,暂时用数组,以后看使用什么格式方便可以再改
 * author: suxy.
 */
function openReport(win, param){
    var strFullPath = window.document.location.href;
    var strPath = window.document.location.pathname;
    var pos = strFullPath.indexOf(strPath);
    var prePath = strFullPath.substring(0, pos);
    var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
    var url = postPath;

       if(!param.jasper){
           alert("jasper参数为空!");
           return false;
       }

    //弹出报表展示窗口,可选择更多的功能,不只是打印,还有导出excel等等
    url+="/report/common/showReport.jsp?jasper="+param.jasper+"&ds="+param.ds+"&args="+param.args;
    url=encodeURI(url);
    //打开新窗口
//    var win=window.open("about:blank");
    win.document.write("报表加载中,请稍候..");
    //创建form对象
    var win_form=win.document.createElement("form");
    win_form.action=url;
    win_form.method="POST";
    win.document.body.appendChild(win_form);
    //参数设置(创建input对象)
    var win_form_input=win.document.createElement("input");
    win_form_input.type="hidden";
    win_form_input.name='fileName';
    win_form_input.value=param.fileName;
    win_form.appendChild(win_form_input);
    //提交表单
    win_form.submit();
}

七. 效果展示

  访问:http://localhost:8080/ims/mms/receive.do,点击 打印 按钮

  右上角的按钮可以实现打印、pdf导出、word导出

jasperreports+iReport+jatoolsPrinter制作报表笔记的更多相关文章

  1. jasperreports+iReport制作报表笔记

    一. 准备工作 1. 下载相关工具:点击此下载相关工具,jasperreports-5.6.0-project.zip中有提供所需的jar包. 二. 安装ant 1. 解压apache-ant-1.9 ...

  2. iReport 4.1 报表制作,子报表,实例解析

    开发使用步骤(iReport 4.1.1) (个人总结,如有问题请留言,另外知道table控件用法的给我留言或者发邮件谢谢.Email:jiazx0107@163.com) 目录 1.      开发 ...

  3. 第一部分:使用iReport制作报表的详细过程(Windows环境下)

    提示:在有些板块,文中的图片看不到,建议到我的blog浏览文章:http://blog.csdn.net/jemlee2002/文章将会涉及3个方面的内容: 第一部分:使用iReport制作报表的详细 ...

  4. IReport制作报表——日期时间显示格式

    转自:https://blog.csdn.net/linglinglu/article/details/9022679?utm_source=blogxgwz2 IReport工具在制作报表的时候,会 ...

  5. HighCharts SVN IReport进行PDF报表设计--模板

    BOS物流项目笔记第十五天 HIghcharts是很强大的图表绘制插件,它是基于纯js绘制的.当然地,对于图表也会有很多操作了.下面就我工作时遇到的一些比较常见的highcharts的操作进行小结,不 ...

  6. jasperreports+IReport 5.56,集成到Spring MVC4.0案例

    首先,先说一下需求,项目需要打印一些报表,也没多想,直接就在jsp页面设置了样式,前台直接调用window.print()写了打印功能,但是例会的时候,领导提出需要一些比较麻烦的打印,自己写肯定费时间 ...

  7. JasperReports+iReport在eclipse中的使用

    转载:http://blog.csdn.net/daming924/article/details/7402295 一.介绍1)它可以PDF,HTML,XML等多种形式产生报表或动态报表,在新版本还支 ...

  8. 利用JasperReport+iReport进行Web报表开发

    用JasperReport+iReport进行Web报表开发 序言 在非常多实际的项目里,报表都是当中十分重要的组成部分,比如把查询结果以报表的形式呈现出来.这里所提到的报表可不是简单的二维表,而是拥 ...

  9. 使用JasperReport+iReport进行Web报表开发

    使用JasperReport+iReport进行Web报表开发 前言 在实际工程中非常,报告是其中很重要的一部分,结果以报表的形式呈现出来.这里所提到的报表可不是简单的二维表,而是拥有复杂表头的.多维 ...

随机推荐

  1. c51

    ORG 0000HMOV R7,#08HMOV 83H,#01HMOV R4,#00HAA1:CLR P3.6 CLR P3.4 SETB P3.6 DJNZ R7,AA1AA2:JB P3.0,AA ...

  2. SQLServer : 几个特殊函数(RAND,CHECKSUM, NEWID)

    这一篇我们来捋捋在T-SQL中可能会用到的几个特殊的函数 1. 随机数: RAND 返回从 0 到 1 之间的随机 float 值. 语法: RAND ( [ seed ] ) seed 提供种子值的 ...

  3. fluery算法

    #include<stdio.h> #include<string.h> struct stack { int top; ]; }s; ][]; void dfs(int x) ...

  4. gdb 7.11

    因为CentOS自带的GDB版本有点低,所以下载了最新的gdb 7.11编译以后,调试过程中提示以下错误. Python Exception <type 'exceptions.NameErro ...

  5. css3 3d学习笔记

    几个属性: -webkit-perspective:0;景深(默认0), -webkit-perspective-origin:center center;景深基点(默认中间), -webkit-tr ...

  6. 如何设置Samza的metrics

    参考这个里边对API的调用 http://samza.incubator.apache.org/learn/documentation/0.7.0/container/metrics.html 参考这 ...

  7. [Irving] Ext.Net动态添加GridPanel列绑定Checkbox值失败的解决办法

    var grid = X.GetCmp<GridPanel>(vm.GRID_QUOTATIONS_FEEITEM_RANGE_SHOW); grid.AddColumn(Html.X() ...

  8. iOS UILabel UITextView UIButton 等等显示文本行间距

    iOS UILabel  UITextView UIButton 等等显示文本行间距都用如下方法 NSMutableParagraphStyle *paragraphStyle = [[NSMutab ...

  9. linux 之 tar 命令

    通过SSH访问服务器,难免会要用到压缩,解压缩,打包,解包等,这时候tar命令就是是必不可少的一个功能强大的工具.linux中最流行的tar是麻雀虽小,五脏俱全,功能强大. tar 命令可以为linu ...

  10. Kubernetes使用cephfs作为后端存储

    这里使用了k8s自身的持久化卷存储机制:PV和PVC.各组件之间的关系参考下图: PV的Access Mode(访问模式) The access modes are: ReadWriteOnce – ...