How To Make PDF File Downloadable In HTML Link? - Stack Overflow

Just browsing Stack Overflow? Help us improve your experience. Sign up for research
    1. Home
    2. Questions
    3. Tags
    4. Users
    5. Companies
    6. Labs
    7. Jobs
    8. Discussions
    9. Collectives
    10. Communities for your favorite technologies. Explore all Collectives

  1. Teams

    Ask questions, find answers and collaborate at work with Stack Overflow for Teams.

    Try Teams for free Explore Teams
  2. Teams
  3. Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Get early access and see previews of new features.

Learn more about Labs How to make PDF file downloadable in HTML link? Ask Question Asked 15 years, 11 months ago Modified 4 years ago Viewed 836k times Part of PHP Collective 155

I am giving link of a pdf file on my web page for download, like below

<a href="myfile.pdf">Download Brochure</a>

The problem is when user clicks on this link then

  • If the user have installed Adobe Acrobat, then it opens the file in the same browser window in Adobe Reader.
  • If the Adobe Acrobat is not installed then it pop-up to the user for Downloading the file.

But I want it always pop-up to the user for download, irrespective of "Adobe acrobat" is installed or not.

Please tell me how i can do this?

Share Improve this question Follow edited Feb 9, 2012 at 10:22 Rob W's user avatar Rob W 348k87 gold badges807 silver badges682 bronze badges asked Dec 13, 2008 at 7:09 djmzfKnm's user avatar djmzfKnmdjmzfKnm 27.2k70 gold badges171 silver badges232 bronze badges Add a comment |

14 Answers 14

Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 264

This is a common issue but few people know there's a simple HTML 5 solution:

<a href="./directory/yourfile.pdf" download="newfilename">Download the pdf</a>

Where newfilename is the suggested filename for the user to save the file. Or it will default to the filename on the serverside if you leave it empty, like this:

<a href="./directory/yourfile.pdf" download>Download the pdf</a>

Compatibility: I tested this on Firefox 21 and Iron, both worked fine. It might not work on HTML5-incompatible or outdated browsers. The only browser I tested that didn't force download is IE...

Check compatibility here: http://caniuse.com/#feat=download

Share Improve this answer Follow edited Jun 2, 2016 at 15:37 Martin Gottweis's user avatar Martin Gottweis 2,73915 silver badges27 bronze badges answered Jun 9, 2013 at 15:46 T_D's user avatar T_DT_D 3,3013 gold badges18 silver badges24 bronze badges 6
  • 9 This is a simple solution but unfortunately not very widely supported, esp. no support by IE caniuse.com/#feat=download – benebun Commented Nov 13, 2013 at 15:44
  • 2 Yep, I know right. That's why I have the side-note on compatibility. And according to your source both IE and Safari don't support this approach, or at least not yet :) Anyhow, if you want all browsers to force download I suggest checking some of the other answers instead... – T_D Commented Nov 14, 2013 at 16:23
  • 3 works like a charm with chrome Version 39.0.2171.65 (64-bit) ! – edelans Commented Nov 21, 2014 at 20:32
  • The solution is easy but unfortunately not supported in IE and Safari. – valkirilov Commented Jul 14, 2016 at 10:25
  • says no permission to access – Abdulla Sirajudeen Commented Aug 7, 2018 at 3:54
| Show 1 more comment 121

Instead of linking to the .PDF file, instead do something like

<a href="pdf_server.php?file=pdffilename">Download my eBook</a>

which outputs a custom header, opens the PDF (binary safe) and prints the data to the user's browser, then they can choose to save the PDF despite their browser settings. The pdf_server.php should look like this:

header("Content-Type: application/octet-stream"); $file = $_GET["file"] .".pdf"; header("Content-Disposition: attachment; filename=" . urlencode($file)); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); header("Content-Description: File Transfer"); header("Content-Length: " . filesize($file)); flush(); // this doesn't really matter. $fp = fopen($file, "r"); while (!feof($fp)) { echo fread($fp, 65536); flush(); // this is essential for large downloads } fclose($fp);

