ireport导出各种格式(pdf,excel,word,html,print)

关于JaserReport报表的应用导致tomcat无限占用内存问题
最近启动tomcat时,用top查看内存占用为7%左右。2小时后为13%左右。4小时后为20%左右。8小时后内存用完,死机!这期间内存一直是上涨,没有下降过,即使一个晚上不连接不操作,第二天还是居高不下,没办法只好重启tomcat。

jasperreport+applet实现客户端打印报表
本人使用ireport5.1.0画的报表,实现客户端打印时报java.io.StreamCorruptedException:invalid
stream
header:0D0A0D0A这个错误,下面是代码,请各位高手帮忙看看怎么回事:
1)、action类代码
import java.io.File;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

ireport
2010-07-06 17:36:06 阅读63 评论0 字号:大中澳门新葡萄京官网注册,小

我下载了个jProfiler来查看了下,那个类在占用着资源,发现这个net.sf.jasperreport.engine.fill包下的JRTemplatePrintText类,其Instance
count不断增加,其占用的内存也不断上涨,我查看了代码,发现代码里面根本没有调用过此类(若有调用也是jasperreport内部机制调用的),代码如下:

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public static void getpdfreport(List data, String title, String year,
String filereport,String pdfname,HttpServletResponse response,
HttpServletRequest request){

import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

try{

import org.apache.struts2.ServletActionContext;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.base.JRBaseReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.engine.export.JRRtfExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.util.JRLoader;

File reportFile = new File(request.getRealPath(filereport));

import com.opensymphony.xwork2.ActionSupport;

public class JasperExportUtils
{
public static void prepareReport(JasperReport jasperReport, String type)
{
    /*
     * 如果导出的是excel,则需要去掉周围的margin
     */
    if (“excel”.equals(type))
     try {
      Field margin = JRBaseReport.class
        .getDeclaredField(“leftMargin”);
      margin.setAccessible(true);
      margin.setInt(jasperReport, 0);
      margin = JRBaseReport.class.getDeclaredField(“topMargin”);
      margin.setAccessible(true);
      margin.setInt(jasperReport, 0);
      margin = JRBaseReport.class.getDeclaredField(“bottomMargin”);
      margin.setAccessible(true);
      margin.setInt(jasperReport, 0);
      Field pageHeight = JRBaseReport.class
        .getDeclaredField(“pageHeight”);
      pageHeight.setAccessible(true);
      pageHeight.setInt(jasperReport, 2147483647);
     } catch (Exception exception) {
     }
   }

if (!reportFile.exists

public class IreportAction extends ActionSupport{
private static final long serialVersionUID = 1974082731836773155L;
private static final String CONTENTTYPE = “application/octet-stream”;

   /**
    * 导出excel
    */
   public static void exportExcel(JasperPrint jasperPrint,
     HttpServletRequest request, HttpServletResponse response) throws
IOException, JRException {
     /*
      * 设置头信息
      */
     response.setContentType(“application/vnd.ms-excel”);
     String fileName = new String(“未命名.xls”.getBytes(“GBK”),
“ISO8859_1”);
     response.setHeader(“Content-disposition”, “attachment; filename=”
       + fileName);

System.out.println;

/** * 打印报表 * @return */@SuppressWarnings("unchecked")public void doIreportPrint(){ HttpServletResponse response = ServletActionContext.getResponse(); String fileName = ""; String sql = "select id,dname,dcode from ct_su_departments where datalevel = 0 and status = 0 and rownum <=100"; //建立连接 Connection conn = this.createConnection(); //参数设置 Map parameters = new HashMap(); try { Statement stmt = conn.createStatement();//获取数据库链接 ResultSet rs = stmt.executeQuery;//获取数据 String jasper = new File(ServletActionContext.getServletContext().getRealPath("/report/report1.jasper")).getPath();//获取文件的绝对路径 JasperPrint jpt = JasperFillManager.fillReport(jasper, parameters, new JRResultSetDataSource;//匹配数据源,生成JasperPrint response.setContentType(CONTENTTYPE); ServletOutputStream ouputStream = response.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(ouputStream); oos.writeObject; oos.flush(); oos.close(); }catch(Exception e) { System.out.println("Error:" + e.toString; e.printStackTrace(); }finally { CloseConnect; conn = null; }}/** * 建立数据库连接 * @return */public Connection createConnection(){ Connection conn; try{ String driver = "oracle.jdbc.driver.OracleDriver";//oracle.jdbc.OracleDriver String url = "jdbc:oracle:thin:@172.19.24.239:1521:NSOA"; Class.forName; conn = DriverManager.getConnection(url,"JXKHOA","JXKHOA"); conn.setAutoCommit; return conn; }catch(SQLException e1) { System.out.println("建立连接错误 = " + e1.toString; e1.printStackTrace(); }catch(ClassNotFoundException e2) { System.out.println("建立连接错误 = " + e2.toString; e2.printStackTrace(); } return null;}/** * 关闭数据库连接 * @param conn */public void CloseConnect(Connection conn){ try{ conn.commit(); conn.setAutoCommit; conn.close(); }catch(Exception e){ System.out.println("关闭连接错误 = " + e.toString; }}

     ServletOutputStream ouputStream = response.getOutputStream();
     JRXlsExporter exporter = new JRXlsExporter();
     exporter
       .setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
     exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
       ouputStream);
     exporter.setParameter(
       JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,
       Boolean.TRUE);
    
exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
       Boolean.FALSE);
     exporter.setParameter(
       JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND,
       Boolean.FALSE);
     exporter.exportReport();
     ouputStream.flush();
     ouputStream.close();
   }

else

}

   /**
    * 导出pdf,注意此处中文问题,
1)在ireport的classpath中加入iTextAsian.jar
    * 2)在ireport画jrxml时,pdf font name :STSong-Light ,pdf
encoding :
    * UniGB-UCS2-H
    */
   public static void exportPdf(JasperPrint jasperPrint,
     HttpServletRequest request, HttpServletResponse response) throws
IOException, JRException {
     response.setContentType(“application/pdf”);
     String fileName = new String(“未命名.pdf”.getBytes(“GBK”),
“ISO8859_1”);
     response.setHeader(“Content-disposition”, “attachment; filename=”
       + fileName);
     ServletOutputStream ouputStream = response.getOutputStream();
     JasperExportManager.exportReportToPdfStream(jasperPrint,
       ouputStream);
     ouputStream.flush();
     ouputStream.close();
   }

System.out.println;

2)japplet代码:
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;

   /**
    * 导出html
    */
   public static void exportHtml(JasperPrint jasperPrint,
     HttpServletRequest request, HttpServletResponse response) throws
IOException, JRException {
     response.setContentType(“text/html”);
     ServletOutputStream ouputStream = response.getOutputStream();
     JRHtmlExporter exporter = new JRHtmlExporter();
     exporter.setParameter(
       JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,
       Boolean.FALSE);
     exporter
       .setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
     exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING,
       “UTF-8”);
     exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
       ouputStream);

JasperReport jasperReport =
(JasperReport)JRLoader.loadObject(reportFile.getPath;

import javax.swing.JOptionPane;

     exporter.exportReport();

Map parameters = new HashMap();

import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperPrintManager;
import net.sf.jasperreports.engine.util.JRLoader;

     ouputStream.flush();
     ouputStream.close();
   }

parameters.put(“title”, title);

public class IreportApplet extends javax.swing.JApplet{
private static final long serialVersionUID = 2525694418170444107L;

   /**
    * 导出word
    */
   public static void exportWord(JasperPrint jasperPrint,
     HttpServletRequest request, HttpServletResponse response)
     throws JRException, IOException {
    response.setContentType(“application/msword;charset=utf-8”);
    String fileName = new String(“未命名.doc”.getBytes(“GBK”),
“ISO8859_1”);
    response.setHeader(“Content-disposition”, “attachment; filename=”
      + fileName);
    JRExporter exporter = new JRRtfExporter();
    exporter.setParameter(JRExporterParameter.JASPER_PRINT,
jasperPrint);
    exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response
      .getOutputStream());

JRBeanCollectionDataSource ds=new JRBeanCollectionDataSource;

private URL url = null;private JasperPrint jasperPrint = null;public void init(){ String strUrl = "http://172.19.24.28:8100/BaseWeb/ireportPrint.action"; if (strUrl != null){ try{ URL urll = new URL; url = urll; System.out.println("url="+urll); }catch (Exception e){ StringWriter swriter = new StringWriter(); PrintWriter pwriter = new PrintWriter; e.printStackTrace; JOptionPane.showMessageDialog(this, swriter.toString; } }else{ JOptionPane.showMessageDialog(this, "init():Source URL not specified"); }}public void start(){ if (url != null){ if (jasperPrint == null){ try{ jasperPrint = (JasperPrint)JRLoader.loadObject; }catch (Exception e){ StringWriter swriter = new StringWriter(); PrintWriter pwriter = new PrintWriter; e.printStackTrace; JOptionPane.showMessageDialog(this, swriter.toString; } } if (jasperPrint != null){ final JasperPrint print = jasperPrint; Thread thread = new Thread(new Runnable(){ public void run(){ try{ System.out.println("进入start方法,即将打印pdf文件"); JasperPrintManager.printReport(print, true); }catch (Exception e){ StringWriter swriter = new StringWriter(); PrintWriter pwriter = new PrintWriter; e.printStackTrace; JOptionPane.showMessageDialog(null, swriter.toString; } } }); thread.start(); }else{ JOptionPane.showMessageDialog(this, "Empty report."); } }else{ JOptionPane.showMessageDialog(this, "start():Source URL not specified"); }}

    exporter.exportReport();
   }

JasperPrint jasperPrint=JasperFillManager.fillReport(jasperReport,
parameters,ds);

}

   /**
    * 打印
    */
   public static void exportPrint(JasperPrint jasperPrint,
     HttpServletResponse response, HttpServletRequest request)
     throws IOException {
    response.setContentType(“application/octet-stream”);
    ServletOutputStream ouputStream = response.getOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(ouputStream);
    oos.writeObject(jasperPrint);
    oos.flush();
    oos.close();
    ouputStream.flush();
    ouputStream.close();
   }

response.setContentType(“application/pdf”);

执行到jasperPrint =
(JasperPrint)JRLoader.loadObject;这就话是就报错了。该报表导出excel和pdf都是可以的,而且在action类里面直接使用JasperViewer.viewReport(jpt,false);也是可以打印的,就这个japplet生成客户端打印时报错了。希望各位高手能赐教,非常感谢!!!

   /**
    * 按照类型导出不同格式文件
    *
    * @param datas
    *            数据
    * @param type
    *            文件类型
    * @param is
    *            jasper文件的来源
    * @param request
    * @param response
    */
   public static void export(Collection datas, String type, InputStream
is,
     HttpServletRequest request, HttpServletResponse response) {
    try {
     JasperReport jasperReport = (JasperReport)
JRLoader.loadObject(is);
     prepareReport(jasperReport, type);
     JRDataSource ds = new JRBeanCollectionDataSource(datas, false);
     Map parameters = new HashMap();
     JasperPrint jasperPrint = JasperFillManager.fillReport(
       jasperReport, parameters, ds);

JRPdfExporter exporter=new JRPdfExporter();

     if (EXCEL_TYPE.equals(type)) {
      exportExcel(jasperPrint, request, response);
     } else if (PDF_TYPE.equals(type)) {
      exportPdf(jasperPrint, request, response);
     } else if (HTML_TYPE.equals(type)) {
      exportHtml(jasperPrint, request, response);
     } else if (WORD_TYPE.equals(type)) {
      exportWord(jasperPrint, request, response);
     }
    } catch (Exception e) {
     e.printStackTrace();
    }
   }

ByteArrayOutputStream baos=new ByteArrayOutputStream();

   public static final String PRINT_TYPE = “print”;
   public static final String PDF_TYPE = “pdf”;
   public static final String EXCEL_TYPE = “excel”;
   public static final String HTML_TYPE = “html”;
   public static final String WORD_TYPE = “word”;

exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING,
“GB2312”);

}

exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);

exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);

exporter.exportReport();

//以下为另打开文件

byte[] bytes;

bytes=baos.toByteArray();

String newpdf=”/report/”+pdfname;

File pdffile = new File(request.getRealPath;

FileOutputStream fos=new FileOutputStream;

fos.write;

fos.close();

}catch (JRException e){

System.out.println(“JRException出错:”+e.toString;

e.printStackTrace();

}catch (IOException ex) {

System.out.println(“IOException出错:”+ex.toString;

ex.printStackTrace();

}

}

一旦调用了此方法net.sf.jasperreport.engine.fill.JRTemplatePrintText包就开始出现并曾现递增状况。

系统在我本机的tomcat下跑的时候不会出现这种情况,但发布到公共服务器上供多人联网同时进行操作,这种情况就曾现出来了,一旦内存被盛满tomcat就会出现假死现象,系统将会特别慢,但是一直想不到解决方法,还希望大家能指点指点。