Tuesday 23 August 2011

Asp.Net: Write Binary Stream to Response

Question:
How to send a Pdf binary stream as response of a web request?
How to return a generated pdf to the user in an asp.net app?


Answer:
Suppose you have generated your PDF as a binary stream.
You first set the HTTP ContentType of the Response object to "Application/pdf".
And then you use the BinaryWrite() method of the Response and end the response.

Here is an example
private void WriteResponse(byte[] result)
{
    if (result != null)
    {
        Response.ClearHeaders();
        // this will make the browser ask for download, instead of showing the pdf
        Response.AddHeader("content-disposition", "attachment; filename=" + pdfDownloadFilename);
        // specify content type
        Response.ContentType = "Application/pdf";
        Response.BinaryWrite(result);
        Response.End();
    }
}




No comments: