将JasperReport导出为PDF OutputStream?

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

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

如何在OutputStream获取PDF?

好的,这就是它的工作原理; 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()); // export it! File pdf = File.createTempFile("output.", ".pdf"); JasperExportManager.exportReportToPdfStream(print, new FileOutputStream(pdf)); 

请享用。

您可以使用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参数来控制报告的目标。

JRExporterParameter在最新版本中已弃用,这是@stevemac答案的一个未弃用的解决方案

 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();