I want to preview a pdf file genereted with java, but the following code gives this error
Unrecognized response type; displaying content as text.
@GetMapping("/previewPDF/{codeStudent}")
public ResponseEntity<byte[]> previewPDF(@PathVariable("codeStudent") String code) throws IOException {
byte[] pdf = //pdf content in bytes
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "inline; filename=" "example.pdf");
headers.setContentType(MediaType.parseMediaType("application/pdf"));
return ResponseEntity.ok().headers(headers).body(pdf);
}
UPDATE: here is a screenshot of the error
CodePudding user response:
You need to specify the response PDF Media Type for your resource.
See RFC standart. Full list of Media Types.
Spring documentation regarding produces Media Type.
@GetMapping(value = "/previewPDF/{codeStudent}", produces = MediaType.APPLICATION_PDF_VALUE)
public ResponseEntity<byte[]> previewPDF(@PathVariable("codeStudent") String code) throws IOException
Set also PDF content type for your ResponseEntity
@GetMapping(value = "/previewPDF/{codeStudent}", produces = MediaType.APPLICATION_PDF_VALUE)
public ResponseEntity<byte[]> previewPDF(@PathVariable("codeStudent") String code) throws IOException {
byte[] pdf = null;
HttpHeaders headers = new HttpHeaders();
String fileName = "example.pdf";
headers.setContentDispositionFormData(fileName, fileName);
headers.setContentType(MediaType.APPLICATION_PDF);
return ResponseEntity.ok().headers(headers).body(pdf);
}