jasperreport生成html,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.

ImageServlet

net.sf.jasperreports.j2ee.servlets.ImageServlet

ImageServlet

/image

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 parameters = new HashMap();

//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!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好!要生成多张报表,您可以使用JasperReports库来实现。下面是一个简单的示例代码,演示了如何使用JasperReports生成多张报表: ```java import net.sf.jasperreports.engine.*; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class JasperReportGenerator { public static void main(String[] args) { try { // 创建一个JasperReport对象 JasperReport jasperReport = JasperCompileManager.compileReport("report_template.jrxml"); // 准备数据源 List<Map<String, Object>> dataList = new ArrayList<>(); // 添加第一份报表数据 Map<String, Object> data1 = new HashMap<>(); data1.put("name", "Report 1"); dataList.add(data1); // 添加第二份报表数据 Map<String, Object> data2 = new HashMap<>(); data2.put("name", "Report 2"); dataList.add(data2); // 将数据源封装为JRBeanCollectionDataSource对象 JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(dataList); // 设置参数 Map<String, Object> parameters = new HashMap<>(); // 生成第一份报表 JasperPrint jasperPrint1 = JasperFillManager.fillReport(jasperReport, parameters, dataSource); JasperExportManager.exportReportToPdfFile(jasperPrint1, "report1.pdf"); // 生成第二份报表 JasperPrint jasperPrint2 = JasperFillManager.fillReport(jasperReport, parameters, dataSource); JasperExportManager.exportReportToPdfFile(jasperPrint2, "report2.pdf"); System.out.println("报表生成成功!"); } catch (JRException e) { e.printStackTrace(); } } } ``` 在上面的示例中,我们使用了JasperReports的核心类,如JasperCompileManager、JasperFillManager和JasperExportManager来编译模板、填充数据并导出报表。您需要将报表模板文件(.jrxml)准备好,并将其作为参数传递给`JasperCompileManager.compileReport()`方法。 然后,您可以通过创建一个包含报表数据的List对象,并使用JRBeanCollectionDataSource将其封装为数据源。之后,可以使用JasperFillManager.fillReport()方法来填充数据并生成JasperPrint对象。最后,使用JasperExportManager.exportReportToPdfFile()方法将报表导出为PDF文件。 请确保您已经正确设置了JasperReports的依赖项,并且将报表模板文件正确地放置在指定的位置。 希望这个示例能帮助到您!如有任何问题,请随时提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值