JasperReport html 导出

In my last blog post I discussed about Generating jasper reports in different formats using json file as a data source.You can find my last post here. In this blog article I will discuss about exporting the jasperPrint object in different formats like pdf, html, csv, xls and docx using the newer API of jasper reports.

Exporting the jasperPrint object which consists of images into html format is a tedious task with the jasper’s deprecated API found all over the internet. I have tried using the JRHtmlExporter class that consists of mostly deprecated methods and using it I couldn’t get the images in the jrxml in the html format.

So, I wanted to write a blog post to help my fellow programmers to illustrate how it can be done with the new API of jasper reports. HtmlExporter class is part of new API and using it one can export the report to html format.

To do this first we need to place the jasperPrint object in the http session using the following code.

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

After placing the jasperPrint object in the session, we need to set the image handler for images in the report using the code,

exporterOutput.setImageHandler(new WebHtmlResourceHandler("image?image={0}"));

The images are served by ImageServlet which should be mapped to ‘/image’ in the web.xml. Here is the configuration that should be added to web.xml file.

 <servlet>
    <servlet-name>ImageServlet</servlet-name>
    <servlet-class>net.sf.jasperreports.j2ee.servlets.ImageServlet</servlet-class> </servlet>
 <servlet-mapping>
     <servlet-name>ImageServlet</servlet-name>
     <url-pattern>/image</url-pattern>
 </servlet-mapping>

The JasperCompileManager.compileReport(jrxmlSource) method compiles and generates a jasperReport object which is used to generate jasperPrint object using the JasperFillManager.fillReport(jasperReport, parameters, dataSource) method. In the following example the dataSource is populated using a string which is in json format. I am exporting the generated documents to the response. So, accordingly I have set content-type, content-disposition headers appropriately, which I have not shown in the code. The headers are set for all formats except for the type html as htmls are to be displayed in the browser along with images.

