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

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

我该怎么办?


当前回答

虽然下面的工作很好在firefox,它不工作在chrome和移动浏览器。

Content-Type: application/pdf
Content-Disposition: inline; filename="filename.pdf"

要修复chrome和移动浏览器错误,请执行以下操作:

将文件存储在项目中的某个目录中 使用谷歌PDF查看器

谷歌PDF查看器可以这样使用:

<iframe src="http://docs.google.com/gview?url=http://example.com/path/to/my/directory/pdffile.pdf&embedded=true" frameborder="0"></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");
    }

要么使用

<embed src="file.pdf" />

如果嵌入是一个选项或我的新插件,PIFF: https://github.com/terrasoftlabs/piff

虽然下面的工作很好在firefox,它不工作在chrome和移动浏览器。

Content-Type: application/pdf
Content-Disposition: inline; filename="filename.pdf"

要修复chrome和移动浏览器错误,请执行以下操作:

将文件存储在项目中的某个目录中 使用谷歌PDF查看器

谷歌PDF查看器可以这样使用:

<iframe src="http://docs.google.com/gview?url=http://example.com/path/to/my/directory/pdffile.pdf&embedded=true" frameborder="0"></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>

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

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

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

<FilesMatch "\.(?i:pdf)$">
    ForceType application/octet-stream
    Header set Content-Disposition attachment
</FilesMatch>