当“在浏览器中显示PDF”选项未选中时,是否有一种方法强制PDF文件在浏览器中打开?

我尝试使用嵌入标签和一个iframe,但它只有当该选项被选中时才会工作。

我该怎么办?


当前回答

你可以通过以下方式做到这一点:

<a href="path to PDF file">Open PDF</a>

如果PDF文件在某个文件夹中,而该文件夹没有权限直接访问该文件夹中的文件,那么你必须通过使用.htaccess文件设置绕过一些文件访问限制:

<FilesMatch ".*\.(jpe?g|JPE?G|gif|GIF|png|PNG|swf|SWF|pdf|PDF)$" >
    Order Allow,Deny
    Allow from all
</FilesMatch>

但是现在只允许某些必要的文件。

我已经使用了这段代码,它工作得很完美。

其他回答

从rootfile打开downloads.php。

然后在第186行修改如下:

        if(preg_match("/\.jpg|\.gif|\.png|\.jpeg/i", $name)){
            $mime = getimagesize($download_location);
            if(!empty($mime)) {
                header("Content-Type: {$mime['mime']}");
            }
        }
        elseif(preg_match("/\.pdf/i", $name)){
            header("Content-Type: application/force-download");
            header("Content-type: application/pdf");
            header("Content-Disposition: inline; filename=\"".$name."\";");
        }

        else{
            header("Content-Type: application/force-download");
            header("Content-type: application/octet-stream");
            header("Content-Disposition: attachment; filename=\"".$name."\";");
        }

哎呀,我上一篇文章中有打字错误。

    header("Content-Type: application/force-download");
    header("Content-type: application/pdf");
    header("Content-Disposition: inline; filename=\"".$name."\";");

如果你不想让浏览器提示用户,那就用"inline"代替"attachment"作为第三个字符串。内联工作得很好。PDF立即显示,而不需要用户单击“打开”。我使用了“附件”,这将提示用户打开,保存。我尝试改变浏览器设置螺母,它不能阻止提示。

(我误解了问题,下面的答案是关于强制下载文件而不是在浏览器中打开文件)

如果你使用HTML5(我猜现在每个人都在用HTML5),有一个属性叫做下载。

例如,

<a href="somepathto.pdf" download="filename">

这里filename是可选的,但是如果提供了,它将使用这个名称下载文件。

EDIT

我知道这和问题的答案正好相反。我为那些(像我一样)寻找相反问题的人保留了相反的答案(证据:这个答案的赞票比反对票多)

你可以通过以下方式做到这一点:

<a href="path to PDF file">Open PDF</a>

如果PDF文件在某个文件夹中,而该文件夹没有权限直接访问该文件夹中的文件,那么你必须通过使用.htaccess文件设置绕过一些文件访问限制:

<FilesMatch ".*\.(jpe?g|JPE?G|gif|GIF|png|PNG|swf|SWF|pdf|PDF)$" >
    Order Allow,Deny
    Allow from all
</FilesMatch>

但是现在只允许某些必要的文件。

我已经使用了这段代码,它工作得很完美。

这是ASP的。NET MVC

在你的cshtml页面:

<section>
    <h4><a href="@Url.Action("Download", "Document", new { id = @Model.GUID })"><i class="fa fa-download"></i> @Model.Name</a></h4>
    <object data="@Url.Action("View", "Document", new { id = @Model.GUID })" type="application/pdf" width="100%" height="800" class="col-md-12">
        <h2>Your browser does not support viewing PDFs, click on the link above to download the document.</h2>
    </object>
</section>

在你的控制器中:

public ActionResult Download(Guid id)
    {
        if (id == Guid.Empty)
            return null;

        var model = GetModel(id);

        return File(model.FilePath, "application/pdf", model.FileName);
    }

public FileStreamResult View(Guid id)
    {
        if (id == Guid.Empty)
            return null;

        var model = GetModel(id);

        FileStream fs = new FileStream(model.FilePath, FileMode.Open, FileAccess.Read);

        return File(fs, "application/pdf");
    }