Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write PDF stream to response stream

If I have a pdf file as a Stream, how can I write it to the response output stream?

like image 918
ryudice Avatar asked Apr 29 '11 05:04

ryudice


4 Answers

Since you are using MVC, the best way is to use FileStreamResult:

return new FileStreamResult(stream, "application/pdf")
{
    FileDownloadName = "file.pdf"
};

Playing with Response.Write or Response.OutputStream from your controller is non-idiomatic and there's no reason to write your own ActionResult when one already exists.

like image 175
Talljoe Avatar answered Nov 03 '22 17:11

Talljoe


One way to do it is as follows:

//assuming you have your FileStream handle already - named fs
byte[] buffer = new byte[4096];
long count = 0;

while ((count = fs.Read(buffer, 0, buffer.Length)) > 0)
{
    response.OutputStream.Write(buffer, 0, count);
    response.Flush();
}

You can also use GZIP compression to speed the transfer of the file to the client (less bytes streamed).

like image 27
ljkyser Avatar answered Nov 03 '22 16:11

ljkyser


In asp.net this is the way to download a pdf file

    Dim MyFileStream As FileStream
    Dim FileSize As Long

    MyFileStream = New FileStream(filePath, FileMode.Open)
    FileSize = MyFileStream.Length

    Dim Buffer(CInt(FileSize)) As Byte
    MyFileStream.Read(Buffer, 0, CInt(FileSize))
    MyFileStream.Close()

    Response.ContentType = "application/pdf"
    Response.OutputStream.Write(Buffer, 0, FileSize)
    Response.Flush()
    Response.Close()
like image 6
Abdul Saboor Avatar answered Nov 03 '22 17:11

Abdul Saboor


The HTTP Response is a stream exposed to you through the HttpContext.Response.OutputStream property, so if you have the PDF file in a stream you can simply copy the data from one stream to the other:

CopyStream(pdfStream, response.OutputStream);

For an implementation of CopyStream see Best way to copy between two Stream instances - C#

like image 4
Justin Avatar answered Nov 03 '22 15:11

Justin