【问题标题】:PDF won't display in browser windowPDF 不会显示在浏览器窗口中
【发布时间】:2014-02-20 19:51:27
【问题描述】:

我正在使用处理程序使用以下代码在浏览器窗口中获取和显示 PDF:

byte[] byt = RetrieveDocument(int.Parse(context.Request.Params["id"]), context.Request.Params["title"]);
string file = WriteDocumentFilePDF(byt);
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("content-length", byt.Length.ToString());
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=programdetails.pdf");
HttpContext.Current.Response.BinaryWrite(byt);
HttpContext.Current.Response.End();

函数 WriteDocumentFilePDF 成功地将 PDF 写入临时目录。我有上面的代码在不同的应用程序中正常工作。我错过了什么吗?

【问题讨论】:

    标签: c# .net pdf ashx


    【解决方案1】:

    在调试此类问题时,我发现 Fiddler 是一个非常宝贵的工具;很多次,它使我免于简单的错误。此外,该站点http://www.c-sharpcorner.com/uploadfile/prathore/what-is-an-ashx-file-handler-or-web-handler/ 提供了一个使用 GIF 图像做同样事情的示例。您的示例和他的示例之间的区别似乎是使用 Response.WriteFile() 而不是使用 BinaryWrite() 直接写入响应。

    我会在设置内容类型之前执行 Response.ClearHeaders(),然后删除对 Response.End() 的调用。

    【讨论】:

      【解决方案2】:

      如果您先将byte[] 传递给memorystream,会有什么不同吗?所以像

      byte[] byt = RetrieveDocument(int.Parse(context.Request.Params["id"]), context.Request.Params["title"]);
      string file = WriteDocumentFilePDF(byt);
      MemoryStream ms = new MemoryStream(byt);
      

      然后添加标题

      HttpContext.Current.Response.ContentType = "application/pdf";    
      HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;  filename=programdetails.pdf");
      HttpContext.Current.Response.BinaryWrite(ms.ToArray());
      HttpContext.Current.Response.End();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-29
        • 2016-11-05
        • 1970-01-01
        • 1970-01-01
        • 2014-06-18
        • 1970-01-01
        • 2022-01-01
        • 1970-01-01
        相关资源
        最近更新 更多