How to create jasper report in spring boot rest api with jpa

19 Views Asked by At

This is my code for the rest api in spring boot and jpa that has a function of performance report for employees but something is not working here, i dont know what.

Controller:

@GetMapping("/my-report")
public ResponseEntity<?> getReport(String name, String date){
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dateFormat.setLenient(false); // Strict check to ensure the entered string follows the format yyyy-MM-dd
    Date newDate;
    try {
        newDate = dateFormat.parse(date);
    } catch (Exception e) {
        return ResponseEntity.badRequest().body("Invalid date format");
    }
    try {
        byte[] report = service.generateReport(name, newDate);
        if (report == null) { // In case there are no performances for the entered parameters
            return ResponseEntity.ok("No performances found for the given parameters.");
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/pdf"));
        headers.setContentDispositionFormData("attachment", "report.pdf");
        return ResponseEntity.ok()
            .headers(headers)
            .body(report);
    } catch(Exception e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error generating report.");

Service:

public byte[] generateReport(String name, Date date) throws JRException, IOException {
    if (performanceRepository.getPerformances(name, date).size() > 0) {
        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(performanceRepository.getPerformances(name, date));
        InputStream inputStream = this.getClass().getResourceAsStream("/jasperreports/performanceReport.jrxml");
        JasperReport jasperReport = JasperCompileManager.compileReport(inputStream);
        Map<String, Object> params = new HashMap<>();
        params.put("dateParam", date);
        params.put("nameParam", name);
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, dataSource);
        inputStream.close();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        JRPdfExporter exporter = new JRPdfExporter();
        exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(byteArrayOutputStream));
        exporter.exportReport();
        return byteArrayOutputStream.toByteArray();
    }
    return null;
}

Also i didnt forget to add @EntityScan("model") to main java file

0

There are 0 best solutions below