jasper 导出html,使用jasper导出HTML并解决图片显示问题代码

public static void printToHTML(HttpServletRequest request, HttpServletResponse response, String jasperURL, HashMap hashMap, ServletConfig servletConfig) throws ServletException, IOException {

Connection connection = null;

//读取报表文件

File reportFile = new File(servletConfig.getServletContext().getRealPath(jasperURL));

if (!reportFile.exists()) {

throw new JRRuntimeException("报表文件 *.jasper 不存在!");

}

try {

//连接数据库

connection = ConnectionManager.getConnection();

//获得Jasper输入流

InputStream inputStream = servletConfig.getServletContext().getResourceAsStream(jasperURL);

//获得JasperPrint对象

JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, hashMap, connection);

//关闭数据库连接

connection.close();

//设置格式

//response.setContentType("text/html");

response.setContentType("text/html;charset=UTF-8");

//获得输出流 ,这里不能这样response.getOutputStream()

PrintWriter printWriter = response.getWriter();

//创建JRHtmlExporter对象

JRHtmlExporter htmlExporter = new JRHtmlExporter();

//把jasperPrint到Session里面(net.sf.jasperreports.j2ee.jasper_print)

request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);

//设值jasperPrint

htmlExporter.setParameter(JRExporterParameter.JASPER_PRINT,jasperPrint);

//设置输出

htmlExporter.setParameter(JRExporterParameter.OUTPUT_WRITER,printWriter);

//设置图片生成的Servlet(生成图片就用这个ImageServlet,并且要在XML文件里面配置 image?image=这个是Servlet的url-pattern)

//flush随机数用于重新获取图片(更新图片地址),否则条件改变后图片不会随之发生改变

htmlExporter.setParameter(JRHtmlExporterParameter.IMAGES_URI,"image?flush="+Math.random()+"&image=");

htmlExporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8");

//导出

htmlExporter.exportReport();

//关闭输出流

printWriter.close();

//关闭输入流

inputStream.close();

} catch (JRException jre) {

System.out.println("JRException:" + jre.getMessage());

} catch (Exception e) {

System.out.println("Exception:" + e.getMessage());

} finally {

if (null != connection) {

try {

connection.close();

connection = null;

} catch (SQLException sqle) {

System.out.println("SQLException:" + sqle.getMessage());

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值