Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

c# - How to convert pdf Byte[] Array to downloadable file using iTextSharp

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");

 }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");

?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...