首页 > 其他分享 >Itextsharp_v416-非商用项目中的PDF生成方案

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

时间:2024-05-08 22:33:58浏览次数:14  
标签:text v416 iTextSharp pdfTable cell Itextsharp new PDF document

    项目演示地址: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());
 }

 

标签:text,v416,iTextSharp,pdfTable,cell,Itextsharp,new,PDF,document
From: https://www.cnblogs.com/qq2806933146xiaobai/p/18181045

相关文章

  • MuPDF
    MuPDFhttps://mupdf.com/https://mupdf.readthedocs.io/en/latest/index.html是一个轻量级的PDF、XPS和电子书查看器。MuPDF由软件库、命令行工具和适用于各种平台的查看器组成。MuPDF中的渲染器专为高质量抗锯齿图形而定制。它以精确到像素分数的度量和间距渲染文本,以......
  • 【专题】2022年中国制造业数字化转型研究报告PDF合集分享(附原数据表)
    报告链接:http://tecdat.cn/?p=32145本文中所说的制造业数字化转型,指的是在制造企业的设计、生产、管理、销售及服务的每一个环节中,将新一代信息技术应用到制造企业的设计、生产、管理、销售及服务的每一个环节中,并可以以每一个环节中产生的数据为基础,展开控制、监测、检测、预测......
  • Python 将PDF转为PDF/A、PDF/X,以及PDF/A转回PDF
    PDF/A和PDF/X是两种有特定用途的PDF格式,具体查看以下:PDF/A是一种用于长期存档的PDF格式,它旨在确保文档的内容和格式在未来的访问中保持不变。如果您需要对文件进行长期存档,比如法律文件或档案记录,将其转换为PDF/A格式是一个明智的选择。PDF/X是一种用于印刷输出的PDF格式,它旨在......
  • 读取PDF文件,并写入excel表
    importrefromopenpyxlimportWorkbookpdf_name='D:/beifangzhongzhi/zhongye/百保科技/疾病/疾病.pdf'importPyPDF2defget_text(pdf_name):withopen(pdf_name,'rb')asfile:reader=PyPDF2.PdfReader(file)num_pages=......
  • pdf.js源码分析-textLayer中的坐标计算
    在pdf.js中显示pdf内容和选择pdf文字属于不同的层,一个是canvas绘制,一个是使用dom进行布局,那么接下来先看一下在textLayer中的文字节点div是怎么计算每段文字的布局位置的吧。首先找到pdf.js源码中的text_layer.js文件,然后得到下面方法appendText方法,下面的解释是在字体没有发生旋......
  • 扫描版PDF电子书目录制作方法
    前置条件书籍:扫描版《软件调试》(请支持正版......
  • 【专题】2024年4月消费趋势报告合集汇总PDF分享(附原数据表)
    原文链接:https://tecdat.cn/?p=36089原文出处:拓端数据部落公众号随着科技的不断进步和全球化的深入发展,各行各业都面临着前所未有的机遇与挑战。从零售业的变革到美妆行业的崛起,从消费者行为的转变到营销策略的创新,每一个领域都在不断地演进和重塑。在快速变化的市场环境中,消费......
  • 代码修改pdf文件
    上篇说在python修改pdf上很费了些周张,效果却了了,看着网上连绵不绝的在线pdf编辑网站,疑是有钱赚的地不给草民磨推。其一,发现用记事本打印输出的pdf文件,用PyPDF2,pdfplumber,都是可以获取文本信息,并用replace方法修改,vscode其其它增强文本编辑器,用的也是MicrosoftPrinttoPDF,输出的......
  • 使用vscode写Markdown并且导出为pdf(干货)
    目录序言下载vscode安装插件markdown语法导出为pdf序言大家在学习过程中都会有记笔记的好习惯(美观的笔记当然是上上选),于是,Markdown就是一个不错的选择,待会也会附上一下常用基础语法。笔者比较喜欢使用vscode,有插件它就是无所不能的(bush。下载vscode官网下载https://code.v......
  • 【专题】消费品行业的5G新时代:2024年消费品行业趋势洞察报告合集PDF分享(附原数据表)
    原文链接:https://tecdat.cn/?p=36059原文出处:拓端数据部落公众号2023年,我国社会消费品零售总额同比增长7.2%,呈现出稳健而强劲的增长态势。与此同时,最终消费支出对经济增长的贡献率显著提升,达到了82.5%,比去年提高了3.1个百分点,这进一步凸显了消费在驱动我国经济发展中的核心作用......