将JasperReport导出为PDF OutputStream?

时间:2011-12-19 23:27:52

标签: java jasper-reports

我正在编写一个非常简单的示例项目,用于熟悉Jasper Reports。我想将我配置的报告导出为PDF OutputStream,但它没有工厂方法:

InputStream template = JasperReportsApplication.class
    .getResourceAsStream("/sampleReport.xml");
JasperReport report = JasperCompileManager.compileReport(template);
JasperFillManager.fillReport(report, new HashMap<String, String>());
// nope, just chuck testa.  
//JasperExportManager.exportReportToPdfStream(report, new FileOutputStream(new File("/tmp/out.pdf")));

如何在OutputStream中获取PDF?

3 个答案:

答案 0 :(得分:34)

好的,这就是它的工作原理; JasperFillManager实际上会返回JasperPrint个对象,所以:

// get the JRXML template as a stream
InputStream template = JasperReportsApplication.class
    .getResourceAsStream("/sampleReport.xml");
// compile the report from the stream
JasperReport report = JasperCompileManager.compileReport(template);
// fill out the report into a print object, ready for export. 
JasperPrint print = JasperFillManager.fillReport(report, new HashMap<String, String>());
// export it!
File pdf = File.createTempFile("output.", ".pdf");
JasperExportManager.exportReportToPdfStream(print, new FileOutputStream(pdf));

享受。

答案 1 :(得分:16)

您可以使用JRExporter将填充的报告导出为不同的流和格式。

JRExporter exporter = null;

exporter = new JRPdfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream);
exporter.exportReport();

另请注意,还有其他出口商:

exporter = new JRRtfExporter();
exporter = new JRHtmlExporter();

您可以在此处找到更多出口商: http://jasperreports.sourceforge.net/api/net/sf/jasperreports/engine/JRExporter.html

他们都应该接受OUTPUT_STREAM参数来控制报告的目的地。

答案 2 :(得分:12)

  最新版本中不推荐使用

JRExporterParameter,这是@stevemac answer 不推荐使用解决方案

JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputStream));
SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
configuration.setMetadataAuthor("Petter");  //why not set some config as we like
exporter.setConfiguration(configuration);
exporter.exportReport();