You can refer my previous blog post for maven dependencies. I have used commons-io dependency in addition to the previous dependencies.

        private static final Logger logger = LoggerFactory.getLogger(YOURCLASS.class);
	JRDataSource dataSource = getDataSource(jsonData);//pass jsonData to populate the dataSource
	JasperReport jasperReport = null;
	JasperPrint jasperPrint = null;
	//String type = Any of the types mentioned above
	//jrxmlSource is the the jrxml generated using the iReport

	Map<String, Object> parameters = new HashMap<String, Object>();
	//Add any parameters that are referenced in the jrxml to this map

	try {
		jasperReport = JasperCompileManager.compileReport(jRXMLSource);
		jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);
	} catch (JRException ex) {
		ex.printStackTrace();
	}

	if ("pdf".equals(type)) {
		JRPdfExporter exporter = new JRPdfExporter();
		try {
			exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
                        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));
			exporter.exportReport();
		} catch (IOException e) {
			logger.error("IOException occured", e);
			e.printStackTrace();
		} catch (JRException e) {
			logger.error("JRException while exporting for pdf format", e);
			e.printStackTrace();
		}

	} else if ("xls".equals(type)) {

		JRXlsExporter exporter = new JRXlsExporter();
		try {
			exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
   		        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));
			SimpleXlsReportConfiguration configuration = new SimpleXlsReportConfiguration();
			configuration.setOnePagePerSheet(true);
			exporter.setConfiguration(configuration);
			exporter.exportReport();
		} catch (JRException e) {
			logger.error("JRException while exporting for xls format", e);
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("IOException occured", e);
			e.printStackTrace();
		}

	} else if ("csv".equals(type)) {
		JRCsvExporter exporter = new JRCsvExporter();
		try {
			exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
			exporter.setExporterOutput(new SimpleWriterExporterOutput(response.getOutputStream()));
			exporter.exportReport();
		} catch (IOException e) {
			logger.error("IOException occured", e);
			e.printStackTrace();
		} catch (JRException e) {
			logger.error("JRException while exporting report csv format", e);
			e.printStackTrace();
		}
	} else if ("html".equals(type)) {
		request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,jasperPrint);

		HtmlExporter exporterHTML = new HtmlExporter();
		SimpleExporterInput exporterInput = new SimpleExporterInput(jasperPrint);
		exporterHTML.setExporterInput(exporterInput);

		SimpleHtmlExporterOutput exporterOutput;
		try {
			exporterOutput = new SimpleHtmlExporterOutput(response.getOutputStream());
			exporterOutput.setImageHandler(new WebHtmlResourceHandler("image?image={0}"));
			exporterHTML.setExporterOutput(exporterOutput);

		        SimpleHtmlReportConfiguration reportExportConfiguration = new SimpleHtmlReportConfiguration();
			reportExportConfiguration.setWhitePageBackground(false);
			reportExportConfiguration.setRemoveEmptySpaceBetweenRows(true);
			exporterHTML.setConfiguration(reportExportConfiguration);
			exporterHTML.exportReport();
		} catch (IOException e) {
			logger.error("IOException occured", e);
			e.printStackTrace();
		} catch (JRException e) {
			logger.error("JRException while exporting for html format", e);
			e.printStackTrace();
		}
	} else if ("docx".equals(type)) {
		JRDocxExporter exporter = new JRDocxExporter();

		try {
			exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
		        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));
			exporter.exportReport();
		} catch (IOException e) {
			logger.error("IOException occured", e);
			e.printStackTrace();
		} catch (JRException e) {
			logger.error("JRException while exporting for docx format", e);
			e.printStackTrace();
		}
	}

	public JRDataSource getDataSource(String jsonData) {
		logger.info("jsonData = " + jsonData);
		JRDataSource dataSource = null;

		if ("null".equals(jsonData) || jsonData == null || "".equals(jsonData)) {
			logger.info("jsonData parameter value is null. Creating JREmptyDataSource");
			dataSource = new JREmptyDataSource();
			return dataSource;
		}

		InputStream jsonInputStream = null;
		try {
			// Convert the jsonData string to inputStream
			jsonInputStream = IOUtils.toInputStream(jsonData, "UTF-8");
			// selectExpression is based on the jsonData that your string contains
			dataSource = new JsonDataSource(jsonInputStream, "data");
		} catch (IOException ex) {
			logger.error("Couldn‘t covert string into inputStream", ex);
			ex.printStackTrace();
		} catch (JRException e) {
			logger.error("Couldn‘t create JsonDataSource", e);
			e.printStackTrace();
		}

		if (dataSource == null) {
			dataSource = new JREmptyDataSource();
			logger.info("dataSource is null. Request parameter jsondData is null");
		}

		return dataSource;
	}

Hope the above code helps to resolve the issue of getting the images in html format. The images can be placed in WEB-INF/classes directory if the directory is not mentioned in the jrxml. If the directory is mentioned then the path should supplied as a parameter which should be kept inside parameters map.

Wish you happy coding!!

Rajasekhar
Helical IT Solutions

时间: 2024-10-27 11:07:07

JasperReport html 导出的相关文章

jasperReport+ireport实现报表导出和数据分析

jasperReport + ireport组合实现报表文件(各种文件格式xsl.pdf,rtf等)的生成导出是目前开源报表中使用的最为广泛的.在平台一期完成之后,而且功能中报表以及数据分析这块是必不可少的,一下展示如何使用JasperReport + ireport导出excel报表. 1.需要.jasper文件作为生成报表的模板,这个文件是由ireport文件编译.jrxml文件之后生成的.这个需要注意的是JasperReport和ireport的版本一定要对应,否则很可能出问题.下面的文件

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

用JasperReport+iReport进行Web报表开发 序言 在非常多实际的项目里,报表都是当中十分重要的组成部分,比如把查询结果以报表的形式呈现出来.这里所提到的报表可不是简单的二维表,而是拥有复杂表头的.多维的.能够在执行期从数据库中自己主动读取数据.可自己主动分页.拥有丰富的页面元素(图片,超连接等).支持分组和交叉表.支持打印.最好还能导出到Excel或Word…...(汗L).可是显而易见,报表功能越强大,提供的服务越丰富,其复杂度也就越提高,所以仅靠石器时代的手工方式生成报表是

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

