1

The problem

I am offering a PDF for download to my visitors. At the moment I just supply a link for the visitors to click. However, if they have PDF software on their PC's the PDF will open in the browser. Of course I could tell the users to right-click the link and choose 'save target as' but I'd rather the download would popup on page load as you see on a lot of major download websites.

My question

How can I serve a download to my visitors on page load? This could be using either PHP or jQuery/javascript.

  • http://stackoverflow.com/questions/1878208/how-can-i-create-a-download-link-of-a-pdf-that-does-not-require-a-right-click?rq=1 have a look at this – Count Jan 13 '15 at 09:32

2 Answers2

1
$filename="whatever_file.pdf";
// required for IE, otherwise Content-disposition is ignored
if (ini_get('zlib.output_compression'))
    ini_set('zlib.output_compression', 'Off');

// addition by Jorg Weske
$file_extension = strtolower(substr(strrchr($filename,"."),1));

if ($filename == "") {
    echo "<html><title>eLouai's Download Script</title><body>ERROR: download file NOT SPECIFIED. USE force-download.php?file=filepath</body></html>";
    exit;
} elseif (!file_exists($filename)) {
    echo "<html><title>eLouai's Download Script</title><body>ERROR: File:$filename not found. USE force-download.php?file=filepath</body></html>";
    exit;
}

header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: application/pdf");
// change, added quotes to allow spaces in filenames, by Rajkumar Singh
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile($filename);
exit;
Peter
  • 8,776
  • 6
  • 62
  • 95
1

Here is a simple PHP solution:

header("Content-type:application/pdf");
// Set the name of the downloaded file here:
header("Content-Disposition:attachment;filename='example.pdf'"); 
 // Get the contents of the original file:
echo file_get_contents('example.pdf');
Samuil Banti
  • 1,735
  • 1
  • 15
  • 26
  • Why is your answer so much smaller then the other one. What's the difference? –  Jan 13 '15 at 10:03
  • It contains only two headers. That should be enough in this case but if you need to set any additional information you are free to add more. – Samuil Banti Jan 13 '15 at 10:15