SpringBoot项目中如何从数据库字节数组创建JasperReport对象?
从数据库字节数组生成JasperReport实例的解决方案
核心思路
数据库中存储的Attachment对象里的attachmentFile字段是编译好的.jasper文件字节数组,只需将该字节数组转换为ByteArrayInputStream,再通过JasperReports提供的JRLoader工具类加载即可得到JasperReport实例。
修改后的控制器代码
@GetMapping("api/V1/pdfDocument/{finDocId}") public ResponseEntity<byte[]> generatePdf(@PathVariable long finDocId) throws Exception { FinancialDocument financialDocument = financialDocumentService.getDocumentById(finDocId); ArrayList<FinancialDocument> documentCollection = new ArrayList<>(); documentCollection.add(financialDocument); JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(documentCollection); Attachment reportAttachment = attachmentService.getAttachmentById(1L); // 关键修改:将字节数组转为输入流,再加载为JasperReport try (ByteArrayInputStream inputStream = new ByteArrayInputStream(reportAttachment.getAttachmentFile())) { JasperReport jasperReport = (JasperReport) JRLoader.loadObject(inputStream); JasperPrint report = JasperFillManager.fillReport(jasperReport, null, beanCollectionDataSource); byte[] data = JasperExportManager.exportReportToPdf(report); HttpHeaders headers = new HttpHeaders(); headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=invoice.pdf"); return ResponseEntity.ok().headers(headers).contentType(MediaType.APPLICATION_PDF).body(data); } }
注意事项
- 确保
reportAttachment.getAttachmentFile()返回的是已编译的.jasper文件字节数组,而非.jrxml源码文件;如果存储的是.jrxml,需要先用JasperCompileManager.compileReport()编译后再使用。 - 使用
try-with-resources语法自动关闭输入流,避免资源泄漏。 - 可根据业务需求添加异常捕获逻辑(如
JRException、IOException),或通过全局异常处理器统一处理。
内容的提问来源于stack exchange,提问作者Sunfile
相关产品推荐
相关产品推荐

