如何使 PDF 文件可在 HTML 链接中下载? [英] How to make PDF file downloadable in HTML link?

查看:47
本文介绍了如何使 PDF 文件可在 HTML 链接中下载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的网页上提供了一个 pdf 文件的链接以供下载,如下所示

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

  • 如果用户安装了 Adob​​e Acrobat,则会在 Adob​​e Reader 的同一浏览器窗口中打开文件.
  • 如果未安装 Adob​​e Acrobat,则会向用户弹出下载文件.

但我希望它总是弹出给用户下载,无论是否安装了Adobe acrobat".

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

请告诉我该怎么做?

推荐答案

不要链接到 .PDF 文件,而是执行类似

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

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

输出自定义标题,打开 PDF(二进制安全)并将数据打印到用户的浏览器,然后他们可以选择保存 PDF,而不管他们的浏览器设置.pdf_server.php 应如下所示:

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:并且显然对file"变量运行一些健全性检查以防止人们窃取您的文件,例如不接受文件扩展名、拒绝斜杠、将 .pdf 添加到值中

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

这篇关于如何使 PDF 文件可在 HTML 链接中下载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