Spring - display PDF-file in browser instead of downloading
i am trying to display a pdf in my browser with spring. my problem is that the browser downloads the file instead of displaying it. this is my code:
@RequestMapping(value="/getpdf1", method=RequestMethod.GET)
public ResponseEntity<byte[]> getPDF1() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String filename = "pdf1.pdf";
headers.add("content-disposition", "inline;filename=" + filename);
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(pdf1Bytes, headers, HttpStatus.OK);
return response;
}
i am looking forward to your answers! thanks
Content-Disposition to control either download or view in browser
View in browser
headers.add("Content-Disposition", "inline; filename=" + "example.pdf");
Download
headers.add("Content-Disposition", "attachment; filename=" + "example.pdf");
You are almost done. Just remove
headers.setContentDispositionFormData(filename, filename);
from your code block. It should be used when posting multipart/form-data to the server.
Below code Snippet will assist you display the file on the browser
@GetMapping(value = "/terms-conditions")
public ResponseEntity<InputStreamResource> getTermsConditions() {
String filePath = "/path/to/file/";
String fileName = "fileName.pdf";
File file = new File(filePath+fileName);
HttpHeaders headers = new HttpHeaders();
headers.add("content-disposition", "inline;filename=" +fileName);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/pdf"))
.body(resource);
}