PS: and obviously run some sanity checks on the "file" variable to prevent people from stealing your files such as don't accept file extensions, deny slashes, add .pdf to the value

Share Improve this answer Follow edited Mar 30, 2017 at 18:27 answered Dec 13, 2008 at 7:18 TravisO's user avatar TravisOTravisO 9,5304 gold badges39 silver badges45 bronze badges 13
  • 2 I am facing another problem with this, that my file is located at /products/brochure/myfile.pdf I am giving $file variable as $file_path = $_SERVER['DOCUMENT_ROOT'].'/products/brochure/' . $file; but its downloading the file as "%2Fvar%2Fwww%2Fweb15%2Fweb%2Fproducts%2Fbrochure%2myfile.pdf" – djmzfKnm Commented Dec 13, 2008 at 10:11
  • 3 @TravisO "Content-type: application/force-download" isn't listed anywhere here: iana.org/assignments/media-types/application It's a completely bogus header. Please don't make up headers and send them. Could you update your answer. Thanks. – Nicholas Wilson Commented Aug 28, 2013 at 15:37
  • 4 Be careful when using this code verbatim, though. This introduces a serious LFI vulnerability, as you're passing GET-variables directly into fopen. – Joost Commented Feb 25, 2015 at 12:48
  • 4 This code is likely dangerous in another way. If you pass HTTP links to fopen, I think it'll go retrieve the file from another server. Could be used by an attacker to attempt to scan your internal network for exposed PDF files. – Rory McCune Commented Sep 4, 2015 at 12:24
  • 2 Not to mention how easy it would be to bypass any "sanity checks" you think you'll be doing to the "file" parameter. Path injection / directory traversal attacks are extremely likely. – AviD Commented Sep 4, 2015 at 13:18
| Show 8 more comments 49

Don't loop through every file line. Use readfile instead, its faster. This is off the php site: http://php.net/manual/en/function.readfile.php

