How can I return a pdf from a web request in ASP.NET? How can I return a pdf from a web request in ASP.NET? asp.net asp.net

How can I return a pdf from a web request in ASP.NET?


Assuming you can get a byte[] representing your PDF:

Response.Clear();Response.ContentType = "application/pdf";Response.AddHeader("Content-Disposition",    "attachment;filename=\"FileName.pdf\"");Response.BinaryWrite(yourPdfAsByteArray);Response.Flush();Response.End();


Look at how HTTP works. The client (=browser) doesn't rely on extensions, it only wants the server to return some metadata along with the document.

Metadata can be added with Response.AddHeader, and one 'metadata line' consists of Name and Value.

Content-Type is the property you are interested in, and the value is MIME type of the data (study: RFC1945 for HTTP headers, google for MIME type).

For ordinal aspx pages (html, ....) the property is 'text/html' (not so trivial, but for this example it is enough.). If you return JPG image, it can have name 'image.gif', but as long as you send 'image/jpeg' in Content-Type, it is processed as JPG image.Content-type for pdf is 'application/pdf'.

The browser will act according to default behaviour, for example, with Adobe plugin, it will display the PDF in it's window, if you don't have any plugin for PDF, it should download the file, etc..

Content-Disposition header says, what you should do with the data. If you want explicitly the client to 'download' some HTML/PDF/whatever, and not display it by default, value 'attachment' is what you want. It should have another parameter, (as suggested by Justin Niessner), which is used in case of something like:

http://server/download.aspx?file=11 -> Content-Disposition: attachment;filename=file.jpg says, how the file should be by default named.