wpf .netcore 导出pdf文件

发布于:2025-09-09 ⋅ 阅读:(15) ⋅ 点赞:(0)

PdfTableHelper.cs

   

 public class PdfTableHelper
    {
        /// <summary>
        /// 表一 基本信息
        /// </summary>
        public static PdfModels Table1 { get; set; } = new();

        /// <summary>
        /// 表二 程序参数
        /// </summary>
        public static PdfModels Table2 { get; set; } = new();

        /// <summary>
        /// 第三部分 表格的集合
        /// </summary>
        public static List<PdfModels> TileTables { get; set; } = new();

        /// <summary>
        /// 标准曲线 缓存图片的地方
        /// </summary>
        public static Image Img { get; set; } = null;

        public static string Formula { get; set; } = null;

        /// <summary>
        /// 设置字号与字体颜色
        /// </summary>
        /// <returns></returns>
        static Font SetFontSizeColor()
        {
            BaseFont bfchinese = BaseFont.CreateFont("C:\\Windows\\Fonts\\msyh.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            var ChFont = new Font(bfchinese, 8, Font.NORMAL, iTextSharp.text.Color.BLACK);
            return ChFont;
        }

        /// <summary>
        /// 创建一行N列表格
        /// </summary>
        /// <param name="columnNameList">列的元素</param>
        /// <param name="fontSize">字号大小</param>
        /// <returns></returns>
        static PdfPTable CreateOneRowTableForTiltle(List<string> columnNameList)
        {
            // 定义表格对象,参数是该表格的列数
            var table = new PdfPTable(columnNameList.Count)
            {
                // 实现自动换页
                SplitLate = false,
                SplitRows = true
            };
            try
            {
                // 获取字号
                BaseFont bfchinese = BaseFont.CreateFont("C:\\Windows\\Fonts\\msyh.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                var font = new Font(bfchinese, 10, Font.NORMAL, iTextSharp.text.Color.BLACK);

                // 定义单元格对象
                PdfPCell cell;

                int rowCount = columnNameList.Count;
                for (int i = 0; i < rowCount; i++)
                {
                    if (columnNameList[i] == null) { columnNameList[i] = string.Empty; }
                    if (columnNameList[i] != null)
                    {
                        // 将内容绑定到单元格中
                        cell = new PdfPCell(new Phrase(columnNameList[i], font))
                        {
                            BorderWidthLeft = 0,
                            BorderWidthRight = 0,
                            BorderWidthTop = 0,
                            BorderColorLeft = iTextSharp.text.Color.WHITE,
                            BorderColorRight = iTextSharp.text.Color.WHITE,
                            BorderColorTop = iTextSharp.text.Color.WHITE,
                            HorizontalAlignment = 0,   // 居中
                            PaddingBottom = 5
                        };
                        table.AddCell(cell);

                        var cellBlankRow = new PdfPCell(new Phrase(" "))
                        {
                            FixedHeight = 5,
                            BorderWidthLeft = 0,
                            BorderWidthRight = 0,
                            BorderWidthTop = 0,
                            BorderWidthBottom = 0,
                            BorderColorLeft = iTextSharp.text.Color.WHITE,
                            BorderColorRight = iTextSharp.text.Color.WHITE,
                            BorderColorTop = iTextSharp.text.Color.WHITE
                        };
                        table.AddCell(cellBlankRow);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.GetSingleObj().WriteLog(ex);
            }
            return table;
        }

        /// <summary>
        /// 创建一行N列表格
        /// </summary>
        /// <param name="columnNameList">列的元素</param>
        /// <param name="fontSize">字号大小</param>
        /// <returns></returns>
        static PdfPTable CreateOneRowTable(List<string> columnNameList, bool hasLine = false)
        {
            // 定义表格对象,参数是该表格的列数
            var table = new PdfPTable(columnNameList.Count)
            {
                // 实现自动换页
                SplitLate = false,
                SplitRows = true
            };

            try
            {
                // 获取字号
                Font font = SetFontSizeColor();
                // 定义单元格对象
                PdfPCell cell;

                int rowCount = columnNameList.Count;
                for (int i = 0; i < rowCount; i++)
                {
                    if (columnNameList[i] == null) { columnNameList[i] = string.Empty; }
                    if (columnNameList[i] != null)
                    {
                        // 将内容绑定到单元格中
                        cell = new PdfPCell(new Phrase(columnNameList[i], font))
                        {
                            HorizontalAlignment = Element.ALIGN_CENTER, // 居中
                            VerticalAlignment = Element.ALIGN_MIDDLE // 垂直居中
                        };

                        if (hasLine == false)
                        {
                            cell.Border = Rectangle.NO_BORDER; // 去掉边框
                        }
                        table.AddCell(cell);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.GetSingleObj().WriteLog(ex);
            }
            return table;
        }


        /// <summary>
        /// 创建一行N列表格
        /// </summary>
        /// <param name="columnNameList">列的元素</param>
        /// <param name="fontSize">字号大小</param>
        /// <returns></returns>
        static PdfPTable CreateOneRowTableOneLeft(List<string> columnNameList, bool hasLine = false)
        {
            // 定义表格对象,参数是该表格的列数
            var table = new PdfPTable(columnNameList.Count)
            {
                // 实现自动换页
                SplitLate = false,
                SplitRows = true
            };

            try
            {
                // 获取字号
                Font font = SetFontSizeColor();
                // 定义单元格对象
                PdfPCell cell;

                int rowCount = columnNameList.Count;
                for (int i = 0; i < rowCount; i++)
                {
                    if (columnNameList[i] == null) { columnNameList[i] = string.Empty; }
                    if (columnNameList[i] != null)
                    {
                        if (rowCount == 1)
                        {
                            // 将内容绑定到单元格中
                            cell = new PdfPCell(new Phrase(columnNameList[i], font))
                            {
                                HorizontalAlignment = Element.ALIGN_LEFT, // 居中
                                VerticalAlignment = Element.ALIGN_MIDDLE // 垂直居中
                            };
                        }
                        else
                        {
                            // 将内容绑定到单元格中
                            cell = new PdfPCell(new Phrase(columnNameList[i], font))
                            {
                                HorizontalAlignment = Element.ALIGN_CENTER, // 居中
                                VerticalAlignment = Element.ALIGN_MIDDLE // 垂直居中
                            };
                        }

                        if (hasLine == false)
                        {
                            cell.Border = Rectangle.NO_BORDER; // 去掉边框
                        }
                        table.AddCell(cell);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.GetSingleObj().WriteLog(ex);
            }
            return table;
        }

        /// <summary>
        /// 创建一行N列表格
        /// </summary>
        /// <param name="columnNameList">列的元素</param>
        /// <param name="fontSize">字号大小</param>
        /// <returns></returns>
        static PdfPTable CreateCellHasImg(List<string> columnNameList, bool hasLine = false)
        {
            // 定义表格对象,参数是该表格的列数
            var table = new PdfPTable(columnNameList.Count)
            {
                // 实现自动换页
                SplitLate = false,
                SplitRows = true
            };
            try
            {
                // 获取字号
                Font font = SetFontSizeColor();
                // 定义单元格对象
                PdfPCell cell;

                int rowCount = columnNameList.Count;
                for (int i = 0; i < rowCount; i++)
                {
                    if (columnNameList[i] == null) { columnNameList[i] = string.Empty; }
                    if (columnNameList[i] != null)
                    {
                        if (columnNameList[i].Contains("ResultImag"))
                        {
                            string s = columnNameList[i].Substring(columnNameList[i].Length - 1);
                            if (!string.IsNullOrEmpty(s) && int.TryParse(s, out int ispass))
                            {
                                ImageSource imageSource;
                                if (ispass == 0)
                                {
                                    imageSource = (ImageSource)new ImageSourceConverter().ConvertFromString("pack://application:,,,/YouMin_MicroplateReader;component/Images/UnPass.png");
                                }
                                else
                                {
                                    imageSource = (ImageSource)new ImageSourceConverter().ConvertFromString("pack://application:,,,/YouMin_MicroplateReader;component/Images/Pass.png");
                                }
                                // 将 ImageSource 转换为 BitmapSource

                                if (imageSource is System.Windows.Media.Imaging.BitmapSource bitmapSource && bitmapSource != null)
                                {
                                    using var memoryStream = new MemoryStream(); // 创建一个字节数组并将 BitmapSource 保存到该字节数组中                                  
                                    var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();  // 使用 PngBitmapEncoder 将 BitmapSource 保存为 PNG 格式
                                    encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bitmapSource));
                                    encoder.Save(memoryStream);

                                    // 创建 iTextSharp 的图像
                                    byte[] byteArray = memoryStream.ToArray();
                                    var iTextImage = Image.GetInstance(byteArray);

                                    // 创建单元格并添加图像
                                    cell = new PdfPCell(iTextImage, true)
                                    {
                                        FixedHeight = 5,
                                        HorizontalAlignment = Element.ALIGN_CENTER, // 居中
                                        VerticalAlignment = Element.ALIGN_MIDDLE // 垂直居中
                                    };
                                    table.AddCell(cell);
                                }
                            }
                        }
                        else
                        {
                            // 将内容绑定到单元格中
                            cell = new PdfPCell(new Phrase(columnNameList[i], font))
                            {
                                HorizontalAlignment = Element.ALIGN_CENTER, // 居中
                                VerticalAlignment = Element.ALIGN_MIDDLE // 垂直居中
                            };

                            if (hasLine == false)
                            {
                                cell.Border = Rectangle.NO_BORDER; // 去掉边框
                            }
                            table.AddCell(cell);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.GetSingleObj().WriteLog(ex);
            }

            return table;
        }

        /// <summary>
        /// 用于添加行 并有一个空白行进行分隔
        /// </summary>
        /// <param name="tileTable"></param>
        /// <param name="linebreak"></param>
        /// <param name="linebreakColcount"></param>
        /// <returns></returns>
        static PdfPTable CreatePrintTable(PdfModels tileTable, bool linebreak = false, int linebreakColcount = 3, bool hasLine = false)
        {
            //创建第一个表格
            var title = new List<string>
            {
                tileTable.TableTile
            };

            var tableMain1 = CreateOneRowTableForTiltle(title);//创建标题

            //创建行
            var tableMainrows = new List<PdfPTable>
            {
                tableMain1//把表头添加上去
            };
            try
            {
                ///添加行数据
                if (linebreak == false)
                {
                    if (tileTable.Rows?.Count > 0)
                    {
                        foreach (var item in tileTable.Rows)
                        {
                            var rowcols = new List<string>();
                            if (!string.IsNullOrEmpty(item.Key))
                            {
                                rowcols.Add(item.Key);
                            }
                            rowcols.AddRange(item.Value);
                            tableMainrows.Add(CreateOneRowTable(rowcols, hasLine));
                        }
                    }
                }
                else//列过多换行
                {
                    if (tileTable.Rows.Count > 0)
                    {
                        var cspcount = Math.Ceiling((double)tileTable.Rows[0].Value.Count / linebreakColcount);
                        //分次数取行
                        for (int i = 0; i < cspcount; i++)
                        {
                            var Skipcount = i * linebreakColcount;
                            foreach (var item in tileTable.Rows)
                            {
                                var rowcols = new List<string>();
                                if (!string.IsNullOrEmpty(item.Key))
                                {
                                    rowcols.Add(item.Key);
                                }
                                rowcols.AddRange(item.Value.Skip(Skipcount).Take(linebreakColcount));
                                tableMainrows.Add(CreateOneRowTable(rowcols, hasLine));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.GetSingleObj().WriteLog(ex);
            }

            var printtable = MergeMultTable(tableMainrows);
            return printtable;
        }

        /// <summary>
        /// 用于添加行 并有一个空白行进行分隔
        /// </summary>
        /// <param name="tileTable"></param>
        /// <param name="linebreak"></param>
        /// <param name="linebreakColcount"></param>
        /// <returns></returns>
        static PdfPTable CreatePrintTableOneLeft(PdfModels tileTable, bool linebreak = false, int linebreakColcount = 3, bool hasLine = false)
        {
            var title = new List<string> { tileTable.TableTile };  //创建第一个表格
            var tableMain1 = CreateOneRowTableForTiltle(title);//创建标题

            //创建行
            var tableMainrows = new List<PdfPTable>
            {
                tableMain1//把表头添加上去
            };
            try
            {
                ///添加行数据
                if (linebreak == false)
                {
                    if (tileTable.Rows?.Count > 0)
                    {
                        foreach (var item in tileTable.Rows)
                        {
                            var rowcols = new List<string>();
                            if (!string.IsNullOrEmpty(item.Key))
                            {
                                rowcols.Add(item.Key);
                            }
                            rowcols.AddRange(item.Value);
                            tableMainrows.Add(CreateOneRowTableOneLeft(rowcols, hasLine));
                        }
                    }
                }
                else//列过多换行
                {
                    if (tileTable.Rows.Count > 0)
                    {
                        var cspcount = Math.Ceiling((double)tileTable.Rows[0].Value.Count / linebreakColcount);
                        //分次数取行
                        for (int i = 0; i < cspcount; i++)
                        {
                            var Skipcount = i * linebreakColcount;
                            foreach (var item in tileTable.Rows)
                            {
                                var rowcols = new List<string>();
                                if (!string.IsNullOrEmpty(item.Key))
                                {
                                    rowcols.Add(item.Key);
                                }
                                rowcols.AddRange(item.Value.Skip(Skipcount).Take(linebreakColcount));
                                tableMainrows.Add(CreateOneRowTableOneLeft(rowcols, hasLine));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.GetSingleObj().WriteLog(ex);
            }

            var printtable = MergeMultTable(tableMainrows);
            return printtable;
        }

        /// <summary>
        /// 用于添加行 并有一个空白行进行分隔
        /// </summary>
        /// <param name="tileTable"></param>
        /// <param name="linebreak"></param>
        /// <param name="linebreakColcount"></param>
        /// <returns></returns>
        static PdfPTable CreatePrintTableCellHasImg(PdfModels tileTable, bool linebreak = false, int linebreakColcount = 3, bool hasLine = false)
        {
            //创建第一个表格
            var title = new List<string>
            {
                tileTable.TableTile
            };

            var tableMain1 = CreateOneRowTableForTiltle(title);//创建标题

            //创建行
            var tableMainrows = new List<PdfPTable>
            {
                tableMain1//把表头添加上去
            };
            try
            {
                ///添加行数据
                if (linebreak == false)
                {
                    if (tileTable.Rows?.Count > 0)
                    {
                        foreach (var item in tileTable.Rows)
                        {
                            var rowcols = new List<string>();
                            if (!string.IsNullOrEmpty(item.Key))
                            {
                                rowcols.Add(item.Key);
                            }
                            rowcols.AddRange(item.Value);
                            tableMainrows.Add(CreateCellHasImg(rowcols, hasLine));
                        }
                    }
                }
                else//列过多换行
                {
                    if (tileTable.Rows.Count > 0)
                    {
                        var cspcount = Math.Ceiling((double)tileTable.Rows[0].Value.Count / linebreakColcount);
                        //分次数取行
                        for (int i = 0; i < cspcount; i++)
                        {
                            var Skipcount = i * linebreakColcount;
                            foreach (var item in tileTable.Rows)
                            {
                                var rowcols = new List<string>();
                                if (!string.IsNullOrEmpty(item.Key))
                                {
                                    rowcols.Add(item.Key);
                                }
                                rowcols.AddRange(item.Value.Skip(Skipcount).Take(linebreakColcount));
                                tableMainrows.Add(CreateCellHasImg(rowcols, hasLine));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.GetSingleObj().WriteLog(ex);
            }

            var printtable = MergeMultTable(tableMainrows);
            return printtable;
        }

        /// <summary>
        /// 用于添加图片 现在只有标准曲线
        /// </summary>
        /// <param name="tileTable"></param>
        /// <returns></returns>
        static PdfPTable CreatePrintImgTable(PdfModels tileTable, Image img)
        {
            try
            {
                var title1 = new List<string> { tileTable.TableTile }; //创建第一个表格                         
                var tableMain1 = CreateOneRowTableForTiltle(title1);  //创建标题

                List<PdfPTable> tableMainrows;
                if (!string.IsNullOrEmpty(Formula))
                {
                    var FList = Formula.Split('\t');
                    if (FList.Length == 2)
                    {
                        Formula = FList[0] + "\u00A0   " + FList[1];
                    }
                    var title2 = new List<string> { Formula };//创建第一个表格          
                    var tableMain2 = CreateOneRowTable(title2);  //创建标题 
                    tableMainrows = new List<PdfPTable>
                {
                    tableMain1,
                    tableMain2
                };//创建行把表头添加上去
                }
                else
                {
                    tableMainrows = new List<PdfPTable> { tableMain1 };//创建行把表头添加上去
                }
                var printtable = MergeMultTable(tableMainrows);
                var cell = new PdfPCell(img, true)
                {
                    Border = Rectangle.NO_BORDER, // 去掉边框
                    HorizontalAlignment = Element.ALIGN_CENTER, // 居中
                    VerticalAlignment = Element.ALIGN_MIDDLE // 垂直居中
                };
                printtable.AddCell(cell);
                return printtable;
            }
            catch (Exception ex)
            {
                LogHelper.GetSingleObj().WriteLog(ex);
                return null;
            }
        }

        public static bool WritePdf(string FileName)
        {
            bool result = false;
            try
            {
                // 创建PDF文件
                using (var pdfFs = new FileStream(FileName, FileMode.Create))
                {
                    var rectangle = new Rectangle(PageSize.A4);//页面大小(画出矩形轮廓)                                                              
                    var doc = new Document(rectangle); // 获取实例
                    doc.SetMargins(5, 5, 5, 5);//页边空白                    
                    PdfWriter.GetInstance(doc, pdfFs);

                    // 打开pdf
                    doc.Open();
                    if (Table1 != null)
                    {
                        var printtable1 = CreatePrintTable(Table1);
                        doc.Add(printtable1);//添加到打印对象
                        doc.Add(GetBlankRow());
                    }
                    if (Table2 != null)
                    {
                        var printtable2 = CreatePrintTable(Table2);
                        doc.Add(printtable2);//添加到打印对象
                        doc.Add(GetBlankRow());
                    }
                    if (TileTables?.Count > 0)
                    {
                        foreach (var item in TileTables)
                        {
                            var tmpprinttable = CreatePrintTable(item, true, item.Count, item.HasLine);
                            doc.Add(tmpprinttable);//添加到打印对象
                            doc.Add(GetBlankRow());
                        }
                    }
                    if (Img != null)
                    {
                        var imgTitle = new PdfModels
                        {
                            TableTile = Util.FindKey("StandardCurve")
                        };
                        var imagtable1 = CreatePrintImgTable(imgTitle, Img);
                        if (imagtable1 != null)
                        {
                            doc.Add(imagtable1);
                        }
                    }
                    // 关闭
                    doc.Close();
                }
                result = true;
            }
            catch (Exception ex)
            {
                LogHelper.GetSingleObj().WriteLog(ex);
            }
            return result;
        }

        public static bool WritePdfOneLeft(string FileName)
        {
            bool result = false;
            try
            {
                // 创建PDF文件
                using (var pdfFs = new FileStream(FileName, FileMode.Create))
                {
                    var rectangle = new Rectangle(PageSize.A4);//页面大小(画出矩形轮廓)

                    // 获取实例
                    var doc = new Document(rectangle);
                    doc.SetMargins(10, 10, 10, 10);//页边空白                    
                    PdfWriter.GetInstance(doc, pdfFs);

                    // 打开pdf
                    doc.Open();
                    if (Table1 != null)
                    {
                        var printtable1 = CreatePrintTableOneLeft(Table1);
                        doc.Add(printtable1);//添加到打印对象
                        doc.Add(GetBlankRow());
                    }
                    if (Table2 != null)
                    {
                        var printtable2 = CreatePrintTableOneLeft(Table2);
                        doc.Add(printtable2);//添加到打印对象
                        doc.Add(GetBlankRow());
                    }
                    if (TileTables?.Count > 0)
                    {
                        foreach (var item in TileTables)
                        {
                            var tmpprinttable = CreatePrintTableOneLeft(item, true, item.Count, item.HasLine);
                            doc.Add(tmpprinttable);//添加到打印对象
                            doc.Add(GetBlankRow());
                        }
                    }
                    if (Img != null)
                    {
                        var imgTitle = new PdfModels
                        {
                            TableTile = Util.FindKey("StandardCurve")
                        };
                        var imagtable1 = CreatePrintImgTable(imgTitle, Img);
                        if (imagtable1 != null)
                        {
                            doc.Add(imagtable1);
                        }
                    }
                    // 关闭
                    doc.Close();
                }
                result = true;
            }
            catch (Exception ex)
            {
                LogHelper.GetSingleObj().WriteLog(ex);
            }
            return result;
        }

        public static bool WritePdfCellHasImg(string FileName)
        {
            bool result = false;
            try
            {
                // 创建PDF文件
                using (var pdfFs = new FileStream(FileName, FileMode.Create))
                {
                    var rectangle = new Rectangle(PageSize.A4);//页面大小(画出矩形轮廓)
                                                               // 获取实例
                    var doc = new Document(rectangle);
                    doc.SetMargins(10, 10, 10, 10);//页边空白                    
                    PdfWriter.GetInstance(doc, pdfFs);

                    // 打开pdf
                    doc.Open();
                    if (Table1 != null)
                    {
                        var printtable1 = CreatePrintTable(Table1);
                        doc.Add(printtable1);//添加到打印对象
                        doc.Add(GetBlankRow());
                    }
                    if (Table2 != null)
                    {
                        var printtable2 = CreatePrintTable(Table2);
                        doc.Add(printtable2);//添加到打印对象
                        doc.Add(GetBlankRow());
                    }
                    if (TileTables?.Count > 0)
                    {
                        foreach (var item in TileTables)
                        {
                            var tmpprinttable = CreatePrintTableCellHasImg(item, true, item.Count, item.HasLine);
                            doc.Add(tmpprinttable);//添加到打印对象
                            doc.Add(GetBlankRow());
                        }
                    }
                    if (Img != null)
                    {
                        var imgTitle = new PdfModels
                        {
                            TableTile = Util.FindKey("StandardCurve")
                        };
                        var imagtable1 = CreatePrintImgTable(imgTitle, Img);
                        if (imagtable1 != null)
                        {
                            doc.Add(imagtable1);
                        }
                    }
                    // 关闭
                    doc.Close();
                }
                result = true;
            }
            catch (Exception ex)
            {
                LogHelper.GetSingleObj().WriteLog(ex);
            }
            return result;
        }

        public static void WritePdfForOne(string path)
        {
            try
            {
                using var pdfFs = new FileStream(path, FileMode.Create);// 创建PDF文件               
                var doc = new Document(); // 获取实例
                PdfWriter.GetInstance(doc, pdfFs);

                // 打开pdf
                doc.Open();
                if (TileTables?.Count > 0)
                {
                    foreach (var item in TileTables)
                    {
                        var tmpprinttable = CreatePrintTable(item, true, 8);
                        doc.Add(tmpprinttable);//添加到打印对象
                    }
                }
                // 关闭
                doc.Close();
            }
            catch (Exception ex)
            {
                LogHelper.GetSingleObj().WriteLog(ex);
            }
        }

        /// <summary>
        /// 生成默认空白行
        /// </summary>
        /// <returns></returns>
        public static Paragraph GetBlankRow()
        {
            var blankRow = new Paragraph(" ", SetFontSizeColor());//设置字号大小和样式
            blankRow.SetAlignment(Element.ALIGN_CENTER.ToString());
            blankRow.SetLeading(10, 0);//行间距
            return blankRow;
        }

        /// <summary>
        /// 合并两个表格
        /// </summary>
        /// <param name="table1"></param>
        /// <param name="table2"></param>
        /// <returns></returns>
        public static PdfPTable MergeTwoTable(PdfPTable table1, PdfPTable table2)
        {
            var table = new PdfPTable(1) // 定义表格对象,参数代表是该表格一共由多少列
            {
                // 实现自动换页
                SplitLate = false,
                SplitRows = true
            };
            try
            {
                PdfPCell cell;// 定义单元格对象
                // 这个函数写死是合并两个单元格
                int rowCount = 2;
                for (int i = 0; i < rowCount; i++)
                {
                    switch (i)
                    {
                        case 0:
                            // 单元格中添加表格1
                            cell = new PdfPCell(table1)
                            {
                                // 居中
                                Padding = 0
                            };
                            // 将单元格添加到表格中
                            table.AddCell(cell);
                            break;
                        case 1:
                            cell = new PdfPCell(table2)
                            {
                                Padding = 0
                            };
                            table.AddCell(cell);
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.GetSingleObj().WriteLog(ex);
            }
            // 最后将合并好的表格返回
            return table;
        }

        /// <summary>
        /// 合并多个表格
        /// </summary>
        /// <param name="pdfList"></param>
        /// <returns></returns>
        public static PdfPTable MergeMultTable(List<PdfPTable> pdfList)
        {
            var table = new PdfPTable(1)
            {
                SplitLate = false,
                SplitRows = true
            };
            try
            {
                PdfPCell cell;
                // 将表格绑定到单元格中,然后将单元格插入汇总表格
                if (pdfList != null && pdfList.Any())
                {
                    foreach (PdfPTable pdf in pdfList)
                    {
                        cell = new PdfPCell(pdf)
                        {
                            Border = Rectangle.NO_BORDER, // 去掉边框
                            HorizontalAlignment = Element.ALIGN_CENTER, // 居中
                            VerticalAlignment = Element.ALIGN_MIDDLE, // 垂直居中
                            Padding = 0
                        };
                        table.AddCell(cell);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.GetSingleObj().WriteLog(ex);
            }
            return table;
        }
    }

PdfModels.cs


    public partial class PdfModels : ObservableObject
    {
        public PdfModels() { Rows = new List<KeyValuePair<string, List<string>>>(); }

        /// <summary>
        /// 表格标题
        /// </summary>
        public string TableTile { get; set; } = string.Empty;

        public int Count { get; set; } = 12;

        public bool HasLine { get; set; } = false;

        public List<KeyValuePair<string, List<string>>> Rows { get; set; }
    }

 方法里的实现

using var folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
                if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    var selectedPath = folderBrowserDialog.SelectedPath;

 //注册编码提供程序 
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

  PdfTableHelper.TileTables = new List<PdfModels>();
                    PdfTableHelper.Formula = null;
                    PdfTableHelper.Img = null;

 string FileName = Path.Combine(selectedPath, $"{xxxx}.pdf");
                    var fi = new FileInfo(FileName);
                    if (fi.Directory != null && !fi.Directory.Exists)
                    {
                        fi.Directory.Create();
                    }
                    if (File.Exists(FileName))
                    {
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            if (new IsDeleteWin("HasFile").ShowDialog() == false)
                            {
                                return;
                            }
                        });
                    }

 PdfTableHelper.Table1 = new PdfModels();
                        PdfTableHelper.Table2 = new PdfModels();
                        PdfTableHelper.TileTables = new List<PdfModels>();

                        //构造第一个表格
                        PdfTableHelper.Table1.TableTile = Util.FindKey("BaseInformation");
                        PdfTableHelper.Table1.Rows = new List<KeyValuePair<string, List<string>>>()
                            {
                                new KeyValuePair<string, List<string>>("111",new List<string>(){111}),
                new KeyValuePair<string, List<string>>("222",new List<string>(){ 222 })
                            };

                        //构造第二个表格
                        PdfTableHelper.Table2.TableTile = Util.FindKey("ProgramParameters");
                        PdfTableHelper.Table2.Rows = new List<KeyValuePair<string, List<string>>>();
                                PdfTableHelper.Table2.Rows.Add(new KeyValuePair<string, List<string>>("333"), new List<string>() { "333" }));

model = new PdfModels()
                                    {
                                        TableTile = xxx
                                    };
                                    model.Rows.Add(new KeyValuePair<string, List<string>>("444"),
                                        new List<string>() { "1", "2", "3", "4", "5", "6" }));
                                    foreach (var Temp in TempList)
                                    {
                                        model.Rows.Add(new KeyValuePair<string,
                                            List<string>>(Temp.Hole, new List<string>()
                                            {
                                                Temp.111,
                                                Temp.222,
                                                Temp.333,
                                                Temp.444,
                                                Temp.555,
                                                Temp.666
                                            }));
                                    }
                                    PdfTableHelper.TileTables.Add(model);
                        PdfTableHelper.WritePdf(FileName);

}


网站公告

今日签到

点亮在社区的每一天
去签到