如何使用iTextSharp将pdf Byte [] Array转换为可下载文件

时间:2010-09-02 04:21:02

标签: c# asp.net-mvc itextsharp

嘿伙计我有这个字节数组我想转换为pdf并让它可供下载。任何人都知道如何做到这一点?

这是我的动作控制器

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

 }

1 个答案:

答案 0 :(得分:27)

我使用类似的代码,但有一些不同之处:

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. 之前请致电Reponse.Clear()。
  2. 使用MemoryStream.WriteTo写入Response.OutputStream。
  3. 编辑:抱歉,我没有看到你使用的是ASP.NET MVC,上面的代码是在WebForms aspx页面中。

    对于ASP.NET MVC,你不能只做

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