如何强制PDF下载?

时间:2015-01-13 09:29:01

标签: php jquery download

问题

我正在向访问者提供PDF下载。目前我只是提供了一个供访问者点击的链接。但是,如果他们的PC上有PDF软件,PDF将在浏览器中打开。当然,我可以告诉用户右键单击该链接并选择“将目标另存为”,但我宁愿在页面加载时弹出下载,就像您在许多主要下载网站上看到的那样。

我的问题

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

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:1)

这是一个简单的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');