Open Pdf file on web page in Spring boot

3.9k Views Asked by At
@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

1

There are 1 best solutions below

4
On

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