简体   繁体   中英

PDF won't display in browser window

I am using a handler to get and display a PDF in the browser window using the code below:

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

The function WriteDocumentFilePDF successfully writes the PDF to the temp directory. I have the above code working correctly in a different application. Am I missing something?

When debugging issues like this, I find that Fiddler is an invaluable tool; many many times it has saved me from simple mistakes. Also, this site http://www.c-sharpcorner.com/uploadfile/prathore/what-is-an-ashx-file-handler-or-web-handler/ gives an example of doing the same thing but with a GIF image. The difference between your example and his seems to be the use of Response.WriteFile() rather than the direct write to the Response using BinaryWrite().

I would perform a Response.ClearHeaders() before I set the content-type and I would remove the call to Response.End().

Does it make a difference if you pass the byte[] to memorystream first? So something like

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

And then add your headers

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM