jasperreports+iReport+jatoolsPrinter制作报表笔记

时间:2022-02-26 14:55:25

此文章是基于  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,点击 打印 按钮

jasperreports+iReport+jatoolsPrinter制作报表笔记

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