Search code examples
javaspring-bootitextbackendjfreechart

How to create an endpoint that generates a PDF with the data from the database


I have the following JSON, which comes with the data, inside my database:

[
    {
        "id_process": "87",
        "final_state": "FINISHED",
        "tag_rollgrinder": "LM_170A",
        "tag_roll": "LM170A123",
        "datetime_begin": "2022-09-30T18:15:00Z",
        "datetime_end": "2022-09-30T18:35:00Z",
        "profileRollStartDiameter": "[1, 2, 3]",
        "profileRollStartAdvanceDistance": "[1, 2, 3]"

    }
]

I need to create a functionality in the back-end, through an endpoint (to test in Postman) that creates a PDF file with this data, which comes from the database. However, in the PDF, the attributes "profileRollStartDiameter": "[1, 2, 3]" and "profileRollStartAdvanceDistance": "[1, 2, 3]", need to come in the form of a graph, where the profileRollStartDiameter is data that will be in the Y axis and the RollStartAdvanceDistance profile data will be on the X axis, as shown in the image:

Modelo do gráfico X e Y

Could anyone help me, where could I start? I've tried using IText with PDFPTable, from this link: Spring Boot Export Data to PDF Example to generate the PDF on the endpoint, but it only puts the database data in tables, like cells.


Solution

  • You have to split your task into two steps:

    • Expose endpoint that return PDF file
    @PostMapping()
    public ResponseEntity<byte[]> generatePDF() {
       
        YourData data = fetchDataService.getData();
        byte[] pdfFile = pdfGenerationService.generatePdf(data);
        
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PDF);
        String filename = "yourname.pdf";
        headers.setContentDispositionFormData(filename, filename);
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
        ResponseEntity<byte[]> response = new ResponseEntity<>(pdfFile, headers, HttpStatus.OK);
        return response;
    }
    
    • Handle request and generate PDF

    I will personally go with jasperSoft reports. It's pretty powerful and I never needed another solution.