0
@GetMapping(value = "/pdf",produces= MediaType.APPLICATION_PDF_VALUE)
    public ResponseEntity<InputStreamResource> getTermsConditions() throws Exception {

        String filePath = "C:\\";
        String fileName = "PDF.pdf";
        File file = new File(filePath+fileName);
        HttpHeaders headers = new HttpHeaders();
//        headers.add("content-disposition", "inline;filename=" +fileName);
        headers.add("Content-Disposition", "attachment; filename=" + fileName);

        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/pdf"))
                .body(resource);
    }

Open file, but format is incorrect.

���� 6 0 obj << /Type /ExtGState /BM /Normal /ca 1 >> endobj 7 0 obj << /Type /ExtGState /BM /Normal /CA 1 >> endobj 10 0 obj << /Filter /FlateDecode /Length 156465 /Length eP}��&֓�����

Please help me. I want to open book pdf in browser like online library

javaUser
  • 1
  • 1
  • 3
  • I get same error! – Ulviyya Ibrahimli Dec 25 '21 at 14:03
  • It works for me (though it downloads the PDF instead of displaying it in the browser). Can you better describe what happens? What do you mean by "Open file"? In what program is the below output display? What browser are you using? Can you also show the details of the HTTP request (e.g. screen shot from browser's inspector). – Codo Dec 25 '21 at 14:43

1 Answers1

1

Using value "attachment" for response header "Content-Disposition" will download the PDF . Instead of displaying it in new tab.

Value "inline" for response header "Content-Disposition" will open the PDF in new tab in browser.

For example:

v1

headers.add("Content-Disposition", "inline;filename=PDF.pdf");

v2

headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=PDF.pdf");

You can review: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition

Murat Kara
  • 791
  • 4
  • 15
  • It's not "CONTENT_DISPOSITION", it's "CONTENT-DISPOSITION". "CONTENT_DISPOSITION" does not work. – Codo Dec 25 '21 at 16:16
  • i mean this; headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=PDF.pdf"); – Murat Kara Dec 25 '21 at 16:35
  • 1
    You better provide a code example. Otherwise people will write `headers.add("CONTENT_DISPOSITION", ...);` and wonder why it doesn't work. Even better would be `headers.addContentDisposition(ContentDisposition.inline().filename(fileName).build());` – Codo Dec 25 '21 at 16:46
  • @Codo You said is true. I'm updating. – Murat Kara Dec 26 '21 at 10:12