Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write PDF stream to response stream

Tags:

asp.net

I am having problems when I tried to run the following code from my asp.net page. The code is from another post (http://stackoverflow.com/questions/5828315/write-pdf-stream-to-response-stream). When the Test.pdf file is located in my local drive, I am not able to open the file when the open button on the dialog box is clicked. When, the save button is clicked, the file tries in as myAspPageName.pdf in "C:\Downloads" the operation goes on for ever without actually saving anything.

I am sure what I am doing wrong. Thanks for any help. Is there a better way of doing the same thing?

protected void Page_Load(object sender, EventArgs e) 
{         
    Context.Response.Buffer = false;         
    FileStream inStr = null;         
    byte[] buffer = new byte[1024];         
    long byteCount; inStr = File.OpenRead(@"C:\Downloads\Test.pdf");         
    while ((byteCount = inStr.Read(buffer, 0, buffer.Length)) > 0) 
    {    
        if (Context.Response.IsClientConnected) 
        { 
            Context.Response.ContentType = "application/pdf";
            Context.Response.OutputStream.Write(buffer, 0, buffer.Length);
            Context.Response.Flush();             
        }        
    }     
} 
like image 618
KSM Avatar asked May 20 '26 20:05

KSM


2 Answers

You can use Response.WriteFile instead of all the buffer work.

protected void Page_Load(object sender, EventArgs e) 
{         
    Context.Response.WriteFile(@"C:\Downloads\Test.pdf"); 
}
like image 173
Oded Avatar answered May 24 '26 15:05

Oded


Consider using HttpResponse.TransmitFile (ASP.NET >= 2.0), especially for large files because it writes the file without buffering it into server memory.

Also, make sure you always set the Response.ContentType property to the appropriate MIME type or browsers will sometimes have trouble with downloading your files correctly, especially if you are writing the file from a handler:

Response.ContentType = "application/pdf";
like image 41
Saeb Amini Avatar answered May 24 '26 14:05

Saeb Amini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!