RubyRedGrapefruit
RubyRedGrapefruit

Reputation: 12224

How can I force a link to a PDF to tell the browser to download it as a PDF?

My application generates a dynamic link to any PDF files that are associated with a product. The link is presented like this:

<a href="http://mysite.net/mylink.pdf?uid=db5f3dc108594b34a86ad52c8686ade5%2FMyCompany&amp;expires=1324049275&amp;signature=jrSF87xtHkQDCTvOek6uuMacPRc%3D" target="_blank">Brochure</a>

If the user right-clicks and selects "Download Linked File As" (or its equivalent), the file is presented with a ".pdf.png" extension in Google Chrome and Safari. Firefox works appropriately, not sure about Internet Explorer.

I want Firefox and Chrome to know that it is a PDF. Because obviously users are going to try to download these, they are going to save it with the wrong extension, and they won't be able to open the file.

Upvotes: 1

Views: 1184

Answers (3)

dmcnally
dmcnally

Reputation: 771

Assuming you are using "send_data" from within a rails controller to serve the file might I suggest:

send_data(
    data, 
    :filename => "filename.pdf",
    :disposition => "attachment",
    :type => 'application/pdf'
  )

Where "data" is the contents of the PDF.

For more information checkout the following link:

http://api.rubyonrails.org/classes/ActionController/DataStreaming.html#method-i-send_data

Upvotes: 3

Sir Crispalot
Sir Crispalot

Reputation: 4854

Have you heard of the content-disposition header? It allows you to tell the browser to ask the user what to do with the file, rather than try and handle it by itself. I don't think it is part of the HTTP spec, but it is documented by the IETF under RFC 2183.

You should be able to use whatever language you are using to alter the HTTP headers before they go to the client. The header you add will look something like this:

Content-Disposition: attachment; filename=filename.pdf

You might also need a Content-Type header:

Content-Type: application/pdf

Upvotes: 0

BugTheLady
BugTheLady

Reputation: 35

send proper headers in some scripting lang like php or user .htaccess

<Files *.pdf>
  ForceType application/pdf
  Header set Content-Disposition attachment
</Files>

Upvotes: 0

Related Questions