0

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 = "/download" , method=RequestMethod.GET , produces = "application/pdf")
public ResponseEntity<InputStreamResource> downloadPdf() throws IOException {
    ClassPathResource pdfFile = new ClassPathResource("TMOBILE.pdf");
    return ResponseEntity
            .ok()
            .contentLength(pdfFile.contentLength())
            .contentType(
                    MediaType.parseMediaType("application/octet-stream"))
            .body(new InputStreamResource(pdfFile.getInputStream()));

}

i am looking forward to your answers! thanks

  • Possible duplicate of [Display PDF within web browser](https://stackoverflow.com/questions/4853898/display-pdf-within-web-browser) – gonzaloan Dec 04 '18 at 19:14

3 Answers3

3

Change your headers to this:

Content-Type: application/pdf
Content-Disposition: inline; filename="filename.pdf"

Setting the Content-Type to application/octet-stream will FORCE it to always download.

Andrew T Finnell
  • 13,417
  • 3
  • 33
  • 49
0

Use Content-Type application/pdf instead of application/octet-stream

Mykhailo Moskura
  • 2,073
  • 1
  • 9
  • 20
-1

Combining your code & Andrew answer above this modified code works fine !!

@RequestMapping(value = "/download" , method=RequestMethod.GET)
     public ResponseEntity<InputStreamResource> downloadPdf() throws IOException {
         ClassPathResource pdfFile = new ClassPathResource("files/Locations.pdf");
         return ResponseEntity
                 .ok()
                 .contentLength(pdfFile.contentLength())
                 .header("Content-Disposition", "inline; filename=\"" + pdfFile.getFilename() + "\"")
                 .contentType(
                         MediaType.parseMediaType("application/pdf"))
                 .body(new InputStreamResource(pdfFile.getInputStream()));

     }
Jay Yadav
  • 236
  • 1
  • 2
  • 10