'SpringBoot base64 pdf downloading

When user makes a get request this should download a pdf file, so far I am getting base64 of the pdf file but I don't know how to download. Can someone help me out?

@ResponseBody
@GetMapping("/download/pdf/{uuid}/{userid}")
public String downloadPdf (@PathVariable String  uuid,@PathVariable String userid, Model model) {
    JSONObject jsonObject = RequestHelper.getResponse("pdf", uuid);
    JSONArray d =(JSONArray) jsonObject.get("data");
    String str = (String) d.get(0);
    byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
    // I have base64 pdf how can I start downloading this pdf



    return("file downloaded");
}


Solution 1:[1]

Add Rest Controller to spring boot project and below method to download pdf file from base64 content.

Assign the pdf base64 string to content variable.

@GetMapping(value = "/donw1")
public ResponseEntity<Resource> donw1() {
    logger.info("Start the file processing");
    String content = "<<Add_pdf_base64 content here>>";
    byte[] decoder = Base64.getDecoder().decode(content);
    InputStream is = new ByteArrayInputStream(decoder);
    InputStreamResource resource = new InputStreamResource(is);
    
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    
    ContentDisposition disposition = ContentDisposition.attachment().filename("textdown.pdf").build();
    headers.setContentDisposition(disposition);
    
    return new ResponseEntity<>(resource, headers, HttpStatus.OK);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Somnath