How do I force files to open in the browser instead of downloading (PDF)?

Solution 1:

To indicate to the browser that the file should be viewed in the browser, the HTTP response should include these headers:

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

To have the file downloaded rather than viewed:

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

The quotes around the filename are required if the filename contains special characters such as filename[1].pdf which may otherwise break the browser's ability to handle the response.

How you set the HTTP response headers will depend on your HTTP server (or, if you are generating the PDF response from server-side code: your server-side programming language).

Solution 2:

The correct type is application/pdf for PDF, not application/force-download. This looks like a hack for some legacy browsers. Always use the correct mimetype if you can.

If you have control over the server code:

  • Forced download/prompt: use header("Content-Disposition", "attachment; filename=myfilename.myextension");
  • Browser tries to open it: use header("Content-Disposition", "inline; filename=myfilename.myextension");

No control over the server code:

  • Use the HTML5 download attribute. It uses the custom filename specified on the view side.

NOTE: I prefer setting the filename on the server side as you may have more information and can use common code.

Solution 3:

If you are using HTML5 (and I guess nowadays everyone uses that), there is an attribute called download.

For example,

<a href="somepathto.pdf" download="filename">

Here filename is optional, but if provided, it will take this name for the downloaded file.