views:

47

answers:

2

I am generating pdf using itexsharp. I am creating MemoryStream, then when i am trying t write MemoryStream bytes in to response but no luck. When i am executing this code in my controller the pdf not coming in response. Memory stream is populaitng correctly i can see this in debugger, but for some reason this number of butes not coming in response.

Here is my code:

        HttpContext.Current.Response.ContentType = "application/pdf"; 
        ...
        using (Stream inputPdfStream = new FileStream(pdfFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
        using (Stream outputPdfStream = new MemoryStream())
        {
            PdfReader reader = new PdfReader(inputPdfStream);
            PdfStamper stamper = new PdfStamper(reader, outputPdfStream);
            ....

            //try one
            outputPdfStream.WriteTo(HttpContext.Current.Response.OutputStream); // NOT POPULATING Response
            //try two
            HttpContext.Current.Response.BinaryWrite(outputPdfStream.ToArray()); // NOT POPULATING Response Too

            HttpContext.Current.Response.End();
        }

May be some one have any ideas?

A: 

Probably the memorystream is still set at the position after the last written byte. It will write all bytes from the current position (which is none). If you do a outputPdfStream.Seek(0) it will set the position back to the first byte, and will write the contents of the whole stream to the response output.

Anyway, like Dean says, you should just use the Reponse.WriteFile method.

Jappie
+2  A: 

Could you not use

Response.ContentType = "application/pdf"
Response.AddHeader("Content-Type", "application/pdf")
Response.WriteFile(pdfFilePath)
Response.End()
Dean