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

最新文章

  1. caffe的python接口学习(5):生成deploy文件
  2. IO-02. 整数四则运算(10)
  3. 使用Memory Analyzer tool(MAT)分析内存泄漏
  4. Spring中事务的5种属性总结
  5. iOS离线打包
  6. JavaScript编写了一个计时器
  7. Unity3D-游戏中的技能碰撞检测
  8. RESTful API 架构解读
  9. ubuntu网络设置及遇到问题
  10. es6(二):解构赋值
  11. PHP7 学习笔记(十七)变量函数 - unset
  12. Android常用逆向工具+单机游戏破解
  13. Docker之Swarm
  14. word2013密钥
  15. CASE WHEN 及 SELECT CASE WHEN的用法(写了一坨烂代码发现两条sql就行了, 哎)
  16. 增量式pid和位置式PID参数整定过程对比
  17. 【HubbleDotNet】HubbleDotNet配置安装注册key获取
  18. dorado-menu
  19. iptables之NAT代理-内网访问外网
  20. 如何用代码组织多个Storyboard(故事板)

热门文章

  1. Android学习笔记进阶十三获得本地全部照片
  2. vector转数组
  3. Android ProGuard代码混淆技术详解
  4. Eclipse如何从SVN更新和上传修改部分项目
  5. 00096_Properties类
  6. Maven学习总结(15)——Maven 项目中pom.xml详解
  7. 2017.1-TOP5 Android开源库
  8. WebService--CXF以及CXF与Spring的整合(jaxws:server形式配置)
  9. windows下安装emscripten
  10. 回家过年,CSDN博客暂时歇业