2

I have never thought about this before, but is there a way to control what happens when a user clicks a link to a PDF file?

My boss would like to offer two links to do the following: 1. View this PDF in the browser 2. Download the PDF

Is there a way to do this ? I don't think about these kinds of things, most modern browsers will open a PDF in the browser. If I want to download it, I right-click download. Any way to force the action ?

Thanks

jeph perro
  • 6,242
  • 26
  • 90
  • 124
  • 1
    possible duplicate of [Force to open "Save As..." popup open at text link click for pdf in HTML](http://stackoverflow.com/questions/3802510/force-to-open-save-as-popup-open-at-text-link-click-for-pdf-in-html) – James Hill Feb 21 '12 at 20:52

3 Answers3

3

You can link to an asset, or you can stream the data to the browser. Those are the only two options you have on your end.

If you link to a file: <a href="file.pdf"> whether or not it opens in the browser or not is entirely dependent on the end user's browser and operating system preferences.

You can force the download of a file, however by streaming it to the browser, which will usually trigger the browser's save as dialog.

Your best bet, though, from a user experience perspective, is to simply link to the PDF and let the user know that they are about to click on a PDF link...that way they can decide what they do with it.

DA.
  • 39,848
  • 49
  • 150
  • 213
1

There are a few ways using server side technologies:

you can link to a .net / php page that serves the file to download, eg:

<a href="/ServeFile.aspx?filename=sample.pdf">download pdf</a>

or to display:

<a href="/sample.pdf">view pdf</a>

If you are using itextsharp to generate your pdf, you can add the following to the Response object to force a download:

Response.AddHeader(
  "Content-Disposition",
  "attachment; filename=itext.pdf"
);

or the following to open in the same window:

Response.AddHeader(
 "Content-disposition",
 "inline; filename=itext.pdf");   

The user can always set their adobe reader plugin to always download, in which case the browser window display won't work.

Evert
  • 8,161
  • 1
  • 15
  • 17
1

How PDFs are displayed are based on the user's browser version and configuration. For example Chrome includes a PDF viewer by default, but the user has the ability to change the behavior of the plug-in ( automatically open PDFs, disable, ask the user).

One way to do this is to set the ContentType and Content-Disposition so the browser will know how to handle the request. For example in ASP.NET you would do it like this:

Response.ContentType = "application/pdf";

Response.AddHeader("Content-Disposition", "attachment;filename=filename.pdf");

Disclosure: I hijacked this code from this article

Let me know if this helps.

Zaffiro
  • 4,834
  • 5
  • 36
  • 47