前言 在实际工程中非常,报告是其中很重要的一部分,结果以报表的形式呈现出来.这里所提到的报表可不是简单的二维表,而是拥有复杂表头的.多维的.能够在执行期从数据库中自己主动读取数据.可自己主动分页.拥有丰富的页面元素(图片.超连接等).支持分组和交叉表.支持打印.最好还能导出到Excel或Word…...(汗L). 可是显而易见,报表功能越强大,提供的服务越丰富,其复杂度也就越提高,所以仅靠石器时代的手工方式生成报表是不能满足须要的. 所幸,眼下我们所熟知的几款报表工具功能上足够强大,并且都附有非

JasperReports&#174; Library | Jaspersoft Community

JasperReport报表导出踩坑实录 - 小卖铺的老爷爷 - 博客园https://www.cnblogs.com/laoyeye/p/7707149.html jasperreport_百度百科https://baike.baidu.com/item/jasperreport/3413053 JasperReports® Library | Jaspersoft Communityhttps://community.jaspersoft.com/project/jasperreports-

EChart整合JasperReport在struts2环境中导出

EChart是百度前端团队开发的一个图表展示控件,功能很全,效果很炫,可以直接百度到各种教程和资源. JasperReport是Java中处理报表的一种方式,配合iReport工具可以进行可视化的报表开发,也比较方便. 下面主要是一个小小的实例. 项目工程和jar包截图如下,其中jar包的截图是多于实际需要的jar的 下面开始步骤讲解: 首先是前端的jsp显示: echart_export.jsp <%@ page language="java" import="jav

JasperReport导出报表8

我们已经看到在前面的章节中,如何打印和查看的JasperReport生成的文档.在这里,我们将看到如何在其他格式,如PDF,HTML和XLS转换或导出这些报告. Facade类net.sf.jasperreports.engine.JasperExportManager提供实现这一功能.导出方式转变JasperPrint对象(.jrprint文件)导入到不同的格式. 下面的代码(JasperReportExport.java)演示了JasperReport文档的导出过程.该JasperExpor

JAVA实用案例之文件导出(JasperReport踩坑实录)

写在最前面 想想来新公司也快五个月了,恍惚一瞬间. 翻了翻博客,因为太忙,也有将近五个多月没认真总结过了. 正好趁着今天老婆出门团建的机会,记录下最近这段时间遇到的大坑-JasperReport. 六月份的时候写过一篇利用poi文件导入导出的小Demo,JAVA实用案例之文件导入导出(POI方式). 虽然简单,但是企业应用的原理基本上也就是这样,只不过是封装的更好些,不像我之前写的那样每个Cell都需要定义,其实poi的方式也是我目前最推崇的方式之一了.主要原因是jxl不支持xlsx,Jaspe

客制化jasperreport导出html的过程

* 先看一段简单的导出html过程中,修改html头部的例子:[jasperreport6.3.1] HtmlExporter exporter = new HtmlExporter(); SimpleHtmlExporterConfiguration config=new SimpleHtmlExporterConfiguration(); String header= "<html>\n"+ "<head>\n"+ " <

struts2与JasperReport整合应用中解决PDF中文不显示问题(让我烦恼了半天)

今天在struts2中以pdf导出JasperReport报表时,遇到了一个很奇怪的问题:在action中获取一些值并且将其放到map中,但是通过$F{name}取值时,有些值能显示,而有些值不能显示,有些值只能显示部分.刚开始还以为是action存放到map中的key和jsper中取到的是不一致的,检查了半天发现并没有问题.这个问题然我郁闷了半天,始终没找到问题所在,由于不知道问题出在哪了,在百度上搜索了半天也没找到解决的办法,无意间看到了一片文章解决了我的问题,下面整理了一下此问题的解决方案