views:

217

answers:

1

Hei guys I have this byte array i want to convert to pdf and make it available for download. Anybody has any idea how this is done?

here is my Action Controller

public ActionResult DownloadLabTestResult(string labTestResultID)
{
            PdfReader pdfReader = new PdfReader("Xue_Tang.pdf");

            MemoryStream stream = new MemoryStream();
            PdfStamper stamper = new PdfStamper(pdfReader, stream);

            pdfReader.Close();
            stamper.Close();
            stream.Flush();
            stream.Close();
            byte[] pdfByte = stream.ToArray();

            // So i got the byte array of the original pdf at this point. Now how do i convert this
            // byte array to a downloadable pdf? i tried the method below but to no avail.

            MemoryStream ms = new MemoryStream(pdfByte);

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=labtest.pdf");
            Response.Buffer = true;
            Response.Clear();
            Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
            Response.OutputStream.Flush();
            Response.End();

            return new FileStreamResult(Response.OutputStream, "application/pdf");

 }
A: 

I am using similar code with a few differences:

Response.Clear();
MemoryStream ms = new MemoryStream(pdfByte);
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=labtest.pdf");
Response.Buffer = true;
ms.WriteTo(Response.OutputStream);
Response.End();
  1. Call Reponse.Clear() earlier.
  2. Use MemoryStream.WriteTo to write to Response.OutputStream.

Edit: sorry, I didn't see that you are using ASP.NET MVC, the above code is in a WebForms aspx page.

For ASP.NET MVC, couldn't you just do

return new FileStreamResult(ms, "application/pdf");

?

Andreas Paulsson
actually yeah you can do this. i over-complicated things haha. One other question though, is it even possible to convert a byte array (not knowing whether its pdf or doc or txt) into the right format, without specifying whether its pdf txt or doc? im stuck with this now.
Ari