$file = $_GET["file"]; if (file_exists($file)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header("Content-Type: application/force-download"); header('Content-Disposition: attachment; filename=' . urlencode(basename($file))); // header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); exit; }

Make sure to sanitize your get variable as someone could download some php files...

Share Improve this answer Follow answered Nov 14, 2011 at 13:35 Alex V's user avatar Alex VAlex V 18.3k6 gold badges38 silver badges35 bronze badges 1
  • 5 The readfile function is indeed faster. I personally recommend using this answer instead of the accepted one – Jose Garrido Commented Feb 4, 2013 at 21:08
Add a comment | 25

Instead of using a PHP script, to read and flush the file, it's more neat to rewrite the header using .htaccess. This will keep a "nice" URL (myfile.pdf instead of download.php?myfile).

<FilesMatch "\.pdf$"> ForceType applicaton/octet-stream Header set Content-Disposition attachment </FilesMatch> Share Improve this answer Follow edited Dec 26, 2013 at 9:16 answered Feb 9, 2012 at 10:24 Rob W's user avatar Rob WRob W 348k87 gold badges807 silver badges682 bronze badges 3
  • Wouldn't this make ALL your PDFs force download? – TecBrat Commented Sep 26, 2014 at 14:54
  • 1 @TecBrat Yes, but that was what the OP asked. If you want to limit to a few PDFs only, edit the ^\.pdf$ regular expression. – Rob W Commented Sep 26, 2014 at 14:55
  • 2 @TecBrat or put the .htaccess file only in the subfolder where this behavior is needed. – habakuk Commented Mar 5, 2015 at 12:00
Add a comment | 15

I found a way to do it with plain old HTML and JavaScript/jQuery that degrades gracefully. Tested in IE7-10, Safari, Chrome, and FF:

HTML for download link:

<p>Thanks for downloading! If your download doesn't start shortly, <a id="downloadLink" href="...yourpdf.pdf" target="_blank" type="application/octet-stream" download="yourpdf.pdf">click here</a>.</p>

jQuery (pure JavaScript code would be more verbose) that simulates clicking on link after a small delay:

var delay = 3000; window.setTimeout(function(){$('#downloadLink')[0].click();},delay);

To make this more robust you could add HTML5 feature detection and if it's not there then use window.open() to open a new window with the file.

Share Improve this answer Follow edited Dec 20, 2013 at 20:58 answered Aug 6, 2013 at 14:59 Alex W's user avatar Alex WAlex W 38.1k13 gold badges111 silver badges114 bronze badges Add a comment | 8

This is the key:

header("Content-Type: application/octet-stream");

Content-type application/x-pdf-document or application/pdf is sent while sending PDF file. Adobe Reader usually sets the handler for this MIME type so browser will pass the document to Adobe Reader when any of PDF MIME types is received.

Share Improve this answer Follow answered Dec 13, 2008 at 7:27 Sudden Def's user avatar Sudden DefSudden Def 10.4k3 gold badges20 silver badges8 bronze badges Add a comment | 5

This can be achieved using HTML.

<a href="myfile.pdf">Download Brochure</a>

Add download attribute to it: Here the file name will be myfile.pdf

<a href="myfile.pdf" download>Download Brochure</a>

Specify a value for the download attribute:

<a href="myfile.pdf" download="Brochure">Download Brochure</a>

Here the file name will be Brochure.pdf

Share Improve this answer Follow answered Nov 19, 2020 at 11:30 Okiemute Gold's user avatar Okiemute GoldOkiemute Gold 5483 silver badges10 bronze badges 2
  • Sorry, not working, it will replace the current URL of the browser to pdf url – Aljohn Yamaro Commented May 21, 2021 at 5:43
  • Not working, FYI: my pdf link is a aws s3 link – Farhan Syed Commented Aug 24, 2023 at 21:22
Add a comment | 2

I know I am very late to answer this but I found a hack to do this in javascript.

function downloadFile(src){ var link=document.createElement('a'); document.body.appendChild(link); link.href= src; link.download = ''; link.click(); } Share Improve this answer Follow answered Feb 24, 2017 at 18:48 Shivek Parmar's user avatar Shivek ParmarShivek Parmar 2,9932 gold badges35 silver badges42 bronze badges Add a comment | 0

Try this:

<a href="pdf_server_with_path.php?file=pdffilename&path=http://myurl.com/mypath/">Download my eBook</a>

The code inside pdf_server_with_path.php is:

header("Content-Type: application/octet-stream"); $file = $_GET["file"] .".pdf"; $path = $_GET["path"]; $fullfile = $path.$file; header("Content-Disposition: attachment; filename=" . Urlencode($file)); header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); header("Content-Description: File Transfer"); header("Content-Length: " . Filesize($fullfile)); flush(); // this doesn't really matter. $fp = fopen($fullfile, "r"); while (!feof($fp)) { echo fread($fp, 65536); flush(); // this is essential for large downloads } fclose($fp); Share Improve this answer Follow edited Oct 19, 2012 at 22:14 Peter O.'s user avatar Peter O. 32.8k14 gold badges84 silver badges97 bronze badges answered Jun 21, 2012 at 2:15 Saill's user avatar SaillSaill 92 bronze badges Add a comment | 0

Here's a different approach. I prefer rather than to rely on browser support, or address this at the application layer, to use web server logic.

If you are using Apache, and can put an .htaccess file in the relevant directory you could use the code below. Of course, you could put this in httpd.conf as well, if you have access to that.

<FilesMatch "\.(?i:pdf)$"> Header set Content-Disposition attachment </FilesMatch>

The FilesMatch directive is just a regex so it could be set as granularly as you want, or you could add in other extensions.

The Header line does the same thing as the first line in the PHP scripts above. If you need to set the Content-Type lines as well, you could do so in the same manner, but I haven't found that necessary.

