You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 05:10:40