【问题标题】:opening a PDF incompletely in CHROME在 CHROME 中不完整地打开 PDF
【发布时间】:2015-05-04 15:42:46
【问题描述】:

我试图在 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();
    }

有什么想法吗?谢谢

[更新]

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

[已解决]

添加 content-length 后,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();
    }

【问题讨论】:

  • 您不在标头中传输内容长度。有些观众不喜欢这样。
  • @mkl 你是对的。添加内容长度后,chrome终于可以毫无问题地打开了。谢谢
  • @mkl 您可以在下面发布您的答案,以便我可以给您积分。谢谢
  • 您将解决方案编辑到您的问题中。如果问题本质上仍然是一个包括背景的问题,并且您的答案包括解决方案,那就更好了。如果你愿意,我可以代替。
  • @mkl,感谢您的建议。我做了相应的更改,请在下面留下您的答案。谢谢

标签: c# google-chrome pdf


【解决方案1】:

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,还包括其他浏览器的某些版本)往往会过早地认为下载已完成。

如果非身份 Transfer-EncodingContent-Length 都没有已提供。

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

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

在写contents之前。

【讨论】:

    【解决方案2】:

    尝试使用“Content-disposition: attachment”标题。

    【讨论】:

    • 这将强制下载pdf。我在这里想要的是让它在浏览器中强制打开,所以我使用了内联。它可以在 IE 中打开 pdf,但在打开时卡在 chrome 中
    【解决方案3】:

    感谢 mkl 的建议。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-15
      • 1970-01-01
      • 2018-06-18
      • 1970-01-01
      • 1970-01-01
      • 2021-03-01
      • 2014-12-08
      • 1970-01-01
      相关资源
      最近更新 更多