iTextSharp 生成复杂的PDF(包括 插入图片,内嵌表格,checkbox勾选,添加水印等)

iTextSharp 生成复杂的PDF(包括 插入图片,内嵌表格,checkbox勾选,添加水印等)

 

  • ₤😂

第一次用iTextSharp生成复杂的PDF 做下记录

1 安装nug包
 

图片.png

引用
using iTextSharp.text;
using iTextSharp.text.pdf;

2 生成PDF(存在生成二维码图片,具体见上一篇文章,本章只赋代码)

样例:


 

图片.png

代码


 public bool ExportReceipt()
        {
            // 生成二维码的内容
            string strCode = "2020100700004";
            QRCodeGenerator qrGenerator = new QRCoder.QRCodeGenerator();
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(strCode, QRCodeGenerator.ECCLevel.Q);
            QRCode qrcode = new QRCode(qrCodeData);

            // qrcode.GetGraphic 方法可参考最下发“补充说明”
            Bitmap qrCodeImage = qrcode.GetGraphic(5, Color.Black, Color.White, null, 15, 6, false);
            MemoryStream ms = new MemoryStream();
            qrCodeImage.Save(ms, ImageFormat.Jpeg);

            // 保存图片 
            var ImgPath = TestUtils.GetQRFileName();
            qrCodeImage.Save(ImgPath);

            var pdfFilePath = TestUtils.GetOutputFileName();
            if (System.IO.File.Exists(Path.GetFullPath(pdfFilePath)))
            {
                System.IO.File.Delete(Path.GetFullPath(pdfFilePath));
            }
            var fileStream = new FileStream(pdfFilePath, FileMode.Create);
            var pdfDoc = new Document(PageSize.A4);
            var pdfWriter = PdfWriter.GetInstance(pdfDoc, fileStream);

            pdfDoc.AddAuthor(TestUtils.Author);
            pdfDoc.Open();

            // 中文字体,解决中文不能显示问题
            BaseFont bfChinese = BaseFont.CreateFont("C:\\WINDOWS\\FONTS\\SIMSUN.TTC,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//BaseFont bfChinese = BaseFont.CreateFont("C:\\WINDOWS\\FONTS\\SIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
           
            //标题
            Font fonttitle = new Font(bfChinese, 19, Font.BOLD); //加粗

            //空一行
            Font fontnull = new Font(bfChinese, 6);

            // 五号
            Font fiveFont = new Font(bfChinese, 10f);   // 五号 10.5f 小三号 15

            //勾选图片
            System.Drawing.Image imageRight = System.Drawing.Image.FromFile(TestUtils.GetRightFileName());
            System.Drawing.Image imageWrong = System.Drawing.Image.FromFile(TestUtils.GetWrongFileName());

            //添加标题
            Paragraph Title = new Paragraph("XXX登记收件收据", fonttitle);
            Title.Alignment = iTextSharp.text.Rectangle.ALIGN_CENTER;       //设置居中
            pdfDoc.Add(Title);        //将标题段加入PDF文档中

            //插入二维码
            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(ImgPath);
            image.ScalePercent(60);//设置图片比例
            image.SetAbsolutePosition(pdfDoc.PageSize.Width - 97, pdfDoc.PageSize.Height - 80);//设置图片的绝对位置
            pdfDoc.Add(image);

            //空一行
            Paragraph nullp = new Paragraph(" ", fontnull);
            pdfDoc.Add(nullp);

            Paragraph Num = new Paragraph("业务编号: 2020100700004", fiveFont);
            //Num.Alignment = iTextSharp.text.Rectangle.ALIGN_CENTER;       //设置居中
            pdfDoc.Add(Num);

            //空一行
            pdfDoc.Add(nullp);

            // 新建表格 4列.
            PdfPTable table0 = new PdfPTable(4)
            {
                WidthPercentage = 100,// 宽度100%填充,
            };
            // 设置列宽
            float[] columnWidths0 = { 0.4f, 0.8f, 0.4f, 0.8f };
            table0.SetWidths(columnWidths0);

            //正文第1行
            TestUtils.CreateCell(table0, "XXX证书", fiveFont);
            TestUtils.CreateCell(table0, "XXX第0915661号", fiveFont,26,3);
            TestUtils.CreateCell(table0, "申 请 人", fiveFont);
            TestUtils.CreateCell(table0, "XXX", fiveFont);
            TestUtils.CreateCell(table0, "交 件 人", fiveFont);
            TestUtils.CreateCell(table0, "XXX", fiveFont);
            TestUtils.CreateCell(table0, "交件人通讯地址", fiveFont);
            TestUtils.CreateCell(table0, "", fiveFont);
            TestUtils.CreateCell(table0, "交件人联系电话", fiveFont);
            TestUtils.CreateCell(table0, "XXX", fiveFont);
            TestUtils.CreateCell(table0, "业 务 类 型", fiveFont);
            TestUtils.CreateCell(table0, "XXX", fiveFont);
            TestUtils.CreateCell(table0, "查 询 密 码", fiveFont);
            TestUtils.CreateCell(table0, "XXX", fiveFont);
            TestUtils.CreateCell(table0, "坐 落", fiveFont);
            TestUtils.CreateCell(table0, "XXX", fiveFont,26,3);

            pdfDoc.Add(table0);

            // 新建表格.
            PdfPTable table1 = new PdfPTable(3)
            {
                WidthPercentage = 100,// 宽度100%填充,
            };
            // 设置列宽
            float[] columnWidths1 = { 0.4f, 1.0f, 1.0f};
            table1.SetWidths(columnWidths1);
            TestUtils.CreateCell(table1, "提供的附件材料", fiveFont);
            
            //内部表1
            PdfPTable nested1 = new PdfPTable(1);
            nested1.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            TestUtils.CreateNesCell(nested1, "1 .XXX", fiveFont);
            TestUtils.CreateNesCell(nested1, "2 .XXX", fiveFont);
            TestUtils.CreateNesCell(nested1, "3 .XXX", fiveFont);
            TestUtils.CreateNesCell(nested1, "4 .XXX", fiveFont);
            TestUtils.CreateNesCell(nested1, "5 .XXX", fiveFont);
            TestUtils.CreateNesCell(nested1, "6 .XXX", fiveFont);
            TestUtils.CreateNesCell(nested1, "7 .XXX", fiveFont);
            TestUtils.CreateNesCell(nested1, "8 .XXX", fiveFont);
            TestUtils.CreateNesCell(nested1, "", fiveFont);//因为排版的问题 加一行空值
            TestUtils.CreateNesCell(nested1, "", fiveFont);//因为排版的问题 加一行空值

            table1.AddCell(nested1);
            
            //内部表2
            PdfPTable nested2 = new PdfPTable(5);
            nested2.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            float[] columnWidths2 = { 0.9f,0.2f,0.3f,0.2f,0.8f };
            nested2.SetWidths(columnWidths2);
            TestUtils.CreateNesCell(nested2, "是否同意邮寄:", fiveFont);
            //TestUtils.GetRightImage(nested2);
            TestUtils.GetCheckImage(nested2,true);
            TestUtils.CreateNesCell(nested2, "是", fiveFont);
            TestUtils.GetCheckImage(nested2);
            TestUtils.CreateNesCell(nested2, "否", fiveFont);
            TestUtils.CreateNesCell(nested2, "收取人:", fiveFont);
            TestUtils.CreateNesCell(nested2, "", fiveFont, 15, 4);
            TestUtils.CreateNesCell(nested2, "联系电话:", fiveFont);
            TestUtils.CreateNesCell(nested2, "", fiveFont, 15, 4);
            TestUtils.CreateNesCell(nested2, "邮递地址:", fiveFont);
            TestUtils.CreateNesCell(nested2, "", fiveFont, 15, 4);
            TestUtils.CreateNesCell(nested2, "", fiveFont, 15, 5);
            TestUtils.CreateNesCell(nested2, "是否本人领取:", fiveFont);
            TestUtils.GetCheckImage(nested2, true);
            TestUtils.CreateNesCell(nested2, "是", fiveFont);
            TestUtils.GetCheckImage(nested2);
            TestUtils.CreateNesCell(nested2, "否", fiveFont);
            TestUtils.CreateNesCell(nested2, "领证人姓名:", fiveFont);
            TestUtils.CreateNesCell(nested2, "XXX", fiveFont, 15, 4);
            TestUtils.CreateNesCell(nested2, "联系电话:", fiveFont);
            TestUtils.CreateNesCell(nested2, "1XXX", fiveFont, 15, 4);
            TestUtils.CreateNesCell(nested2, "", fiveFont,15,5); //因为排版的问题 加一行空值
            table1.AddCell(nested2);

            pdfDoc.Add(table1);

            // 表尾
            Paragraph thrtionTitle = new Paragraph("收件人: XXX        收件日期: 2020年10月07日        承诺时间:自收件之日起二个工作日内办结。", fiveFont);
            pdfDoc.Add(thrtionTitle);
         
            pdfDoc.Close();
            fileStream.Dispose();

            TestUtils.VerifyPdfFileIsReadable(pdfFilePath);
          
            //添加水印
            //var outputfilepath = @"D:\Preapplication\123.pdf";
            //var watermarkpath=@"D:\watermark.jpg";
            //return TestUtils.PDFWatermark(pdfFilePath, outputfilepath, watermarkpath);

            return true;
        }

public static class TestUtils
    {
        const string ITextExamplesFolder = "iTextExamples";
        const string ResourcesFolder = "resources";

        public static string Author => "VahidN";

        public static string GetBaseDir()
        {
            var currentAssembly = typeof(TestUtils).GetTypeInfo().Assembly;
            var root = Path.GetDirectoryName(currentAssembly.Location);
            var idx = root.IndexOf($"{Path.DirectorySeparatorChar}bin", StringComparison.OrdinalIgnoreCase);
            return root.Substring(0, idx);
        }

        public static string GetImagePath(string fileName)
        {

            return Path.Combine(GetBaseDir(), ITextExamplesFolder, ResourcesFolder, "img", fileName);
        }

        //创建列
        public static void CreateCell(PdfPTable table,string content,Font font,int minimumHeight=26,int colspan=0,int rowspan = 0)
        {
            var cell = new PdfPCell(new Phrase(content, font));
            cell.UseAscender = true;// 设置可以居中
            cell.MinimumHeight = minimumHeight;// 设置单元格高度
            cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;// 设置水平居中
            cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;// 设置垂直居中
            if(rowspan != 0)
            {
                cell.Rowspan = rowspan; //行合并
            }
            if (colspan != 0)
            {
                cell.Colspan = colspan; //列合并
            }
            table.AddCell(cell);
        }

        //创建内表列
        public static void CreateNesCell(PdfPTable table, string content, Font font, int minimumHeight = 15, int colspan = 0, int rowspan = 0)
        {
            var cell = new PdfPCell(new Phrase(content, font));
            cell.UseAscender = true;// 设置可以居中
            cell.MinimumHeight = minimumHeight;// 设置单元格高度
            cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
            cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;// 设置垂直居中
            cell.Border= iTextSharp.text.Rectangle.NO_BORDER; 
            if (rowspan != 0)
            {
                cell.Rowspan = rowspan; //行合并
            }
            if (colspan != 0)
            {
                cell.Colspan = colspan; //列合并
            }
            table.AddCell(cell);
        }

        //生成二维码的路径
        public static string GetQRFileName()
        {
            return Path.Combine(GetOutputFolder(), $"Qr.jpg");
        }

        //勾选图片路径
        public static string GetRightFileName()
        {
            return Path.Combine(GetOutputFolder(), $"right.jpg");
        }

        //加载勾选图片
        public static void GetRightImage(PdfPTable table)
        {
            System.Drawing.Image imageRight = System.Drawing.Image.FromFile(TestUtils.GetRightFileName());
            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageRight, iTextSharp.text.BaseColor.WHITE);
            var cell = new PdfPCell();
            //cell.MinimumHeight = 20;
            cell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            image.ScaleToFit(1, 1);
            cell.Image = image;
            cell.FixedHeight = cell.MinimumHeight;
            table.AddCell(cell);
            imageRight.Dispose();
        }

        //未勾选图片路径
        public static string GetWrongFileName() 
        {
            return Path.Combine(GetOutputFolder(), $"wrong.jpg");
        }

        //加载未勾选图片
        public static void GetWrongImage(PdfPTable table)
        {
            System.Drawing.Image imageRight = System.Drawing.Image.FromFile(TestUtils.GetWrongFileName());
            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageRight, iTextSharp.text.BaseColor.WHITE);
            var cell = new PdfPCell();
            cell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            image.ScaleToFit(1, 1);
            cell.Image = image;
            cell.FixedHeight = cell.MinimumHeight;
            table.AddCell(cell);
            imageRight.Dispose();
        }

        //根据true和false 加载选择勾选图片
        public static void GetCheckImage(PdfPTable table,bool check=false)
        {
            System.Drawing.Image imageCheck = System.Drawing.Image.FromFile(TestUtils.GetWrongFileName());
            if (check == true)
            {
                imageCheck = System.Drawing.Image.FromFile(TestUtils.GetRightFileName());
            }

            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageCheck, iTextSharp.text.BaseColor.WHITE);
            var cell = new PdfPCell();
            cell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            image.ScaleToFit(1, 1);
            cell.Image = image;
            cell.FixedHeight = cell.MinimumHeight;
            table.AddCell(cell);
            imageCheck.Dispose();
        }

        //询问笔录
        public static void QuestionRecordIsBool(PdfPTable table,Font font,bool check = true)
        {
            //内嵌表1
            PdfPTable nested = new PdfPTable(5);
            nested.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            float[] columnWidths = { 0.2f, 0.1f, 0.4f, 0.1f, 1.4f }; // 0.6f, 0.1f, 0.2f, 0.1f, 1.4f
            nested.SetWidths(columnWidths);
            TestUtils.CreateNesCell(nested, "回答:", font, 12);
            if (check == true)
            {
                TestUtils.GetCheckImage(nested, true);
                TestUtils.CreateNesCell(nested, "是", font, 12);
                TestUtils.GetCheckImage(nested);
                TestUtils.CreateNesCell(nested, "否", font, 12);
            }
            else
            {
                TestUtils.GetCheckImage(nested);
                TestUtils.CreateNesCell(nested, "是", font, 12);
                TestUtils.GetCheckImage(nested,true);
                TestUtils.CreateNesCell(nested, "否", font, 12);
            }
            table.AddCell(nested);
        }

        public static void QuestionRecordIsType(PdfPTable table, Font font, string content1,string content2,bool check = true)
        {
            //内嵌表1
            PdfPTable nested = new PdfPTable(5);
            nested.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            float[] columnWidths = { 0.2f, 0.1f, 0.4f, 0.1f, 1.4f }; // 0.6f, 0.1f, 0.2f, 0.1f, 1.4f
            nested.SetWidths(columnWidths);
            TestUtils.CreateNesCell(nested, "回答:", font);
            if (check == true)
            {
                TestUtils.GetCheckImage(nested, true);
                TestUtils.CreateNesCell(nested, content1, font); //共有   按份共有
                TestUtils.GetCheckImage(nested);
                TestUtils.CreateNesCell(nested, content2, font);//单独所有  共同共有
            }
            else
            {
                TestUtils.GetCheckImage(nested);
                TestUtils.CreateNesCell(nested, content1, font);
                TestUtils.GetCheckImage(nested, true);
                TestUtils.CreateNesCell(nested, content2, font);
            }
            table.AddCell(nested);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        public static string GetOutputFileName([CallerMemberName] string methodName = null)
        {
            return Path.Combine(GetOutputFolder(), $"{methodName}.pdf");
        }

        public static string GetOutputFolder()
        {
            var dir = Path.Combine(GetBaseDir(), "bin", "out");
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            return dir;
        }

        public static string GetPosterPath(string fileName)
        {
            return Path.Combine(GetBaseDir(), ITextExamplesFolder, ResourcesFolder, "posters", fileName);
        }

        public static string GetFontPath(string fileName)
        {
            return Path.Combine(GetBaseDir(), ITextExamplesFolder, ResourcesFolder, "fonts", fileName);
        }

        public static string GetTahomaFontPath()
        {
            return GetFontPath("tahoma.ttf");
        }

        public static string GetArialUnicodeMSFontPath()
        {
            return GetFontPath("arialuni.ttf");
        }

        public static string GetSimSunFontPath()
        {
            return GetFontPath("simsun.ttf");
        }

        public static string GetThaiFontPath()
        {
            return GetFontPath("thsarabunnew.ttf");
        }

        public static string GetTxtPath(string fileName)
        {
            return Path.Combine(GetBaseDir(), ITextExamplesFolder, ResourcesFolder, "txt", fileName);
        }

        public static string GetPdfsPath(string fileName)
        {
            return Path.Combine(GetBaseDir(), ITextExamplesFolder, ResourcesFolder, "pdfs", fileName);
        }

        public static Font GetUnicodeFont(
                    string fontName, string fontFilePath, float size, int style, BaseColor color)
        {
            if (!FontFactory.IsRegistered(fontName))
            {
                FontFactory.Register(fontFilePath);
            }
            return FontFactory.GetFont(fontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, size, style, color);
        }

        public static void VerifyPdfFileIsReadable(byte[] file)
        {
            PdfReader reader = null;
            try
            {
                reader = new PdfReader(file);
                var author = reader.Info["Author"] as string;
                if (string.IsNullOrWhiteSpace(author) || !author.Equals(Author))
                {
                    throw new InvalidPdfException("This is not a valid PDF file.");
                }
            }
            finally
            {
                reader?.Close();
            }
        }

        public static void VerifyPdfFileIsReadable(string filePath)
        {
            VerifyPdfFileIsReadable(File.ReadAllBytes(filePath));
        }



        /// <summary>
        /// 加平铺图片水印
        /// </summary>
        /// <param name="inputfilepath"></param>
        /// <param name="outputfilepath"></param>
        /// <param name="ModelPicName"></param>
        /// <returns></returns>
        public static bool PDFWatermark(string inputfilepath, string outputfilepath, string ModelPicName)
        {
            //throw new NotImplementedException();
            PdfReader pdfReader = null;
            PdfStamper pdfStamper = null;
            try
            {
                pdfReader = new PdfReader(inputfilepath);

                int numberOfPages = pdfReader.NumberOfPages;
                iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);

                float width = psize.Width;
                float height = psize.Height;
                pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));

                PdfContentByte waterMarkContent;
                PdfGState gs = new PdfGState();
                gs.FillOpacity = 0.2f;

                iTextSharp.text.Image imgTemp = iTextSharp.text.Image.GetInstance(ModelPicName);
                float imgWidth = (float)Math.Cos(Math.PI / 4) * imgTemp.Width + 100;
                float imgHeight = (float)Math.Sin(Math.PI / 4) * imgTemp.Width + 100;


                //每一页加水印,也可以设置某一页加水印
                for (int i = 1; i <= numberOfPages; i++)
                {
                    //waterMarkContent = pdfStamper.GetUnderContent(i);//内容下层加水印
                    waterMarkContent = pdfStamper.GetOverContent(i);//内容上层加水印
                    waterMarkContent.SetGState(gs);

                    for (float left = 0; left < width; left += imgWidth)
                    {
                        for (float top = 0; top < height; top += imgHeight)
                        {
                            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(ModelPicName);
                            image.GrayFill = 100;//透明度,灰色填充
                            //image.Rotation = 45;//旋转
                            image.RotationDegrees = 45;//旋转角度
                            image.SetAbsolutePosition(left, height - image.Height - top);
                            Console.WriteLine(left + ":" + (height - image.Height - top));
                            waterMarkContent.AddImage(image);
                        }
                    }
                }
                //strMsg = "success";
                return true;
            }
            catch (Exception ex)
            {
                throw ex;

            }
            finally
            {

                if (pdfStamper != null)
                    pdfStamper.Close();

                if (pdfReader != null)
                    pdfReader.Close();
            }
        }
    }

备注说明: 需要提前保存勾选图片