2012-03-02 45 views

回答

2

爲了生成PDF文件,您將需要一些第三方庫,因爲此功能不是內置在.NET框架中的。 iTextSharp是一個受歡迎的。

因此,例如,你可以寫一個自定義操作結果:

public class PdfResult : ActionResult 
{ 
    public override void ExecuteResult(ControllerContext context) 
    { 
     var response = context.HttpContext.Response; 
     response.ContentType = "application/pdf"; 
     var cd = new ContentDisposition 
     { 
      Inline = true, 
      FileName = "test.pdf", 
     }; 
     response.AddHeader("Content-Disposition", cd.ToString()); 

     using (var doc = new Document()) 
     using (var writer = PdfWriter.GetInstance(doc, response.OutputStream)) 
     { 
      doc.Open(); 
      doc.Add(new Phrase("Hello World")); 
     } 
    } 
} 

,然後讓你的控制器動作返回這個結果:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     return new PdfResult(); 
    } 
} 
[Asp.Net MVC的
+0

非常感謝Darin的支持。這段代碼太容易理解和實現。 – 2012-03-02 08:40:56

+0

嗨達林能否請你告訴我如何在PDF文件中顯示特定班級學生的信息,就像報告一樣。 – 2012-03-02 09:03:51

+0

@SonamMohite,這將取決於你想如何格式化數據。我建議你這次開始一個特定於iTextSharp的新問題,在這個問題中,您將呈現並解釋報告的外觀如何,您有哪些數據源作爲輸入,當然還有所需的輸出。 – 2012-03-02 11:06:43

相關問題