tags:

views:

2137

answers:

6

I have an app that needs to read a PDF file from the file system and then write it out to the user. The PDF is 183KB and seems to work perfectly. When I use the code at the bottom the browser gets a file 224KB and I get a message from Acrobat Reader saying the file is damaged and cannot be repaired.

Here is my code (I've also tried using File.ReadAllBytes(), but I get the same thing):

using (FileStream fs = File.OpenRead(path))
      {
       int length = (int)fs.Length;
       byte[] buffer;

       using (BinaryReader br = new BinaryReader(fs))
       {
        buffer = br.ReadBytes(length);
       }

       Response.Clear();
       Response.Buffer = true;
       Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", Path.GetFileName(path)));
       Response.ContentType = "application/" + Path.GetExtension(path).Substring(1);
       Response.BinaryWrite(buffer);
      }
A: 

Maybe you are missing a Response.close to close de Binary Stream

Igor Zelaya
A: 

In addition to Igor's Response.Close(), I would add a Response.Flush().

AJ
+3  A: 

Try adding

Response.End();

after the call to Response.BinaryWrite().

You may inadvertently be sending other content back after Response.BinaryWrite which may confuse the browser. Response.End will ensure that that the browser only gets what you really intend.

BarneyHDog
+1  A: 

We've used this with a lot of success. WriteFile do to the download for you and a Flush / End at the end to send it all to the client.

            //Use these headers to display a saves as / download
            //Response.ContentType = "application/octet-stream";
            //Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}.pdf", Path.GetFileName(Path)));

            Response.ContentType = "application/pdf";
            Response.AddHeader("Content-Disposition", String.Format("inline; filename={0}.pdf", Path.GetFileName(Path)));

            Response.WriteFile(path);
            Response.Flush();
            Response.End();
Robin Day
+2  A: 
        Response.BinaryWrite(bytes);
        Response.Flush();
        Response.Close();
        Response.End();

This works for us. We create PDFs from SQL Reporting Services.

jinsungy
+1  A: 

Since you're sending the file directly from your filesystem with no intermediate processing, why not use Response.TransmitFile instead?

Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition",
    "attachment; filename=\"" + Path.GetFileName(path) + "\"");
Response.TransmitFile(path);
Response.End();

(I suspect that your problem is caused by a missing Response.End, meaning that you're sending the rest of your page's content appended to the PDF data.)

LukeH