C# PDF打印
C#中使用iTextSharp生成并下载PDF很方便。
首先要将iTextSharp的dll下载并引入项目
主要分成两部分,一部分是PDF的Document生成,另一部分就是将Document输出到页面
这里分别列出aspx页和MVC中ActionResult的下载方式
①aspx
工具类(只是提供Document的输出)
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(); } } }
下载页面
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中
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(); } } }
②调用
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 //内容同上 } } }