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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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).

Method 3

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

Method 4

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#

Method 5

Please try this one:

    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:UsersDownloadssample.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();
            }
        }
    }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x