说三道四技术文摘-感悟人生的经典句子
说三道四 > 文档快照

C#使用iTextsharp生成PDF

HTML文档下载 WORD文档下载 PDF文档下载
本文介绍如何使用Asp.net MVC 将生成PDF页面。

 

如何使用Asp.net MVC 生成PDF页面?

 

首先下载PDF库itextsharp

http://sourceforge.net/projects/itextsharp/

 

 

 

然后将它添加到你的工程中(引用该库)

 

对于ASP.NET MVC模型,添加一个controller然后按下面的代码创建PDF格式数据。

using iTextSharp;using iTextSharp.text.pdf;using iTextSharp.text;using System.IO;public void createPDF(){int totalCharCount = 0;// PDF中使用的字体Font font8 = FontFactory.GetFont("ARIAL", 7, Font.BOLD);Font fonttbltxt = FontFactory.GetFont("ARIAL", 7);Font HeaderFont = FontFactory.GetFont("ARIAL", 12, Font.BOLD);MemoryStream MStream = new MemoryStream();Document document = new Document(PageSize.A4,10,10,10,20 );PdfWriter writer = PdfWriter.GetInstance(document, MStream);document.Open();//添加logoImage logo = Image.GetInstance(Server.MapPath("~/Content/Images/logo.png"));logo.ScaleToFit(70f, 40f);document.Add(logo);Paragraph pgrph = new Paragraph("REPORT", HeaderFont);pgrph.Alignment = Element.ALIGN_CENTER;document.Add(pgrph);PdfContentByte cb = writer.DirectContent;//表格PdfPTable tbl = new PdfPTable(4);PdfPCell pcellID = new PdfPCell(new Phrase(new Chunk("JobID", font8)));pcellID.Border = 0;tbl.AddCell(pcellID);PdfPCell pdfstatus = new PdfPCell(new Phrase(new Chunk("Status", font8)));pdfstatus.Border = 0;tbl.AddCell(pdfstatus);PdfPCell date = new PdfPCell(new Phrase(new Chunk("Date", font8)));date.Border = 0;tbl.AddCell(date);PdfPCell MRN = new PdfPCell(new Phrase(new Chunk("MRN", font8)));MRN.Border = 0;tbl.AddCell(MRN);tbl.TotalWidth = 500;List jobs = new List();jobs=jobRepository.GetAllJobs().ToList();fillCharAndCastData();// 将数据一个一个填入PDF表格中foreach (var item in jobs){pcellID = new PdfPCell();pcellID.Border = 0;pcellID.AddElement(new Paragraph(Convert.ToString(item.JobCode), fonttbltxt));tbl.AddCell(pcellID);pdfstatus = new PdfPCell();pdfstatus.Border = 0;pdfstatus.AddElement(new Paragraph(Convert.ToString(item.JobStatus), fonttbltxt));tbl.AddCell(pdfstatus);date = new PdfPCell();date.Border = 0;date.AddElement(new Paragraph(Convert.ToString(item.JobDate.ToShortDateString()), fonttbltxt));tbl.AddCell(date);MRN = new PdfPCell();MRN.Border = 0;MRN.AddElement(new Paragraph(Convert.ToString(item.MrnNo), fonttbltxt));tbl.AddCell(MRN);}tbl.WriteSelectedRows(0, 11, 50, 770, cb);document.Close();Response.AddHeader("Content-Disposition", "attachment:filename=myPDFNew.pdf");Response.ContentType = "application/pdf";Response.BinaryWrite(MStream.GetBuffer());Response.End();}

 

备案号:鲁ICP备13029499号-2 说三道四 www.s3d4.cn 说三道四技术文摘