2010-08-26 104 views
0

我一直在嘗試從我的應用程序生成簡單的PDF文件,以便稍後轉到使用動態數據生成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 
} 
+0

只是好奇,你使用的是什麼API生成PDF? – 2011-02-17 23:01:47

回答

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"); 
} 
+0

tblImage.AddCell(); pdf.Add(Image); 這兩行代碼給我的錯誤:S – ignaciofuentes 2010-08-26 20:29:08

+0

對不起,拿了一大堆,你只需要底部,我會更新來說清楚。 – 2010-08-26 20:37:16

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); 
+0

這給了我幾個錯誤..主要與ms.Write,它沒有采取Response.OutputStream作爲參數...即時通訊在mvc2,如果它有所作爲 – ignaciofuentes 2010-08-26 20:25:03