Search code examples
javaspring-bootcontrollerjasper-reports

JasperReport .jasper-file from database


I'm working with jasperreports in my Springboot project. I can generate a PDF based on data and a .jasper-file in my resources folder. However, I want no .jasper-file in my resourcesfolder, I want to save the .jasper-file as a bytearray in my database.

I can't figure out how to create a jasperReport object from the attachment, please advice.

Here is my controller for returning the created report.

@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 jasperReport = new 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);
    //return null;
}

Here is my attachment class

public class Attachment {

private Long attachmentId;
private String attachmentName;
private String attachmentType;
private byte[] attachmentFile;

}


Solution

  • Just take the byte array that contains the Jasper report design and wrap it into a ByteArrayInputStream:

    Attachment reportAttachment = attachmentService.getAttachmentById(1L);
    ByteArrayInputStream inputStream = new ByteArrayInputStream(reportAttachment.attachmentFile);
    JasperPrint report = JasperFillManager.fillReport(inputStream, null, beanCollectionDataSource);