Search code examples
asp.netitexteofnul

Itextsharp open new tab ISSUE


I need to open pdf in the new tab, it works and file show perfect, but if I open File with notepadd++, after EOF there are some NULL char (see pics)enter image description here. It happen only I open it in new tab and use memorystream, the string after EOF create some problem the parser of client, whats wrong?.

This is code:

 Dim mswithPage As New MemoryStream()
        Dim SessValue As String = Request.QueryString("s")
        Dim NOrder As String = Request.QueryString("odv")
        mswithPage = CType(Session(SessValue), MemoryStream)


        Response.Clear()
        Response.ContentType = "Application/pdf"
        Response.AddHeader("content-disposition", "inline;filename=" & NOrder & ".pdf")

        Response.OutputStream.Write(mswithPage.GetBuffer(), 0, mswithPage.GetBuffer().Length)
        Response.OutputStream.Flush()
        Response.OutputStream.Close()
        Response.End()

Solution

  • The issue

    An issue is in this line:

     Response.OutputStream.Write(mswithPage.GetBuffer(), 0, mswithPage.GetBuffer().Length)
    

    Even more precisely its final argument mswithPage.GetBuffer().Length - you should use the number of actually used bytes in the buffer but you use the size of the complete buffer.

    A solution

    Thus, use mswithPage.Length instead:

     Response.OutputStream.Write(mswithPage.GetBuffer(), 0, mswithPage.Length)
    

    ... and if the MemoryStream already is closed

    If the MemoryStream already is closed, the solution above doesn't work anymore because its Length property can only be used on open streams.

    What does work on closed streams, though, is the ToArray method! Thus, you can instead use

     Response.OutputStream.Write(mswithPage.ToArray())
    

    (Actually it is funny that ToArray works on closed streams but Length does not. After all, ToArray essentially returns a copy of the first Length many bytes of the internal buffer...)