Force to open "Save As..." popup at text link click for PDF in HTML
Using PHP, we can modify the Content-Disposition
header to attachment
to force a "Save As..." dialog to appear for a PDF. Here's some PHP code to demonstrate:
Define clickable link in your HTML that points to the above PHP script:
Voilà! Now, when the link is clicked, the browser will present a "Save As..." dialog instead of opening the PDF file in the browser.
Client-side savior: The download attribute
When the server side seems unapproachable, here's how you can achieve the "Save As..." dialog functionality on the client side:
Did you see that extra download
attribute in the anchor tag? It does all the magic here. It helps you assign a default filename for the downloaded file and it works well with almost all browsers.
Server config hero: .htaccess
If you want the same behavior across your application, you can use Apache's .htaccess
to rewrite the headers for all PDF files. The following example demonstrates forcing a PDF download:
This handy snippet will ensure a uniform user experience, presenting the "Save As..." dialog for each and every embattled PDF in your app.
Troubleshooting: Overcoming limitations and potential complications
While we're at it, let's talk about a couple of things that might not go according to plan:
- Not all browsers support the
download
attribute, check the latest compatibility stats before using it extensively. - The
Content-Disposition
header method might not always work as expected due to different server settings and certain browsers' behavior. - A
target="_blank"
attribute alongsidedownload
opens the PDF in a new tab prior to download. Some users fancy this. - Make sure your error handling game is strong. Perfect code is a myth. You don’t want users to encounter a roadblock without any directions, do you?
Alternatives for the greater Good: Web services for file management
Third-party services like box.net go a long way in terms of handling file downloads while keeping users content and amazed.
The Nerdy Side: Advanced file handling
If you're generating PDF files on the fly using JavaScript, Blob
objects combined with window.URL.createObjectURL
can create a downloadable link.
Always be prepared for the worst. For larger PDFs, you can implement the Accept-Ranges
header that allows users to resume downloads.
Feedback is a dish best served hot
Make sure you collect feedback and keep tabs on user interactions to improve and fine-tune the usability of your implemented solution. Happy users, happy life!
Was this article helpful?