levi
levi

Reputation: 3521

Download PDF without saving in ASP.net Handler

I've a handler in asp.net app. When there comes some kind of request I want user to get download window, where I put PDF stream. I don't want PDF to be saved in memory. I have the following code, but it fails to open, says pdf file was demaged and couldn't open it. tell me other way to achieve my goal if you think mine is not good.

 MemoryStream stream = new MemoryStream();
                CreatePFD(T.Text, stream);

                context.Response.Write(stream);


                context.Response.ContentType = "application/pdf";
                context.Response.AddHeader("content-disposition", "attachment; filename=" + "Nots__Saved__FIle__fileName.pdf");

Now I have this code:

Document Doc = new Document(PageSize.A4, 80, 50, 30, 65); System.IO.Stream outputStream = new System.IO.FileStream(@"C:\inetpub\wwwroot\c\wefwe.pdf", System.IO.FileMode.OpenOrCreate);

            PdfWriter.GetInstance(Doc, outputStream);

            Doc.Open();

            List<IElement> htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StringReader(T.Text), null);
            for (int k = 0; k < htmlarraylist.Count; k++)
            {
                Doc.Add((IElement)htmlarraylist[k]);
            }

            outputStream.CopyTo(context.Response.OutputStream);
            Doc.Close();

            context.Response.ContentType = "application/pdf";
            context.Response.AddHeader("content-disposition", "attachment; filename=" + "Nots__Saved__FIle__fileName.pdf");

when i save pdf, the file is correct... but when I get response the file is in correct. demaged...

Upvotes: 1

Views: 3058

Answers (1)

SLaks
SLaks

Reputation: 888067

You need to rewind the stream by setting stream.Position = 0.

Also, Response.Write(stream) will just print stream.ToString().

Instead, you should call stream.CopyTo(Response.OutputStream).

Upvotes: 3

Related Questions