C#中使用iTextSharp生成並下載PDF很方便。windows
首先要將iTextSharp的dll下載並引入項目app
主要分紅兩部分,一部分是PDF的Document生成,另外一部分就是將Document輸出到頁面ide
這裏分別列出aspx頁和MVC中ActionResult的下載方式工具
①aspxui
工具類(只是提供Document的輸出)this
using System.Web; using iTextSharp.text; using System.IO; using iTextSharp.text.pdf; namespace Common { public class PdfHelper { public event DocRenderHandler DocRenderEvent; public delegate void DocRenderHandler(ref Document Doc); public void DownLoadPDF(string FileName, HttpContext context) { Document Doc = new Document(); HttpResponse Response = context.Response; using (MemoryStream Memory = new MemoryStream()) { PdfWriter PdfWriter = PdfWriter.GetInstance(Doc, Memory); if (DocRenderEvent != null) DocRenderEvent(ref Doc); #region 文件輸出及相關設置 Response.Clear(); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName); Response.ContentType = "application/pdf"; Response.OutputStream.Write(Memory.GetBuffer(), 0, Memory.GetBuffer().Length); Response.OutputStream.Flush(); Response.OutputStream.Close(); Response.Flush(); #endregion } Response.End(); } } }
下載頁面spa
using System; using iTextSharp.text; using iTextSharp.text.pdf; using System.Text; namespace MvcMovie.Common { public partial class PdfLoad : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string FileName = DateTime.Now.ToShortTimeString() + ".pdf"; PdfHelper ph = new PdfHelper(); ph.DocRenderEvent += RenderPdfDoc; ph.DownLoadPDF(FileName, this.Context); } private void RenderPdfDoc(ref Document Doc) { Doc.SetPageSize(PageSize.A4); Doc.SetMargins(60, 60, 20, 40); #region 相關元素準備 BaseFont bfChinese = BaseFont.CreateFont(@"C:\windows\fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); Font Font16 = new Font(bfChinese, 16); Font Font14 = new Font(bfChinese, 14); Font Font12 = new Font(bfChinese, 12); Font Font12Bold = new Font(bfChinese, 12, Font.BOLD); Font Font12Italic = new Font(bfChinese, 12, Font.BOLDITALIC); Font Font10Bold = new Font(bfChinese, 10, Font.BOLD); Paragraph parag; Chunk chunk; PdfPTable table; #endregion #region 文件標題 Doc.Open(); Doc.AddAuthor("TiestoRay"); Doc.AddTitle("相關部分發布的重要通知"); #endregion #region 正文 parag = new Paragraph("------通知------", Font16); parag.Alignment = Element.ALIGN_CENTER; Doc.Add(parag); parag = new Paragraph(); parag.SetLeading(20f, 1f); parag.Add(new Chunk("曾經滄海難爲水,心有靈犀一點通", Font12Italic)); Doc.Add(parag); parag = new Paragraph(); parag.Add(new Chunk("取次花叢懶回顧,得來全不費工夫", Font10Bold)); Doc.Add(parag); parag = new Paragraph(); parag.Add(new Chunk(" " + DateTime.Now.ToLongDateString(), Font12)); Doc.Add(parag); parag = new Paragraph(); parag.SetLeading(1f, 1f); chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).Append("Come On!").ToString(), Font12); chunk.SetUnderline(-18f, 1.4f); parag.Add(chunk); parag.Alignment = Element.ALIGN_JUSTIFIED_ALL; Doc.Add(parag); Doc.NewPage();//換頁 table = new PdfPTable(new float[] { 5, 3, 3 }); table.WidthPercentage = 100f; table.AddCell(new Phrase("英語老師簽字:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", Font12)); table.AddCell(new Phrase("同桌簽字:", Font12)); table.AddCell(new Phrase("本人簽字:", Font12)); Doc.Add(table); parag = new Paragraph(); parag.SetLeading(-30f, 1.4f); parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 60).ToString() + "簽字日期:", Font12)); Doc.Add(parag); Doc.Close(); #endregion } } }
②MVC3(以上)版本
寫一個繼承自ActionResult的Result類,而且將Document輸出寫到ExecuteResult中code
using System.Web; using System.Web.Mvc; using iTextSharp.text; using System.IO; using iTextSharp.text.pdf; namespace Common { public class PdfResult:ActionResult { private string FileName; public event DocRenderHandler DocRenderEvent; public delegate void DocRenderHandler(ref Document Doc); public PdfResult(string FileName) { this.FileName = FileName; } /// <summary> /// 向頁面輸出時纔會執行該方法 /// </summary> public override void ExecuteResult(ControllerContext context) { Document Doc = new Document(); using (MemoryStream Memory = new MemoryStream()) { PdfWriter PdfWriter = PdfWriter.GetInstance(Doc, Memory); if (DocRenderEvent != null) DocRenderEvent(ref Doc); #region 文件輸出及相關設置 HttpResponseBase Response = context.HttpContext.Response; Response.Clear(); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName); Response.ContentType = "application/pdf"; Response.OutputStream.Write(Memory.GetBuffer(), 0, Memory.GetBuffer().Length); Response.OutputStream.Flush(); Response.OutputStream.Close(); Response.Flush(); #endregion } context.HttpContext.Response.End(); } } }
②調用blog
using System; using System.Web.Mvc; using MvcMovie.Common; using iTextSharp.text; using iTextSharp.text.pdf; using System.Text; namespace MvcMovie.Controllers { public class HomeController : Controller { public ActionResult Index(string name,int? id) { ViewBag.Message = "歡迎使用 ASP.NET MVC!"; return View(); } public ViewResult About() { return View("About"); } public ActionResult DownLoadPdf(int ID) { string FileName = DateTime.Now.ToShortTimeString()+".pdf"; PdfResult pr = new PdfResult(FileName); pr.DocRenderEvent += RenderPdfDoc; return pr; } private void RenderPdfDoc(ref Document Doc) { //TO DO //內容同上 } } }