提示下载生成的PDF文件

时间:2010-08-26 20:08:33

标签: asp.net-mvc pdf-generation itextsharp

我一直在尝试从我的应用程序生成简单的PDF,以便稍后我可以继续使用动态数据生成PDF。我的代码生成文件,但我想让浏览器提示下载文件。

我实际上甚至不希望将生成的文件存储在我的服务器上,但我不知道如何将其提供给用户而不先将其存储在服务器驱动器中。

public ActionResult GetPDF()
{
    Document document = new Document();
    PdfWriter.GetInstance(document, new FileStream(Server.MapPath("../Content/test.pdf"), FileMode.Create));
    document.Open();
    string strHTML = "<B>I Love ASP.Net!</B>";
    HTMLWorker htmlWorker = new HTMLWorker(document);
    htmlWorker.Parse(new StringReader(strHTML));
    document.Close();

    return File(document, "application/pdf", Server.HtmlEncode(filename));//this doesnt work, obviously
}

2 个答案:

答案 0 :(得分:2)

使用FileStreamResult操作

public FileStreamResult Export(int? ID)
{        
    MemoryStream stream = new MemoryStream();

    //Start of PDF work using iTextSharp PDF library
    Document pdf = new Document();
    PdfWriter writer = PdfWriter.GetInstance(pdf, stream);    
    pdf.Open();    
    pdf.Add(new Phrase("test"));    
    pdf.Close();
    //End of PDF work using iTextSharp PDF library

    //Where the download magic happens
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=Log.pdf");
    Response.Buffer = true;
    Response.Clear();
    Response.OutputStream.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length);
    Response.OutputStream.Flush();
    Response.End();

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

答案 1 :(得分:0)

你需要做点什么......

更改

PdfWriter.GetInstance(document, new FileStream(Server.MapPath("../Content/test.pdf"), FileMode.Create));

var memorystream ms = new memorystream;
PdfWriter.GetInstance(document, ms);

然后到最后......

Response.Clear;
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=PDFFile.pdf");

ms.Write(Response.OutputStream);