iTextSharp动态生成多页pdf及追加内容等记录

1.初始化代码

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.小方法

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 字体相关

 //设置支持中文字体  
                BaseFont baseFont = BaseFont.CreateFont("C:\WINDOWS\FONTS\msyhbd.TTC,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                pdfFormFields.AddSubstitutionFont(baseFont);

4 条码

 

   public System.Drawing.Image GetImageCode128(string codetext)
        {
            System.Drawing.Image ydcodeImage = Code128Rendering.MakeBarcodeImage(codetext, 2, true);

            return ydcodeImage;
        }

5 获对象属性值

 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中加内容图片什么的

  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;

        }

  

  

原文地址:https://www.cnblogs.com/xlgwr/p/iTextSharp.html