在CHROME中不完整地打开PDF

时间:2015-03-03 20:16:08

标签: c# google-chrome pdf

我试图在Chrome中打开一个pdf文件,但在显示过程中似乎卡在了某个地方的中间位置。代码似乎有效,因为它可以在IE中打开PDF,不知道为什么它会卡在chrome中。屏幕将灰显,显示“加载”标志,并在7/8停止。该文件大约为6MB或更多。

    public static void ReturnPDF(byte[] contents)
    {
        var response = HttpContext.Current.Response;

        response.Clear();
        response.AppendHeader("Content-Disposition", "inline;filename=" + "abc.pdf");

        response.BufferOutput = true;
        response.ContentType = System.Net.Mime.MediaTypeNames.Application.Pdf;
        response.BinaryWrite(contents);

        response.Flush();
        response.Close();

        response.End();
    }

有什么想法?感谢

[UPDATE]

我尝试使用版本30.0的Firefox,它工作正常。我的IE是8.0.7601.17514,也可以打开pdf。我的Chrome是39.0.2171.95。不确定浏览器的版本是否重要,这里只有chrome无法打开内联PDF ...

[解决]

添加内容长度后,chrome可以打开内联PDF。

   public static void ReturnPDF(byte[] contents)
    {
        var response = HttpContext.Current.Response;

        response.Clear();
        response.AppendHeader("Content-Disposition", "inline;filename=" + "abc.pdf");

        //After adding Content-Length, chrome is able to open PDF inline
        response.AppendHeader("Content-Length", contents.Length.ToString());

        response.BufferOutput = true;
        response.ContentType = System.Net.Mime.MediaTypeNames.Application.Pdf;
        response.BinaryWrite(contents);

        response.Flush();
        response.Close();

        response.End();
    }

3 个答案:

答案 0 :(得分:0)

尝试使用"内容处理:附件"报头中。

答案 1 :(得分:0)

感谢mkl的建议。

我在标题中添加了内容长度,并且可以在Chrome中成功打开pdf!

答案 2 :(得分:0)

OP的原始代码创建了这样的响应:

response.Clear();
response.AppendHeader("Content-Disposition", "inline;filename=" + "abc.pdf");
response.BufferOutput = true;
response.ContentType = System.Net.Mime.MediaTypeNames.Application.Pdf;
response.BinaryWrite(contents);
response.End();

此代码尤其不会设置 Content-Length 标头。一些没有该标题的网络浏览器版本(不仅是Chrome,也包括其他浏览器的某些版本)往往会过早地考虑下载完成。

如果非身份转移编码内容长度都没有,那么检测最初创建为持久性的连接的下载何时完成可能并不简单已经提供。

因此,这里的解决方案是添加

response.AppendHeader("Content-Length", contents.Length.ToString());

在写contents之前。

相关问题