Share Improve this answer Follow answered Nov 29, 2016 at 16:52 Evan Donovan's user avatar Evan DonovanEvan Donovan 7569 silver badges18 bronze badges Add a comment | -1

In a Ruby on Rails application (especially with something like the Prawn gem and the Prawnto Rails plugin), you can accomplish this a little more simply than a full on script (like the previous PHP example).

In your controller:

def index respond_to do |format| format.html # Your HTML view format.pdf { render :layout => false } end end

The render :layout => false part tells the browser to open up the "Would you like to download this file?" prompt instead of attempting to render the PDF. Then you would be able to link to the file normally: http://mysite.com/myawesomepdf.pdf

Share Improve this answer Follow answered Dec 13, 2008 at 7:49 btw's user avatar btwbtw 7,1569 gold badges41 silver badges40 bronze badges 3
  • Where to wrote this code? which controller, i am new to PHP please explain. – djmzfKnm Commented Dec 13, 2008 at 8:01
  • @Prashant This is not PHP, it's Ruby on Rails. – eloyesp Commented Feb 22, 2013 at 17:47
  • @Prashant: If you need a PHP example, look at the ones further up the thread, but please read the comments about how they could be insecure. – Evan Donovan Commented Nov 29, 2016 at 16:54
Add a comment | -1

I solved mine using the whole url of the PDF file (Instead of just putting the file name or location to href): a href="domain . com/pdf/filename.pdf"

Share Improve this answer Follow answered Jun 5, 2017 at 11:05 Mark Allena's user avatar Mark AllenaMark Allena 1 Add a comment | -1 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>File Uploader</title> <script src="../Script/angular1.3.8.js"></script> <script src="../Script/angular-route.js"></script> <script src="../UserScript/MyApp.js"></script> <script src="../UserScript/FileUploder.js"></script> <> .percent { position: absolute; width: 300px; height: 14px; z-index: 1; text-align: center; font-size: 0.8em; color: white; } .progress-bar { width: 300px; height: 14px; border-radius: 10px; border: 1px solid #CCC; background-image: -webkit-gradient(linear, left top, left bottom, from(#6666cc), to(#4b4b95)); border-image: initial; } .uploaded { padding: 0; height: 14px; border-radius: 10px; background-image: -webkit-gradient(linear, left top, left bottom, from(#66cc00), to(#4b9500)); border-image: initial; } </> </head> <body ng-app="MyApp" ng-controller="FileUploder"> <div> <table ="width:100%;border:solid;"> <tr> <td>Select File</td> <td> <input type="file" ng-model-instant id="fileToUpload" onchange="angular.element(this).scope().setFiles(this)" /> </td> </tr> <tr> <td>File Size</td> <td> <div ng-repeat="file in files.slice(0)"> <span ng-switch="file.size > 1024*1024"> <span ng-switch-when="true">{{file.size / 1024 / 1024 | number:2}} MB</span> <span ng-switch-default>{{file.size / 1024 | number:2}} kB</span> </span> </div> </td> </tr> <tr> <td> File Attach Status </td> <td>{{AttachStatus}}</td> </tr> <tr> <td> <input type="button" value="Upload" ng-click="fnUpload();" /> </td> <td> <input type="button" value="DownLoad" ng-click="fnDownLoad();" /> </td> </tr> </table> </div> </body> </html> Share Improve this answer Follow answered Feb 6, 2019 at 8:38 user11021789's user avatar user11021789user11021789 1 1
  • 3 You should explain what you have provided in your code. Even in short form if not possible in details or not required in details. – Suraj Kumar Commented Feb 6, 2019 at 8:41
Add a comment | -2

if you need to limit download rate, use this code !!

