C#生成动态pdf文件的实现示例
一、使用场景我们不难发现在实际生活中PDF文件的使用无处不在。比如说考试结束查分渠道公布了下载的成绩单开具了发票了下载的发票文件考试前登录报考系统下载的准考证党政机关撰写的公文等等诸如此类的文件都是用PDF文件形式保存的。PDF文件保存不会丢失源格式不易于直接篡改信息等优点在日常中的使用非常普遍。今天让我们在这里使用.NET平台下的iTextSharp程序包动态生成写入一个PDF文件回传到前端提供下载 。二、操作流程1.安装iTextSharpNuGet程序包右击项目选项点击管理NuGet程序包搜索iTextSharp选择合适的版本安装上2.后端C#代码的编写引入iTextSharp库使用.ashx一般处理程序响应前端的请求在指定的物理路径中生成成绩单pdf文件并写入信息123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.Script.Serialization;usingiTextSharp;usingiTextSharp.text;usingiTextSharp.text.pdf;usingSystem.IO;namespaceMySolution1{/// summary/// 建立前端适配的映射类/// /summaryclassReqParams{publicstringtype {get;set; }publicintpayload {get;set; }}/// summary/// Handler1 的摘要说明/// /summarypublicclassHandler1 : IHttpHandler{publicvoidProcessRequest(HttpContext context){//创建序列化工具JavaScriptSerializer serializer newJavaScriptSerializer();//获取前端提交的JSON字符串stringjsonString context.Request.Form[param].ToString();//反序列化映射JSON字符串ReqParams req serializer.DeserializeReqParams(jsonString);//需要返回前端的状态objectstate null;switch(req.type){caseinit:state new{time DateTime.Now.ToLongTimeString(),resultreq.payload1,};break;caseuploadFile://有文件上传负载到Request中才下一步操作if(context.Request.Files.Count 0){HttpPostedFile file context.Request.Files[file];//制定文件保存路径stringsavePath context.Server.MapPath(~/Content/images/) file.FileName;try{//保存文件记录状态信息file.SaveAs(savePath);state new{time DateTime.Now.ToLongTimeString(),result 上传成功,payload req.payload 1,url /Content/images/ file.FileName,};}catch(Exception e){//保存失败抛出错误信息state new{time DateTime.Now.ToLongTimeString(),result 上传失败 e.Message.ToString(),payload-1};}}break;casegetScorePDF:state CreatePDF(context);break;}context.Response.Write(serializer.Serialize(state));}objectCreatePDF(HttpContext context){Random ran newRandom(60);//指定pdf文件目录stringpath context.Server.MapPath(~/Content/) scorePDF.pdf;//创建pdf文档、pdf写入器Document pdf newDocument(PageSize.A4, 10, 10, 40, 30);PdfWriter writer PdfWriter.GetInstance(pdf,newFileStream(path, FileMode.Create));// 指定中文字体如微软雅黑stringfontPath C:\Windows\Fonts\msyh.ttc,0;// 微软雅黑BaseFont baseFont BaseFont.CreateFont(fontPath,BaseFont.IDENTITY_H, BaseFont.EMBEDDED);Font chineseFont newFont(baseFont, 8);pdf.Open();//建立表格对象PdfPTable table newPdfPTable(3 3 3);//添加表格的单元格数据table.AddCell(newPdfPCell(newPhrase(姓名, chineseFont)));table.AddCell(newPdfPCell(newPhrase(班级, chineseFont)));table.AddCell(newPdfPCell(newPhrase(准考证, chineseFont)));table.AddCell(newPdfPCell(newPhrase(语文, chineseFont)));table.AddCell(newPdfPCell(newPhrase(数学, chineseFont)));table.AddCell(newPdfPCell(newPhrase(英语, chineseFont)));table.AddCell(newPdfPCell(newPhrase(体育, chineseFont)));table.AddCell(newPdfPCell(newPhrase(美术, chineseFont)));table.AddCell(newPdfPCell(newPhrase(劳动, chineseFont)));//也可以添加表格的行PdfPRow row newPdfPRow(newPdfPCell[]{newPdfPCell(newPhrase(李明,chineseFont)),newPdfPCell(newPhrase(一年级二班,chineseFont)),newPdfPCell(newPhrase(0500090901,chineseFont)),newPdfPCell(newPhrase(ran.Next(60,100).ToString(),chineseFont)),newPdfPCell(newPhrase(ran.Next(60,100).ToString(),chineseFont)),newPdfPCell(newPhrase(ran.Next(60,100).ToString(),chineseFont)),newPdfPCell(newPhrase(ran.Next(60,100).ToString(),chineseFont)),newPdfPCell(newPhrase(ran.Next(60,100).ToString(),chineseFont)),newPdfPCell(newPhrase(ran.Next(60,100).ToString(),chineseFont)),});table.Rows.Add(row);//把表格放入pdf文档pdf.Add(table);pdf.Close();returnnew{time DateTime.Now.ToLongTimeString(),result 操作成功,url /Content/scorePDF.pdf,success true};}publicboolIsReusable{get{returnfalse;}}}}3.前端接口的调用以下载成绩单为例点击下载成绩单按钮即可查看并下载成绩单pdf文件123456789101112131415161718192021222324252627282930313233343536373839404142434445% Page LanguageC#AutoEventWireuptrueCodeBehindWebForm3.aspx.csInheritsMySolution1.WebForm3%!DOCTYPE htmlhtml xmlnshttp://www.w3.org/1999/xhtmlhead runatservermeta http-equivContent-Typecontenttext/html; charsetutf-8/title使用C#生成pdf/titlescript srcScripts/jquery-1.10.2.min.js/script/headbodydivbutton onclickdownloadPDF()下载成绩单/button/div/body/htmlscript typetext/javascriptfunction downloadPDF() {constparam {type:getScorePDF,payload:0}constformDatanewFormData()formData.append(param, JSON.stringify(param))$.ajax({url:/Handler1.ashx,type:post,data:formData,processData:false,contentType:false,success:res{constdata JSON.parse(res)if(data.success) {if(confirm(成绩单已经生成是否打开文件)){window.location.href data.url}}else{alert(下载失败)}}})}/script运行可查看结果点击确定后出现了写入的成绩单pdf文件三、注意事项1.iTextSharp需要和.NET框架兼容才能正常安装使用。安装前可鼠标右击项目选项卡查看项目框架版本2.文件流操作非常容易出现异常例如打开pdf文件写入单元格、行的时候需要适当地异常处理1234567891011121314151617181920212223242526272829303132333435363738394041424344454647try{pdf.Open();//建立表格对象PdfPTable table newPdfPTable(3 3 3);//添加表格的单元格数据table.AddCell(newPdfPCell(newPhrase(姓名, chineseFont)));table.AddCell(newPdfPCell(newPhrase(班级, chineseFont)));table.AddCell(newPdfPCell(newPhrase(准考证, chineseFont)));table.AddCell(newPdfPCell(newPhrase(语文, chineseFont)));table.AddCell(newPdfPCell(newPhrase(数学, chineseFont)));table.AddCell(newPdfPCell(newPhrase(英语, chineseFont)));table.AddCell(newPdfPCell(newPhrase(体育, chineseFont)));table.AddCell(newPdfPCell(newPhrase(美术, chineseFont)));table.AddCell(newPdfPCell(newPhrase(劳动, chineseFont)));//也可以添加表格的行PdfPRow row newPdfPRow(newPdfPCell[]{newPdfPCell(newPhrase(李明,chineseFont)),newPdfPCell(newPhrase(一年级二班,chineseFont)),newPdfPCell(newPhrase(0500090901,chineseFont)),newPdfPCell(newPhrase(ran.Next(60,100).ToString(),chineseFont)),newPdfPCell(newPhrase(ran.Next(60,100).ToString(),chineseFont)),newPdfPCell(newPhrase(ran.Next(60,100).ToString(),chineseFont)),newPdfPCell(newPhrase(ran.Next(60,100).ToString(),chineseFont)),newPdfPCell(newPhrase(ran.Next(60,100).ToString(),chineseFont)),newPdfPCell(newPhrase(ran.Next(60,100).ToString(),chineseFont)),});table.Rows.Add(row);//把表格放入pdf文档pdf.Add(table);returnnew{time DateTime.Now.ToLongTimeString(),result 操作成功,url /Content/scorePDF.pdf,success true};}catch(Exception e){thrownewException(e.Message.ToString());}finally{pdf.Close();}复制讲解3.若需中文字体需要在pdf文件写入呈现必须制定中文字体若没有创建支持中文的字体传入创建单元格的参数中则中文写入后无法显示12345// 指定中文字体如微软雅黑stringfontPath C:\Windows\Fonts\msyh.ttc,0;// 微软雅黑BaseFont baseFont BaseFont.CreateFont(fontPath,BaseFont.IDENTITY_H, BaseFont.EMBEDDED);Font chineseFont newFont(baseFont, 8);到此这篇关于C#生成动态pdf文件的实现示例的文章就介绍到这了