Itextsharp_v416-非商用项目中的PDF生成方案

    项目演示地址:https://gitee.com/qq28069933146_admin/itextsharp_v416_qrcoder_simple(因为itextsharp_v416涉及敏感开源协议的原因项目已删除;虽然只是LGPL协议)

1、主要可参考代码如下:

        /// <summary>
        /// 生成PDF按钮 - 带二维码
        /// </summary>
        private void BtnProducePDF_Click(object sender, EventArgs e)
        {
            string strName = txtName.Text.Trim();          // 姓名
            string strGender = txtGender.Text.Trim();      // 性别
            string strAge = txtAge.Text.Trim();            // 年龄
            string strAddress = txtAddress.Text.Trim();    // 住址
            string strIDNumber = txtIDNumber.Text.Trim();  // 身份证号

            #region 校验数据
            if (string.IsNullOrEmpty(strName))
            {
                MessageBox.Show("姓名不可为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (string.IsNullOrEmpty(strGender))
            {
                MessageBox.Show("性别不可为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (string.IsNullOrEmpty(strAge))
            {
                MessageBox.Show("年龄不可为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (string.IsNullOrEmpty(strAddress))
            {
                MessageBox.Show("住址不可为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (string.IsNullOrEmpty(strIDNumber))
            {
                MessageBox.Show("身份证号不可为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            #endregion 校验数据

            // 生成二维码
            string qrCodeDataStr = string.Concat(strName, ",", strGender, ",", strAge, ",", strAddress, ",", strIDNumber);
            Bitmap bitmap = QRCoderHelper.CreateQRCode(qrCodeDataStr, QRCodeGenerator.ECCLevel.Q, 20, System.Drawing.Color.Yellow, System.Drawing.Color.Blue);
            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(bitmap, System.Drawing.Imaging.ImageFormat.Png);

            #region 生成PDF布局
            // 表格
            //PdfPTable pdfTable = new PdfPTable(new float[] { 1f, 2f, 2f });  // 指定列数量及列宽
            PdfPTable pdfTable = new PdfPTable(3);           // 指定列数量
            pdfTable.SetWidths(new float[] { 1f, 2f, 2f });  // 指定列宽
            pdfTable.TotalWidth = 300f;                      // 设置表格总宽度
            pdfTable.LockedWidth = true;                     // 是否固定列宽
            pdfTable.HorizontalAlignment = 0;                // 水平居中;0=Left, 1=Centre, 2=Right

            // 表头
            pdfTable.AddCell(PDFTableHeaderCell("身份信息"));

            // 表身
            pdfTable.AddCell(PDFTableBodyCell("姓名:"));
            pdfTable.AddCell(PDFTableBodyCell(strName));

            pdfTable.AddCell(PDFTableBodyCell_Img(image, 5, 1));  // 插入图片

            pdfTable.AddCell(PDFTableBodyCell("性别:"));
            pdfTable.AddCell(PDFTableBodyCell(strGender));
            pdfTable.AddCell(PDFTableBodyCell("年龄:"));
            pdfTable.AddCell(PDFTableBodyCell(strAge));
            pdfTable.AddCell(PDFTableBodyCell("住址:"));
            pdfTable.AddCell(PDFTableBodyCell(strAddress));
            pdfTable.AddCell(PDFTableBodyCell("身份证号:"));
            pdfTable.AddCell(PDFTableBodyCell(strIDNumber));

            //pdfTable.DeleteLastRow();                   // 删除最后一行
            //pdfTable.DeleteRow(pdfTable.Rows.Count-1);  // 删除某一行
            #endregion 生成PDF布局

            #region 生成PDF载体(我这里使用的Document)
            // 生成PDF载体(我这里使用的Document)
            Document document = null;
            if (true)
            {
                // A4纸张
                document = new Document(PageSize.A4);
            }
            else
            {
                // 自定义纸张大小与页距
                var pageInfo = new iTextSharp.text.Rectangle(226.4f, 169.8f);  // 页面有效区域80*60 mm
                pageInfo.BackgroundColor = iTextSharp.text.Color.PINK;  // 页面背景色
                pageInfo.BorderColor = iTextSharp.text.Color.BLUE;      // 页面边框色
                document = new Document(pageInfo, 2f, 2f, 2f, 2f);             // 页面有效区域, 左右上下页距
            }

            document.AddTitle("标题");           // 标题
            document.AddSubject("主题");         // 主题
            document.AddKeywords("关键字");      // 关键字
            document.AddAuthor("作者");          // 作者
            document.AddCreator("创建者");       // 创建者
            //document.Header = new HeaderFooter(new Phrase(), new Phrase());  // 设置文档的页头
            //document.Footer = new HeaderFooter(new Phrase(), new Phrase());  // 设置文档的页尾
            document.JavaScript_onLoad = null;    // 文档加载时运行的脚本
            document.JavaScript_onUnLoad = null;  // 文档卸载时运行的脚本

            using (FileStream fileStream = new FileStream($"D:\\{DateTime.Now.ToString("yyyyMMdd_HH_mm_ss")}.pdf", FileMode.Create))
            {
                PdfWriter writer = PdfWriter.GetInstance(document, fileStream);
                document.Open();

                document.Add(pdfTable);  // 添加pdf表格数据
                document.NewPage();  // 换页
                document.Add(new Paragraph("Hello,End!"));  // 随便写点东西试下换页;添加一个段落 (演示结束了!)

                document.Close();
                fileStream.Close();
                writer.Close();  // 保存为PDF文件
            }
            #endregion 生成PDF载体(我这里使用的Document)
        }

        #region PdfP演示表格的样式
        /// <summary>
        /// 字体
        /// </summary>
        BaseFont baseFont = BaseFont.CreateFont("C:\\Windows\\Fonts\\simkai.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);  // 字体 楷体常规

        /// <summary>
        /// 表头样式
        /// </summary>
        /// <param name="cellValue">表格内容</param>
        /// <param name="fontSize">字体大小</param>
        /// <returns></returns>
        public PdfPCell PDFTableHeaderCell(string cellValue, int fontSize = 16)
        {
            iTextSharp.text.Font cn = new iTextSharp.text.Font(baseFont, fontSize, iTextSharp.text.Font.BOLD);  // 字体样式:字体,大小,样式

            PdfPCell cell = new PdfPCell(new Phrase(cellValue, cn));
            cell.Rowspan = 1;              // 跨1行
            cell.Colspan = 3;              // 跨3列
            cell.HorizontalAlignment = 1;  // 水平居中;0=Left, 1=Centre, 2=Right
            cell.VerticalAlignment = 1;    // 垂直居中;0=Left, 1=Centre, 2=Right
            cell.MinimumHeight = 20;       // 最小高度
            cell.Padding = 0;  // 内间距为0
            cell.BackgroundColor = iTextSharp.text.Color.YELLOW;  // 背景色为YELLOW
            cell.BorderColor = iTextSharp.text.Color.RED;         // 边框色为RED
            cell.BorderWidth = 1;                                 // 边框宽度为1

            return cell;
        }

        /// <summary>
        /// 表身样式
        /// </summary>
        /// <param name="cellValue">表格内容</param>
        /// <param name="fontSize">字体大小</param>
        /// <returns></returns>
        public PdfPCell PDFTableBodyCell(string cellValue, int fontSize = 10)
        {
            iTextSharp.text.Font cn = new iTextSharp.text.Font(baseFont, fontSize, iTextSharp.text.Font.NORMAL);  // 字体样式:字体,大小,样式

            PdfPCell cell = new PdfPCell(new Phrase(cellValue, cn));
            cell.HorizontalAlignment = 1;  // 水平居中;0=Left, 1=Centre, 2=Right
            cell.VerticalAlignment = 1;    // 垂直居中;0=Left, 1=Centre, 2=Right
            cell.BorderWidth = 1;          // 边框宽度为1

            return cell;
        }

        /// <summary>
        /// 表身样式-图片
        /// </summary>
        /// <param name="cellValue">表格内容</param>
        /// <param name="rowspan">跨行</param>
        /// <param name="colspan">跨列</param>
        /// <returns></returns>
        public PdfPCell PDFTableBodyCell_Img(iTextSharp.text.Image cellImg, int rowspan = 1, int colspan = 1)
        {
            PdfPCell cell = new PdfPCell(cellImg,true);
            cell.Rowspan = rowspan;        // 跨行
            cell.Colspan = colspan;        // 跨列
            cell.HorizontalAlignment = 1;  // 水平居中;0=Left, 1=Centre, 2=Right
            cell.VerticalAlignment = 1;    // 垂直居中;0=Left, 1=Centre, 2=Right
            cell.BorderWidth = 1;          // 边框宽度为1

            return cell;
        }
        #endregion PdfP演示表格的样式

2、Main方法中需加入注册EncodeProvider的代码

  用于解决字体报错

 static void Main()
 {
     // 注册EncodeProvider(.netcore默认没有)
     Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
     Console.WriteLine("这是中文输出");
     Console.WriteLine("This is english output.");
     Console.WriteLine(Console.ReadLine());

     ApplicationConfiguration.Initialize();
     Application.Run(new Form1());
 }

 

posted @   ꧁执笔小白꧂  阅读(38)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示