Struts2中实现JasperReport打印通用模块设计(兼容多种浏览器)

/**

*报表Applet打印和pdf、xls导出

*

*@authorliulin

*@date2010-3

***/

abstractpublicclassReportActionextendsBaseAction{

privatestaticStringbasepath="/WEB-INF/report/";//报表存放地址

privatestaticStringjrepath="../applet/jre-6u21-windows-i586.exe";//jre-6u19-windows-i586.exe";//jre下载本地路径#Version=6,0,1,9

publicStringreportname;//无后缀的jrxml报表模板名字

publicStringexportname;//导出pdf、xls的文件名字

publicListreportList;//数据明细集合

publicMapreportParams;//报表参数

/**报表填充数据**/

abstractpublicListgetReportList();

publicvoidsetReportList(ListreportList){

this.reportList=reportList;

}

publicMapgetReportParams(){

returnreportParams;

}

publicvoidsetReportParams(MapreportParams){

this.reportParams=reportParams;

}

publicStringgetReportname(){

returnreportname;

}

publicvoidsetReportname(Stringreportname){

this.reportname=reportname;

}

publicStringgetExportname(){

returnexportname;

}

publicvoidsetExportname(Stringexportname){

this.exportname=exportname;

}

publicStringgetBasepath(){

returnbasepath;

}

publicvoidsetBasepath(Stringbasepath){

this.basepath=basepath;

}

publicStringgetJrepath(){

returnjrepath;

}

publicvoidsetJrepath(Stringjrepath){

this.jrepath=jrepath;

}

/**applet打印预览,兼容ie、火狐等大多数浏览器**/

publicStringprint(){

Enumerationen=this.getRequest().getParameterNames();

booleanisIE=isIE();

Stringappleturl;

Stringparam="";

for(;en.hasMoreElements();){

Stringk=(String)en.nextElement();

Stringv=this.getRequest().getParameter(k);

if(v!=null)

param+=k+"="+v.trim()+"&";

else

param+=k+"=&";

}

if(param.lastIndexOf("&")==param.length()-1)

param=param.substring(0,param.length()-1);

appleturl=this.getRequest().getRequestURI().replace("_print.action",

"_APPLET.action")

+"?"+param;

Stringhtml="<html><head><title></title>\n"

+"<styletype=\"text/css\">body{margin:0px2px;padding:0px;}</style>\n"

+"</head><body>\n";

html+="<!--[if!IE]>Firefoxandotherswilluseouterobject-->"+

"<objectclassid=\"java:EmbeddedViewerApplet\"type=\"application/x-java-applet\"WIDTH=\"100%\"HEIGHT=\"100%\">"+

"<PARAMNAME=\"REPORT_URL\""+"VALUE=\""+appleturl+"\">"+

"<PARAMNAME=\"CODEBASE\"VALUE=\"../applet\">"+

"<paramname=\"archive\"value=\"jasperreports-applet-3.7.1.jar,commons-logging.jar,commons-collections.jar\"/>"+

"<!--<![endif]-->"+

"<!--MSIE(MicrosoftInternetExplorer)willuseinnerobject-->"+

"<objectclassid=\"clsid:8AD9C840-044E-11D1-B3E9-00805F499D93\""+

"codebase=\""+jrepath+"\"WIDTH=\"100%\"HEIGHT=\"100%\">"+

"<PARAMNAME=\"CODEBASE\"VALUE=\"../applet\">"+

"<paramname=\"code\"value=\"EmbeddedViewerApplet.class\"/>"+

"<paramname=\"archive\"value=\"jasperreports-applet-3.7.1.jar,commons-logging.jar,commons-collections.jar\"/>"+

"<PARAMNAME=\"REPORT_URL\""+"VALUE=\""+appleturl+"\">"+

"<strong>这个浏览器没有安装JavaPlug-in.<br/>"+

"<ahref=\"http://www.oracle.com/technetwork/java/javase/downloads/index.html\">从最官方下载最新JavaPlug-in.</a></strong><br/>"+

"<ahref=\""+jrepath+"\">从本地下载JavaPlug-in</a><br/>"+

"<ahref=\"../applet/JavaRuntimeEnvironment.reg\">如果安装插件失败,手动修改注册列表来实现(注意:修改JavaRuntimeEnvironment.reg文件中的C:\\\\ProgramFiles\\\\Java\\\\jre6\\\\为你系统jre安装目录;修改1.6.0_21为你当前安装版本)</a>"+

"</object>"+

"<!--[if!IE]>closeouterobject-->"+

"</object>"+

"<!--<![endif]-->";

html+="</body></html>";

this.renderHtml(html);

returnNONE;

}

/**是否IE**/

publicbooleanisIE(){

HttpServletRequestrequest=this.getRequest();

Stringagent=request.getHeader("USER-AGENT");

booleanisIE=false;

if(null!=agent&&-1!=agent.indexOf("MSIE"))

isIE=true;

returnisIE;

}

/**

*根据浏览器类型导出文件中文名称,支持浏览器IE、Firefox、Safari

*

*@throwsUnsupportedEncodingException

**/

publicStringgetFileNameCode(StringfileName)

throwsUnsupportedEncodingException{

HttpServletRequestrequest=this.getRequest();

Stringagent=request.getHeader("USER-AGENT");

if(null!=agent&&-1!=agent.indexOf("MSIE")){

fileName=java.net.URLEncoder.encode(fileName,"UTF-8").replace(

"+","");

}elseif(null!=agent&&-1!=agent.indexOf("Firefox")){

fileName=newString(fileName.getBytes("UTF-8"),"iso8859-1");

}elseif(null!=agent&&-1!=agent.indexOf("Safari")){

fileName=java.net.URLEncoder.encode(fileName,"UTF-8").replace(

"+","");

}else{

}

returnfileName;

}

/**导出xls文件**/

publicStringXLS()throwsException{

HttpServletResponseresponse=this.getResponse();

StringsourceFile=ServletActionContext.getServletContext()

.getRealPath(basepath+reportname+".jrxml");

Fileparent=newFile(sourceFile).getParentFile();

JRXlsExporterexporter=newJRXlsExporter();

JasperPrintjasperPrint=null;

try{

JasperCompileManager.compileReportToFile(sourceFile,newFile(

parent,reportname+".jasper").getAbsolutePath());

JasperReportjasperReport=(JasperReport)JRLoader

.loadObject(sourceFile.replace(".jrxml",".jasper"));

Listlist=this.getReportList();

jasperPrint=JasperFillManager.fillReport(jasperReport,

this.reportParams,newJRBeanCollectionDataSource(list));

}catch(Exceptione){

e.printStackTrace();

}

if(null!=jasperPrint){

byte[]bytes;

ByteArrayOutputStreambo=newByteArrayOutputStream();

exporter

.setParameter(JRExporterParameter.JASPER_PRINT,jasperPrint);

exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,bo);

exporter.exportReport();

bytes=bo.toByteArray();

if(bytes!=null&&bytes.length>0){

response.reset();

response.setContentType("application/xls");

exportname=exportname+"__"

+this.getCurrentTime(newDate(),"yyyy年MM月dd日")

+".xls";

response.addHeader("Content-Disposition",

"attachment;filename=\""+getFileNameCode(exportname)

+"\"");

response.setContentLength(bytes.length);

ServletOutputStreamsos=response.getOutputStream();

sos.write(bytes,0,bytes.length);

sos.flush();

sos.close();

}

}

returnNONE;

}