<?php $local_file = 'file.zip'; $download_file = 'name.zip'; // set the download rate limit (=> 20,5 kb/s) $download_rate = 20.5; if(file_exists($local_file) && is_file($local_file)) { header('Cache-control: private'); header('Content-Type: application/octet-stream'); header('Content-Length: '.filesize($local_file)); header('Content-Disposition: filename='.$download_file); flush(); $file = fopen($local_file, "r"); while(!feof($file)) { // send the current file part to the browser print fread($file, round($download_rate * 1024)); // flush the content to the browser flush(); // sleep one second sleep(1); } fclose($file);} else { die('Error: The file '.$local_file.' does not exist!'); } ?>

For more information click here

Share Improve this answer Follow answered Feb 6, 2019 at 5:30 Mehran Hooshangi's user avatar Mehran HooshangiMehran Hooshangi 52 bronze badges Add a comment | Highly active question. Earn 10 reputation (not counting the association bonus) in order to answer this question. The reputation requirement helps protect this question from spam and non-answer activity.

Not the answer you're looking for? Browse other questions tagged or ask your own question.

PHP Collective Join the discussion This question is in a collective: a subcommunity defined by tags with relevant content and experts.
  • The Overflow Blog
  • Your docs are your infrastructure
  • Featured on Meta
  • More network sites to see advertising test [updated with phase 2]
  • We’re (finally!) going to the cloud!

Linked

-1 PHP: Trying to make a pdf file downloadable 0 how to download data from current PHP webpage 38 How to force a Download File prompt instead of displaying it in-browser with HTML? 10 Download Link not working in html 3 Zend_PDF: Remove html contents from PDF document -2 HTML Link, to save a file to my computer. 1 how to pass number of hits count based on button action in php 2 download image from unsplash Api in js 0 Download with PHP --> ERR_CONTENT_LENGTH_MISMATCH 0 How to offer downloadable invoices on a website without giving the file direct http access? See more linked questions 6 Implementing "Download as PDF" on a PHP web page 0 How can the image and pdf files be made downloadable 0 converting extracted html content in to pdf and giving option to download using php 1 downloading pdf file using php and html link 0 Force download html to pdf using php 2 Download pdf from href link issue 2 Downloading PDF to Browser 1 Php convert html to pdf and download 0 How to put a downloadable pdf link in html 0 Downloading pdf file directly from database

Hot Network Questions

  • cartridge style bottom bracket temperature range
  • How to identify unsafe trees for climbing stand?
  • What plan has Trump proposed to mitigate the predicted inflationary effect of tariffs?
  • Non-reflexive use of laisser without a direct object in « The Stranger » ?
  • Does ambigous license without a version refer to most recent? Is 'AGPL' currently equivalent to 'AGPL-3.0-only'?
  • Difference between English short stories and short English stories
  • Can this strong directional blur at wide apertures still be explained by the usual arguments?
  • Correct place to store data required for custom addon
  • What determines your “awareness” when it comes to being criminally responsible for murder?
  • Is it possible to use NAS hard drives in a desktop?
  • Arrange 3 red balls and 33 white balls randomly in a circle. What is the probability that there are no more than 13 consecutive white balls?
  • War Magic feature with a Heavy Crossbow
  • What is the name of the lady with the white blouse?
  • How to demystify why my degree took so long on my CV
  • Burned washing machine plug
  • Is ATL-98 Carvair still alive in the US?
  • Implicit function theorem without manifolds (Steve Smale article)?
  • Person of interest/under investigation living abroad - what can the UK police do?
  • Does length contraction "break the speed limit"?
  • A fantasy movie with two races, "Big Ones" (=us) and smaller ones, about saving a newborn baby from a cruel queen
  • If the hard problem of consciousness is unanswerable, is it a hard problem or just a bad question?
  • A roulette wheel? An AC Milan kit? Darth Maul's face?
  • Are prenups legally binding in England?
  • How to delete faces that intersect an edge with geometry nodes?
more hot questions Question feed Subscribe to RSS Question feed

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

default

Từ khóa » Html And Css Pdf File Download