如何强制下载PDF?

How to force a PDF download?

问题

我正在提供 PDF 供访问者下载。目前我只提供一个 link 供访问者点击。但是,如果他们的 PC 上有 PDF 软件,PDF 将在浏览器中打开。当然,我可以告诉用户右键单击 link 并选择 'save target as',但我更希望下载会在页面加载时弹出,就像您在许多主要下载网站上看到的那样。

我的问题

如何在页面加载时为访问者提供下载?这可以使用 PHP 或 jQuery/javascript.

$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;

这是一个简单的PHP解决方案:

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');