iTextSharp动态生成多页pdf及追加内容等记录
- 1.要动态生成pdf,无非是用第三方或直接代码生成。
- 2.iTextSharp生成pdf问题点记录
- dll相关下载
- https://files.cnblogs.com/files/xlgwr/iTextSharAndcode128i.zip
1.初始化代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | string appDomainPath = AppDomain.CurrentDomain.BaseDirectory + @"\" ; if (isWebApp) { appDomainPath = System.Web.HttpRuntime.AppDomainAppPath + @"bin\" ; } string SavePath = string .Format( @"{0}pdfTemplate\{1}{2}.{3}" , appDomainPath, saveFileName, DateTime.Now.ToString( "yyyyMMddHHmmssfff" ), "pdf" ); string ImageLogoPath = string .Format( @"{0}pdfTemplate\{1}.{2}" , appDomainPath, "logo" , "jpg" ); string ImageLogoERcodePath = string .Format( @"{0}pdfTemplate\{1}.{2}" , appDomainPath, "logoErcode" , "png" ); using (Document document = new Document()) { //中文字体 string chinese = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "simhei.ttf" ); BaseFont baseFont = BaseFont.CreateFont(chinese, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); //文字大小12,文字样式 Font cn = new Font(baseFont, 12, Font.NORMAL); Font fontToLabel = new Font(baseFont, 10, Font.NORMAL, BaseColor.BLACK); Font fontToValue = new Font(baseFont, 12, Font.BOLD, BaseColor.BLACK); Font fontToValue8 = new Font(baseFont, 10, Font.BOLD, BaseColor.BLACK); Font fontLIGHT_GRAY = new Font(baseFont, 10, Font.NORMAL, BaseColor.LIGHT_GRAY); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(@SavePath, FileMode.Create)); document.Open(); PdfContentByte ConByte_Up = writer.DirectContent; //当前页 #region header title //最后一个参数是颜色,这里可以是rgb格式,也可以是默认定义的 Phrase Phr_HeaderTitle = new Phrase( "x x 书" , new Font(baseFont, 22, Font.BOLD, BaseColor.BLACK)); ColumnText.ShowTextAligned(ConByte_Up, Element.ALIGN_CENTER, Phr_HeaderTitle, 300, 786, 0); //add logo Image imgLogo = Image.GetInstance(ImageLogoPath); AddImageToDoc(writer, imgLogo, 3, 744 + imgLogo.Height); Image imgLogoERcode = Image.GetInstance(ImageLogoERcodePath); AddImageToDoc(writer, imgLogoERcode, 510, 720 + imgLogo.Height, 0.4f); #endregion #region header 头部内容 AddNewLable(dicTitle, "致:" , "QHContactPerson" , ConByte_Up, fontToLabel, fontToValue, 3, 720); AddNewLable(dicTitle, "我司" , "JJCompanyNa" , ConByte_Up, fontToLabel, fontToValue, 3, 690); AddNewLable(dicTitle, "委派" , "kyename" , ConByte_Up, fontToLabel, fontToValue, 180, 690); AddNewLable(dicTitle, "于" , "GoodsTime" , ConByte_Up, fontToLabel, fontToValue, 160 * 2, 690, 20); AddNewLable(dicTitle, "至贵处取货,请予以配合。" , "" , ConByte_Up, fontToLabel, fontToValue, 150 * 3, 690); #endregion float Tleft = 18f; float TcurrLableYSum = 792 - 72 * 2; float TcurrLabelWidth = 60f; float TcurrWidthAdd = 200f; float TcurrHeigthAdd = 25f; #region header 头部详细内容 792 #region 加背影 ConByte_Up.SetColorFill(BaseColor.LIGHT_GRAY); ConByte_Up.Rectangle(6, TcurrLableYSum - TcurrHeigthAdd * 4 + 15, 580, TcurrHeigthAdd * 4.3); ConByte_Up.Fill(); ConByte_Up.Stroke(); ConByte_Up.SetColorStroke(BaseColor.GRAY); ConByte_Up.MoveTo(TcurrWidthAdd + Tleft - 8, TcurrLableYSum + 20); ConByte_Up.SetLineDash(3f, 3f); ConByte_Up.LineTo(TcurrWidthAdd + Tleft - 8, TcurrLableYSum - TcurrHeigthAdd * 2 - 30); ConByte_Up.Stroke(); ConByte_Up.SetColorStroke(BaseColor.GRAY); ConByte_Up.MoveTo(TcurrWidthAdd * 2 + Tleft - 8, TcurrLableYSum + 20); ConByte_Up.SetLineDash(3f, 3f); ConByte_Up.LineTo(TcurrWidthAdd * 2 + Tleft - 8, TcurrLableYSum - TcurrHeigthAdd * 2 - 30); ConByte_Up.Stroke(); #endregion //第一行 AddNewLable(dicTitle, "取货联系人" , "QHContactPerson" , ConByte_Up, fontToLabel, fontToValue, Tleft, TcurrLableYSum, Element.ALIGN_LEFT, TcurrLabelWidth); AddNewLable(dicTitle, "寄件公司" , "JJCompanyNa" , ConByte_Up, fontToLabel, fontToValue, TcurrWidthAdd + Tleft, TcurrLableYSum, Element.ALIGN_LEFT, TcurrLabelWidth); AddNewLable(dicTitle, "取货司机" , "QHMan" , ConByte_Up, fontToLabel, fontToValue, (TcurrWidthAdd * 2) + Tleft, TcurrLableYSum, Element.ALIGN_LEFT, TcurrLabelWidth); //第二行 AddNewLable(dicTitle, "联系方式" , "QHContactWay" , ConByte_Up, fontToLabel, fontToValue, Tleft, TcurrLableYSum - TcurrHeigthAdd, Element.ALIGN_LEFT, TcurrLabelWidth); AddNewLable(dicTitle, "寄件人" , "JJContactPerson" , ConByte_Up, fontToLabel, fontToValue, TcurrWidthAdd + Tleft, TcurrLableYSum - TcurrHeigthAdd, Element.ALIGN_LEFT, TcurrLabelWidth); AddNewLable(dicTitle, "取货车牌号" , "QHCar" , ConByte_Up, fontToLabel, fontToValue, (TcurrWidthAdd * 2) + Tleft, TcurrLableYSum - TcurrHeigthAdd, Element.ALIGN_LEFT, TcurrLabelWidth); //第三行 AddNewLable(dicTitle, "取货地址" , "QHAddress" , ConByte_Up, fontToLabel, fontToValue8, Tleft, TcurrLableYSum - TcurrHeigthAdd * 2, Element.ALIGN_LEFT, TcurrLabelWidth, true , 200, 15); AddNewLable(dicTitle, "联系方式" , "JJContactWay" , ConByte_Up, fontToLabel, fontToValue, TcurrWidthAdd + Tleft, TcurrLableYSum - TcurrHeigthAdd * 2, Element.ALIGN_LEFT, TcurrLabelWidth); AddNewLable(dicTitle, "司机联系方式" , "QHManContactWay" , ConByte_Up, fontToLabel, fontToValue, (TcurrWidthAdd * 2) + Tleft, TcurrLableYSum - TcurrHeigthAdd * 2, Element.ALIGN_LEFT, TcurrLabelWidth); //备注 AddNewLable(dicTitle, "备注:" , "JJRemark" , ConByte_Up, fontToLabel, fontToValue, Tleft, TcurrLableYSum - TcurrHeigthAdd * 4, Element.ALIGN_LEFT, TcurrLabelWidth, true , 550, 15); //签字 AddNewLable(dicTitle, "签字:" , "Siger" , ConByte_Up, fontToLabel, fontToValue, (TcurrWidthAdd) + Tleft * 3, TcurrLableYSum - TcurrHeigthAdd * 8, 30); AddNewLable(dicTitle, "日期:" , "SigerDate" , ConByte_Up, fontToLabel, fontToValue, (TcurrWidthAdd * 2), TcurrLableYSum - TcurrHeigthAdd * 8, 30); #endregion var getPageOne = dicList.Take(2); #region 明细第一页,最多两个 AddListDetails(dicTitle, fontToLabel, fontToValue, fontToValue8, fontLIGHT_GRAY, writer, ConByte_Up, TcurrLableYSum - TcurrHeigthAdd * 10, TcurrHeigthAdd, getPageOne); //页数 string pageSize = string .Format( "页码:{0}/{1}" , 1, 1); #endregion #region 明细第n页,每页最多4个 var getPageGetMoreTow = dicList.Skip(2); var currNextList = getPageGetMoreTow.Take(4); var AllPageSize = Math.Ceiling(getPageGetMoreTow.Count() / 4F); if (AllPageSize > 0) { AllPageSize++; pageSize = string .Format( "页码:{0}/{1}" , 1, AllPageSize); } AddNewLable(dicTitle, pageSize, "" , ConByte_Up, fontToLabel, fontToValue, 300, 10, Element.ALIGN_CENTER); int runNM = 0; while (currNextList.Count() > 0) { //新页面 document.NewPage(); AddListDetails(dicTitle, fontToLabel, fontToValue, fontToValue8, fontLIGHT_GRAY, writer, ConByte_Up, 800, TcurrHeigthAdd, currNextList, true ); //下次 runNM++; currNextList = getPageGetMoreTow.Skip(4 * runNM).Take(4); //页数 pageSize = string .Format( "页码:{0}/{1}" , runNM + 1, AllPageSize); AddNewLable(dicTitle, pageSize, "" , ConByte_Up, fontToLabel, fontToValue, 300, 10, Element.ALIGN_CENTER); } #endregion ////新页面 //document.NewPage(); //AddImageToDoc(writer, imgLogo, 3, 744 + imgLogo.Height); //AddImageToDoc(writer, imgLogoERcode, 510, 720 + imgLogo.Height, 0.4f); } |
2.小方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | private int AddListDetails(Dictionary< string , string > dicTitle, Font fontToLabel, Font fontToValue, Font fontToValue8, Font fontLIGHT_GRAY, PdfWriter writer, PdfContentByte ConByte_Up, float TcurrBaseY, float TcurrHeigthAdd, IEnumerable<Dictionary< string , string >> getPageOne, bool hasPage = false ) { int beseRun = 0; foreach ( var item in getPageOne) { if (!hasPage) { AddNewLable(dicTitle, "--------------------------------------------------由此撕开--------------------------------------------------" , "" , ConByte_Up, fontLIGHT_GRAY, fontToValue, 300, TcurrBaseY - TcurrHeigthAdd * (beseRun * 8) + TcurrHeigthAdd, Element.ALIGN_CENTER); } if (item.ContainsKey( "YDCode" )) { var YDCode = item[ "YDCode" ]; //插入图片128 var ydcode1Image = GetImageCode128(YDCode); var ydcode1ImageToPost = GetImageToPoint(ydcode1Image, 0.45f, 0, TcurrBaseY - TcurrHeigthAdd * (beseRun * 8) - TcurrHeigthAdd * 3.5f); writer.DirectContent.AddImage(ydcode1ImageToPost); } AddNewLable(item, "" , "YDCode" , ConByte_Up, fontToLabel, fontToValue, 20, TcurrBaseY - TcurrHeigthAdd * (beseRun * 8) - TcurrHeigthAdd * 4); AddNewLable(item, "收件公司:" , "SJCompanyNa" , ConByte_Up, fontToLabel, fontToValue, 180, TcurrBaseY - TcurrHeigthAdd * (beseRun * 8), Element.ALIGN_LEFT, 45); AddNewLable(item, "收件地址" , "SJAddress" , ConByte_Up, fontToLabel, fontToValue8, 380, TcurrBaseY - TcurrHeigthAdd * (beseRun * 8), Element.ALIGN_LEFT, 45, true , 550, 18); if (item.ContainsKey( "DeliveryDetail" )) { var getdeliveryDetails = item[ "DeliveryDetail" ].JsonTo<List<GoodsInfo>>(); if (getdeliveryDetails != null && getdeliveryDetails.Count > 0) { ConByte_Up.SetColorFill(BaseColor.LIGHT_GRAY); ConByte_Up.Rectangle(180 - 2, TcurrBaseY - TcurrHeigthAdd * (2 + beseRun * 8) - 3, 380, 15); ConByte_Up.Fill(); ConByte_Up.Stroke(); //货物详情明细: AddNewLable(item, "型号" , "" , ConByte_Up, fontToLabel, fontToValue, 180, TcurrBaseY - TcurrHeigthAdd * (2 + beseRun * 8), Element.ALIGN_LEFT, 45, true , 550, 15); AddNewLable(item, "名称" , "" , ConByte_Up, fontToLabel, fontToValue, 180 + 80 * 1, TcurrBaseY - TcurrHeigthAdd * (2 + beseRun * 8), Element.ALIGN_LEFT, 45, true , 550, 15); AddNewLable(item, "件数" , "" , ConByte_Up, fontToLabel, fontToValue, 180 + 80 * 2, TcurrBaseY - TcurrHeigthAdd * (2 + beseRun * 8), Element.ALIGN_LEFT, 45, true , 550, 15); AddNewLable(item, "其它内容1" , "" , ConByte_Up, fontToLabel, fontToValue, 180 + 80 * 3, TcurrBaseY - TcurrHeigthAdd * (2 + beseRun * 8), Element.ALIGN_LEFT, 45, true , 550, 15); AddNewLable(item, "其它内容2" , "" , ConByte_Up, fontToLabel, fontToValue, 180 + 80 * 4, TcurrBaseY - TcurrHeigthAdd * (2 + beseRun * 8), Element.ALIGN_LEFT, 45, true , 550, 15); int currRun2 = 0; foreach ( var item2 in getdeliveryDetails) { AddNewLable(item, item2.Model, "" , ConByte_Up, fontToValue8, fontToLabel, 180, TcurrBaseY - TcurrHeigthAdd * (3 + beseRun * 8) - currRun2 * TcurrHeigthAdd, Element.ALIGN_LEFT, 45, true , 550, 15); AddNewLable(item, item2.Name, "" , ConByte_Up, fontToValue8, fontToLabel, 180 + 80 * 1, TcurrBaseY - TcurrHeigthAdd * (3 + beseRun * 8) - currRun2 * TcurrHeigthAdd, Element.ALIGN_LEFT, 45, true , 550, 15); AddNewLable(item, item2.Quantity, "" , ConByte_Up, fontToValue8, fontToLabel, 180 + 80 * 2, TcurrBaseY - TcurrHeigthAdd * (3 + beseRun * 8) - currRun2 * TcurrHeigthAdd, Element.ALIGN_LEFT, 45, true , 550, 15); AddNewLable(item, item2.Other1, "" , ConByte_Up, fontToValue8, fontToLabel, 180 + 80 * 3, TcurrBaseY - TcurrHeigthAdd * (3 + beseRun * 8) - currRun2 * TcurrHeigthAdd, Element.ALIGN_LEFT, 45, true , 550, 15); AddNewLable(item, item2.Other2, "" , ConByte_Up, fontToValue8, fontToLabel, 180 + 80 * 4, TcurrBaseY - TcurrHeigthAdd * (3 + beseRun * 8) - currRun2 * TcurrHeigthAdd, Element.ALIGN_LEFT, 45, true , 550, 15); currRun2++; } } else { //货物详情: AddNewLable(item, "货物详情:" , "DeliveryDetail" , ConByte_Up, fontToLabel, fontToValue, 180, TcurrBaseY - TcurrHeigthAdd * (2 + beseRun * 8), Element.ALIGN_LEFT, 45, true , 550, 15); } } else { //货物详情: AddNewLable(item, "货物详情:" , "DeliveryDetail" , ConByte_Up, fontToLabel, fontToValue, 180, TcurrBaseY - TcurrHeigthAdd * (2 + beseRun * 8), Element.ALIGN_LEFT, 45, true , 550, 15); } beseRun++; if (beseRun < getPageOne.Count()) { AddNewLable(dicTitle, "--------------------------------------------------由此撕开--------------------------------------------------" , "" , ConByte_Up, fontLIGHT_GRAY, fontToValue, 300, TcurrBaseY - TcurrHeigthAdd * (beseRun * 8) + TcurrHeigthAdd, Element.ALIGN_CENTER); } } return beseRun; } private static void AddNewLable(Dictionary< string , string > dic, string lableName, string keyName, PdfContentByte ConByte_Up, Font fontToLabel, Font fontToValue, float x, float y, int ealign = Element.ALIGN_LEFT, float w = 30, bool isMuli = false , float muliWidth = 130, float muliHeightAdd = 30, float rotation = 0) { if (y <= 0) { y = 10; } if (!lableName.IsNullOrEmpty()) { Phrase Phr_lable = new Phrase(lableName, fontToLabel); ColumnText.ShowTextAligned(ConByte_Up, ealign, Phr_lable, x, y, rotation); } string GetValue = dic.ContainsKey(keyName) ? dic[keyName] : "" ; if (!GetValue.IsNullOrEmpty()) { if (isMuli) { ColumnText column = new ColumnText(ConByte_Up); column.SetSimpleColumn( new Phrase(GetValue, fontToValue), muliWidth, 0, x + w, y + muliHeightAdd, 15, Element.ALIGN_TOP); column.Go(); } else { Phrase Phr_Value = new Phrase(GetValue, fontToValue); ColumnText.ShowTextAligned(ConByte_Up, ealign, Phr_Value, x + w, y, rotation); } } } private static void AddImageToDoc(PdfWriter writer, Image img, float x, float y, float percent = 1) { //这里用计算出来的百分比来缩小图片 img.ScalePercent(percent * 100); //图片定位,页面总宽283,高416;这里设置0,0的话就是页面的左下角 让图片的中心点与页面的中心店进行重合 img.SetAbsolutePosition(x, y); writer.DirectContent.AddImage(img); } /// <summary> /// 用于xx书 /// </summary> public string PDFWithAddImage( string filePath, string filePath2, string ydcode1) { using (Stream inputPdfStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) using (Stream outputPdfStream = new FileStream(filePath2, FileMode.Create, FileAccess.Write, FileShare.None)) { var reader = new PdfReader(inputPdfStream); var stamper = new PdfStamper(reader, outputPdfStream); var pdfContentByte = stamper.GetOverContent(1); //插入图片 var ydcode1Image = GetImageCode128(ydcode1); //var ydcode2Image = GetImageCode128(ydcode1); var ydcode1ImageToPost = GetImageToPoint(ydcode1Image, 0.5f, 2, 340); var ydcode2ImageToPost = GetImageToPoint(ydcode1Image, 0.5f, 2, 170); pdfContentByte.AddImage(ydcode1ImageToPost); pdfContentByte.AddImage(ydcode2ImageToPost); stamper.Close(); } return filePath2; } public Image GetImageToPoint(System.Drawing.Image image, float percentage, float x, float y) { Image img = Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Bmp); //这里用计算出来的百分比来缩小图片 img.ScalePercent(percentage * 100); img.ScaleAbsoluteHeight(img.PlainHeight * 4); //图片定位,页面总宽283,高416;这里设置0,0的话就是页面的左下角 让图片的中心点与页面的中心店进行重合 img.SetAbsolutePosition(x, y); return img; } public void DeleteFile( string saveFilePath) { try { File.Delete(saveFilePath); } catch (Exception ex) { } } |
3 字体相关
1 2 3 | //设置支持中文字体 BaseFont baseFont = BaseFont.CreateFont( "C:\\WINDOWS\\FONTS\\msyhbd.TTC,0" , BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); pdfFormFields.AddSubstitutionFont(baseFont); |
4 条码
1 2 3 4 5 6 | public System.Drawing.Image GetImageCode128( string codetext) { System.Drawing.Image ydcodeImage = Code128Rendering.MakeBarcodeImage(codetext, 2, true ); return ydcodeImage; } |
5 获对象属性值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public Dictionary< string , string > getProperties<T>(T t) { Dictionary< string , string > tStr = new Dictionary< string , string >(); if (t == null ) { return tStr; } System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); if (properties.Length <= 0) { return tStr; } foreach (System.Reflection.PropertyInfo item in properties) { string name = item.Name; object value = item.GetValue(t, null ); if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith( "String" )) { tStr.Add(name, value.ToNotNullString()); } } return tStr; } |
6 向pdf中加内容图片什么的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public string PDFWithAddImage( string filePath, string filePath2, string ydcode1) { using (Stream inputPdfStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) using (Stream outputPdfStream = new FileStream(filePath2, FileMode.Create, FileAccess.Write, FileShare.None)) { var reader = new PdfReader(inputPdfStream); var stamper = new PdfStamper(reader, outputPdfStream); var pdfContentByte = stamper.GetOverContent(1); //插入图片 var ydcode1Image = GetImageCode128(ydcode1); //var ydcode2Image = GetImageCode128(ydcode1); var ydcode1ImageToPost = GetImageToPoint(ydcode1Image, 0.5f, 2, 340); var ydcode2ImageToPost = GetImageToPoint(ydcode1Image, 0.5f, 2, 170); pdfContentByte.AddImage(ydcode1ImageToPost); pdfContentByte.AddImage(ydcode2ImageToPost); stamper.Close(); } return filePath2; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构