/**导出pdf文件**/

publicStringPDF()throwsException{

HttpServletResponseresponse=this.getResponse();

StringsourceFile=ServletActionContext.getServletContext()

.getRealPath(basepath+reportname+".jrxml");

Fileparent=newFile(sourceFile).getParentFile();

JRPdfExporterexporter=newJRPdfExporter();

JasperPrintjasperPrint=null;

try{

JasperCompileManager.compileReportToFile(sourceFile,newFile(

parent,reportname+".jasper").getAbsolutePath());

JasperReportjasperReport=(JasperReport)JRLoader

.loadObject(sourceFile.replace(".jrxml",".jasper"));

Listlist=this.getReportList();

jasperPrint=JasperFillManager.fillReport(jasperReport,

this.reportParams,newJRBeanCollectionDataSource(list));

}catch(Exceptione){

e.printStackTrace();

}

if(null!=jasperPrint){

byte[]bytes;

ByteArrayOutputStreambo=newByteArrayOutputStream();

exporter

.setParameter(JRExporterParameter.JASPER_PRINT,jasperPrint);

exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,bo);

exporter.exportReport();

bytes=bo.toByteArray();

if(bytes!=null&&bytes.length>0){

response.reset();

response.setContentType("application/pdf");

exportname=exportname+"__"

+this.getCurrentTime(newDate(),"yyyy年MM月dd日")

+".pdf";

response.addHeader("Content-Disposition",

"attachment;filename=\""+getFileNameCode(exportname)

+"\"");

response.setContentLength(bytes.length);

ServletOutputStreamsos=response.getOutputStream();

sos.write(bytes,0,bytes.length);

sos.flush();

sos.close();

}

}

returnNONE;

}

/**

*applet输出

*

***/

publicStringAPPLET(){

FilereportFile=newFile(ServletActionContext.getRequest()

.getRealPath(basepath+reportname+".jasper"));

StringsourceFile=ServletActionContext.getServletContext()

.getRealPath(basepath+reportname+".jrxml");

Fileparent=newFile(sourceFile).getParentFile();

JasperPrintjasperPrint=null;

try{

JasperCompileManager.compileReportToFile(sourceFile,newFile(

parent,reportname+".jasper").getAbsolutePath());

JasperReportjasperReport=(JasperReport)JRLoader

.loadObject(reportFile);

Listlist=this.getReportList();

jasperPrint=JasperFillManager.fillReport(jasperReport,

this.reportParams,newJRBeanCollectionDataSource(list));

}catch(Exceptione){

System.out.println("打印出错了:"+e.getMessage());

e.printStackTrace();

}

if(null!=jasperPrint){

HttpServletResponseresponse=this.getResponse();//ServletActionContext.getResponse();

response.setContentType("application/octet-stream");

ServletOutputStreamouputStream;

try{

ouputStream=response.getOutputStream();

ObjectOutputStreamoos=newObjectOutputStream(ouputStream);

oos.writeObject(jasperPrint);

oos.flush();

oos.close();

ouputStream.flush();

ouputStream.close();

}catch(IOExceptione){

e.printStackTrace();

}

}

returnNONE;

    }

}

相关推荐