Shyju
Shyju

Reputation: 218702

Error: while trying to OPen PDF in ASP.NET

In my ASP.NET application,When I try to open PDF file by using the below code, I am getting an error

CODE USED TO SHOW PDF FILE

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);

ERROR I AMN GETTING

"There was an error opening this document.The file is damaged and could not open"

Upvotes: 0

Views: 2546

Answers (3)

Kelsey
Kelsey

Reputation: 47726

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.

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; }
    }
}

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.

Upvotes: 1

Kevin Pullin
Kevin Pullin

Reputation: 13327

In addition to ocedcio's reply, you need to be aware that Stream.Read() does not necessarily read all of the bytes requested. You should examine the return value from Stream.Read() and continue reading if less bytes are read than requested.

See this question & answer for the details: Creating a byte array from a stream

Upvotes: 0

Ot&#225;vio D&#233;cio
Ot&#225;vio D&#233;cio

Reputation: 74250

You must flush the response otherwise it gets partially transmitted.

Response.Flush();

Upvotes: 0

Related Questions