We are using the code below to merge multiple PDF files (using iTextSharp) into one stream and then display that stream in a web page. It has been working great but now we want to output that memory stream to a single pdf file like it displays and we now get the error "Cannot access a closed Stream." on the line below
mem.WriteTo(file)
Public Shared Sub MergePDFs(ByVal files As List(Of String), ByVal filename As String)
Using mem As New MemoryStream()
Dim readers As New List(Of PdfReader)
Using doc As New Document
Dim copy As New PdfCopy(doc, mem)
copy.SetMergeFields()
doc.Open()
For Each strfile As String In files
Dim reader As New PdfReader(strfile)
copy.AddDocument(reader)
readers.Add(reader)
Next
End Using
For Each reader As PdfReader In readers
reader.Close()
Next
If filename = "finalbillfiles.pdf" Then
filename = "E:/" & filename
Dim file As New FileStream(filename, FileMode.Create, FileAccess.Write)
mem.WriteTo(file)
file.Close()
End If
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.ContentType = "application/pdf"
HttpContext.Current.Response.AppendHeader("Content-Disposition", "inline; filename=" + filename)
HttpContext.Current.Response.BinaryWrite(mem.ToArray)
HttpContext.Current.Response.OutputStream.Flush()
End Using
End Sub