Daniel Kaplan
Daniel Kaplan

Reputation: 67504

How do you open a PDF in a new tab and show it in the browser (don't ask to download)?

I have a link to a PDF and when I click on it I want it to open a new tab and render in the new tab as opposed to asking me to download it. How do I do that?

note, I'm asking this question so I can answer it. This information can be pieced together from other answers, but I'd like it to be all in one place

Upvotes: 7

Views: 18970

Answers (2)

codigoalvo
codigoalvo

Reputation: 1

The secret is using InputStreamResource in method response instead as ResponseEntity:

@GetMapping(path = "/pdf/{key}", produces = MediaType.APPLICATION_PDF_VALUE)
@ResponseBody
public InputStreamResource pdf(@PathVariable("key") String key){
    InputStream file = pdfservice.get(key);
    return new InputStreamResource(file);
}

Upvotes: 0

Daniel Kaplan
Daniel Kaplan

Reputation: 67504

To open a link in a new tab (PDF or not) you must modify the HTML of that link from

<a href="/link_to_pdf.pdf">PDF</a>

to

<a href="/link_to_pdf.pdf" target="_blank">PDF</a>

To open a PDF in the browser you must make a server side change to the response header. In Java, you would do this:

response.setContentType("application/pdf");
response.addHeader("content-disposition", "inline; filename=link_to_pdf.pdf");

Of key importance is the inline. If you put attachment, your browser will try to download it instead. You can read more here.

Upvotes: 15

Related Questions