• 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

  • 相关阅读:
    win11如何启用IIS管理器应用
    vue 滑块 验证
    将页面dom导出为pdf格式并进行下载
    vue3+vite应用中添加sass预处理器
    Vue2.0与Vue3.0区别总结
    迅为iTOPSTM32MP157开发板重磅发布
    迅为RK3568核心板
    迅为STM32MP157开发板入门教程之外设功能验证
    迅为2K1000开发板龙芯平台Ejtag 单步调试 PMON 的汇编阶段
    迅为2K1000龙芯开发板pmon BSP移植之配置CAN总线
  • 原文地址:https://www.cnblogs.com/diyunpeng/p/5934909.html
Copyright © 2020-2023  润新知