当“在浏览器中显示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>

其他回答

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

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

例如,

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

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

EDIT

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

下面是在PHP中强制在浏览器中查看文件的另一种方法:

$extension = pathinfo($file_name, PATHINFO_EXTENSION);
$url = 'uploads/'.$file_name;
        echo '<html>'
                .header('Content-Type: application/'.$extension).'<br>'
                .header('Content-Disposition: inline; filename="'.$file_name.'"').'<br>'
                .'<body>'
                .'<object   style="overflow: hidden; height: 100%;
             width: 100%; position: absolute;" height="100%" width="100%" data="'.$url.'" type="application/'.$extension.'">
                    <embed src="'.$url.'" type="application/'.$extension.'" />
             </object>'
            .'</body>'
            . '</html>';

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

ob_start ();//在开始

. ./ /你的代码

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

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

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

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

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

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