C# 设置PDF跨页表格重复显示表头行

2025-10-19 05:30:44

1、在VS程序中添加引用Spire.PDF.dll。

通过Nuget搜索下载安装。

在“解决方案资源管理器”中,鼠标右键点击“添加引用”—“ 管理NuGet包”

C# 设置PDF跨页表格重复显示表头行

C# 设置PDF跨页表格重复显示表头行

C# 设置PDF跨页表格重复显示表头行

C# 设置PDF跨页表格重复显示表头行

2、完成安装。引用结果:

C# 设置PDF跨页表格重复显示表头行

3、C#:

using Spire.Pdf;

using Spire.Pdf.Graphics;

using Spire.Pdf.Grid;

using System.Drawing;

namespace RepeatTableHeaderRow

{

    class Program

    {

        static void Main(string[] args)

        {

            //新建一个PDF文档

            PdfDocument pdf = new PdfDocument();

            //添加一页

            PdfPageBase page = pdf.Pages.Add();

            //创建PdfGrid类的对象

            PdfGrid grid = new PdfGrid();

            //设置单元格填充

            grid.Style.CellPadding = new PdfPaddings(1, 1, 1, 1);

            //添加表格列数

            grid.Columns.Add(3);

            //添加表头行及表格数据

            PdfGridRow[] pdfGridRows = grid.Headers.Add(1);            

            for (int i = 0; i < pdfGridRows.Length; i++)

            {

                pdfGridRows[i].Style.Font = new PdfTrueTypeFont(new Font("Arial", 11f, FontStyle.Regular), true);//指定字体

                pdfGridRows[i].Cells[0].Value = "NAME";

                pdfGridRows[i].Cells[1].Value = "SUBJECT";

                pdfGridRows[i].Cells[2].Value = "SCORES";

                pdfGridRows[i].Style.TextBrush = PdfBrushes.Red;

                /*pdfGridRows[i].Style.Font = new PdfCjkStandardFont(PdfCjkFontFamily.HanyangSystemsGothicMedium,12f,PdfFontStyle.Regular);//绘制中日韩字体的方法

                pdfGridRows[i].Cells[0].Value = "이 름";

                pdfGridRows[i].Cells[1].Value = "科 目";

                pdfGridRows[i].Cells[2].Value = "ほしとり";

                pdfGridRows[i].Style.TextBrush = PdfBrushes.Blue;

                */

            }

            //设置重复表头(表格跨页时)

            grid.RepeatHeader = true;

            //添加数据到表格

            for (int i = 0; i < 60; i++)

            {

                PdfGridRow row = grid.Rows.Add();              

                for (int j = 0; j < grid.Columns.Count; j++)

                {

                    row.Cells[j].Value = "(Row " + i + ", column " + j + ")";

                }

            }

            //在PDF页面绘制表格

            grid.Draw(page, new PointF(0, 20));         

            //保存文档

            pdf.SaveToFile("Result.pdf");

            System.Diagnostics.Process.Start("Result.pdf");

        }

    }

}

4、执行程序后,在VS的程序项目文件夹下可查看生成的PDF文档,如

C:\Users\Administrator\Documents\Visual Studio 2017\Projects\DrawTable_PDF\RepeatTableHeaderRow\bin\Debug\Result.pdf

文件路径也可以定义为其他路径。跨页表头效果:

C# 设置PDF跨页表格重复显示表头行

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