且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

错误:尝试在ASP.NET中操作OPen PDF时出现错误

更新时间:2021-07-27 23:56:18

听起来像您使用aspx文件输出pdf的声音.您是否考虑过使用HttpHandler的ashx文件?它绕过了所有典型的aspx开销内容,并且在提供原始数据方面效率更高.

Sounds like your using an aspx file to output the pdf. Have you considered using an ashx file which is an HttpHandler? It bypasses all the typical aspx overhead stuff and is more efficient for just serving up raw data.

以下是使用您的代码的ashx示例:

Here is an example of the ashx using your code:

<% WebHandler Language="c#" class="ViewPDF" %>
public class ViewPDF : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        FileStream MyFileStream = new FileStream(filePath, FileMode.Open);
        long FileSize = MyFileStream.Length;
        byte[] Buffer = new byte[(int)FileSize + 1];
        MyFileStream.Read(Buffer, 0, (int)MyFileStream.Length);
        MyFileStream.Close();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment; filename="+filePath);
        Response.BinaryWrite(Buffer);
    }

    public bool IsReusable
    {
        get { return false; }
    }
}

如果您仍然想使用aspx页面.确保您正在执行以下操作:

If you still want to use the aspx page. Make sure you are doing the following:

// At the beginning before you do any response stuff do:
Response.Clear();

// When you are done all your response stuff do:
Response.End();

那应该可以解决您的问题.

That should solve your problem.