Export JasperReport to PDF OutputStream?

2022-09-01 07:18:50

我正在编写一个非常简单的示例项目,以熟悉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")));

如何获取 PDF 格式?OutputStream


答案 1

好的,所以这就是它的工作原理; 实际上返回一个对象,因此:JasperFillManagerJasperPrint

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

享受。


答案 2

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

推荐