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

2
  • I get same error! Commented Dec 25, 2021 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). Commented Dec 25, 2021 at 14:43

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

It's not "CONTENT_DISPOSITION", it's "CONTENT-DISPOSITION". "CONTENT_DISPOSITION" does not work.
i mean this; headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=PDF.pdf");
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 You said is true. I'm updating.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.