Reputation: 118
I'm trying to create a PDF and then download it automatically. I'm using PDFBox to create the PDF and it saves locally just fine but as soon as I return it via ResponseEntity
or byte[]
it becomes blank. I want to use a post because I want to send a body of parameters that I need for the PDF.
Here's my controller
@PostMapping(value="/documents/generate")
ResponseEntity<?> generateSampleTag(@RequestBody SampleTag sampleTag) {
log.info("inside generatePdfFromHtml method in DocumentController");
try(ByteArrayOutputStream byteArrayOutputStream = freePdfService.generatePdf(sampleTag)) {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE);
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=sampleTag.pdf");
headers.add("Expires", "0");
headers.setCacheControl(CacheControl.noCache());
headers.add("Pragma", "public");
ByteArrayResource resource = new ByteArrayResource(byteArrayOutputStream.toByteArray());
return new ResponseEntity<>(resource, headers, HttpStatus.OK);
} catch (Exception e) {
log.error(e.getMessage());
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
I've been trying a variety of input/output streams and header values and I'm just guessing at this point. Thanks for the help!
I answered below but my issue was Swagger couldn't download it correctly. Postman worked.
Upvotes: 0
Views: 4749
Reputation: 118
My issue was that Swagger couldn't download my PDF correctly. I tried it in Postman and it worked...
Upvotes: 2
Reputation: 21
I have not used PDFBox but it has worked for me before to send an inputStream as a response with a PDF mime type header.
Something like...
ByteArrayOutputStream byteArrayOutputStream = freePdfService.generatePdf(sampleTag)
headers.setContentType(MediaType.parseMediaType(MediaType.APPLICATION_PDF_VALUE));
return new ResponseEntity<>(new InputStreamResource(byteArrayOutputStream), headers, HttpStatus.OK);
Upvotes: 2