Search code examples
springspringfox

Spring MVC + Springfox 2.9.2 downloads damaged PDF


I have a Spring MVC project (no SpringBoot) with a GET endpoint which returns a PDF file. The PDF file is either generated manually or read from resources. I also have a SpringFox dependency to generate swagger-ui.html.

Dependency versions:

  • Spring: 4.3.25.RELEASE
  • SpringFox: 2.9.2

The problem is that when I try to download the PDF directly using the "Download file" button then the file is downloaded but somehow corrupted and impossible to open. But when I use the "Request URL" I'm able to download the PDF without any problem. enter image description here

My REST request:

    @RequestMapping(value = "/v1/generatePdfSync", method = RequestMethod.GET)
    public ResponseEntity<Resource> generatePdfSync(@RequestParam String templateName) {
        Map<String, Object> model = new HashMap<>();
        model.put("title", "Hello world!");
        model.put("pages", new ArrayList<>(Arrays.asList(1, 2, 3)));

        byte[] bytes = pdfGenerator.generatePdf(templateName, model);

        // Create response
        ByteArrayResource resource = new ByteArrayResource(bytes);
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .contentLength(resource.contentLength())
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"test.pdf\"")
                .body(resource);
    }

My question is whether I don't have some mistake in the request itself.


Solution

  • The error was mine, this code worked for me:

    @RequestMapping(value = "/v2/generatePdfSync", method = RequestMethod.POST, produces = {MediaType.APPLICATION_PDF_VALUE, MediaType.APPLICATION_OCTET_STREAM_VALUE, MediaType.APPLICATION_JSON_UTF8_VALUE, MediaType.APPLICATION_JSON_VALUE})
        public ResponseEntity<Resource> generatePdfSync(@RequestBody GeneratePdfRequest generatePdfRequest) {
    //        Map<String, Object> model = new HashMap<>();
    //        model.put("title", "Hello world!");
    //        model.put("pages", new ArrayList<>(Arrays.asList(1, 2, 3)));
    
            LOGGER.info("GeneratePdfSync: {}", generatePdfRequest);
    
            byte[] bytes = pdfGenerator.generatePdf(generatePdfRequest.getTemplateName(), generatePdfRequest.getTemplateModel());
    
            // Create response
            ByteArrayResource resource = new ByteArrayResource(bytes);
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .contentLength(resource.contentLength())
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + generatePdfRequest.getResultPdfName() + "\"")
                    .body(resource);
        }