Explain Codes LogoExplain Codes Logo

(html) Download a PDF file instead of opening them in browser when clicked

html
download-attribute
server-side-action
browser-compatibility
Anton ShumikhinbyAnton Shumikhin·Oct 10, 2024
TLDR

Initiate PDF download via HTML's download attribute:

<a href="document.pdf" download>Download PDF</a>

Or leverage HTTP headers for control from the server-side:

header('Content-Type: application/pdf'); header('Content-Disposition: attachment; filename="downloaded.pdf"');

Server-magic: Controlling downloads server-side

Fancy some server-side action? Fine-tune your .htaccess configuration to redirect PDF download requests:

<Files "document.pdf"> ForceType application/octet-stream Header set Content-Disposition attachment </Files>

Doing it with a .NET twist? Add these lines to your ASP.NET server config for that PDF funnel:

Response.ContentType = "application/pdf"; Response.AppendHeader("Content-Disposition", "attachment; filename=Document.pdf"); Response.TransmitFile(Server.MapPath("~/Path/To/Document.pdf")); Response.End();

Always check browser compatibility with the HTML5 download attribute on caniuse.com, to ensure your preceding work doesn't go down the drain.

The Deep Dive: Advanced uses and common issues

Quite straightforward, right? Let’s unpack more layers:

1. Customizing file names: An identity crisis

Don't want the original file name? Use download with a value to customize:

<a href="document.pdf" download="CustomName.pdf">Download PDF</a>
#Remember: Spaces in file names can cause chaos in URLs. Keep it simple, avoid the drama.

2. Playing nice with legacy browsers

Older browsers don't understand HTML5? Prepare a server-side or JavaScript fallback:

if (!('download' in document.createElement('a'))) { // Implement the old-folk-friendly code here }
#It's like translating Teen Slang for Grandma. Sometimes you gotta simplify.

3. Mime types: It's all in the label

Make doubly sure that your server is setting the correct Content-Type (application/pdf):

Content-Type: application/pdf
#Because declaring a jackfruit as a pineapple can lead to some awkward questions.

And the Content-Disposition can't go AWOL. If it does, your download attribute might get ignored:

Content-Disposition: attachment; filename="example.pdf"
#It's like leaving your home without an address. Not advisable. At all.

4. Cross-browser eccentricities

Every browser has a personality. Test across various platforms for a consistent user experience.