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

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

我该怎么办?


当前回答

这是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");
    }

其他回答

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

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

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

对于大文件,你需要让你的输出缓冲区开始添加

ob_start ();//在开始

. ./ /你的代码

Ob_clean();//在文件的末尾

如果你有Apache,把这个添加到。htaccess文件中:

<FilesMatch "\.(?i:pdf)$">
    ForceType application/octet-stream
    Header set Content-Disposition attachment
</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");
    }

我也有同样的问题,上面的大部分答案应该可以解决你的问题。不幸的是,即使我在响应中收到了内容类型和内容处理标题,但我的pdf仍然是被下载而不是被查看。经过几个小时的头脑风暴和尝试。

罪魁祸首是火狐,在某种程度上是我。紧张的笑声

默认情况下,当你在firefox中打开一个pdf文件时,它会弹出一个窗口,让你保存pdf文件或直接打开它,还有一个复选框告诉你从现在开始自动执行这个操作,猜猜是谁选择了它。

由于这个错误,我的pdf文件被下载而不是被查看,即使有所有必要的标题响应。这是一个简单的错误,但却花费了我大量的时间。

要解决这个问题,只需进入设置,搜索应用程序,并将pdf设置更改为您需要的任何设置。