在建立表格時,如果表格內容出現跨頁顯示的時候,預設情況下該表格的表頭不會在下一頁顯示,在閱讀體驗上不是很好。下面分享一個方法如何在表格跨頁時顯示錶格的表頭內容,在C#中只需要簡單使用方法grid.RepeatHeader = true;即可。具體參考如下方法步驟。另附VB.NET程式碼,有需可供參考。
1.在VS程式中新增引用Spire.PDF.dll
方法1:通過Nuget搜尋下載安裝。
在“解決方案資源管理器”中,滑鼠右鍵點選“新增引用”—“ 管理NuGet包”
完成安裝。引用結果:
方法2:下載Free Spire.PDF for .NET包到本地。解壓。在VS中的“解決方案資源管理器”中,滑鼠右鍵點選“新增引用”-將解壓包Bin資料夾下的dll新增引用至vs。
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");
}
}
}
執行程式後,在VS的程式專案資料夾下可檢視生成的PDF文件,如
C:\Users\Administrator\Documents\Visual Studio 2017\Projects\DrawTable_PDF\RepeatTableHeaderRow\bin\Debug\Result.pdf
檔案路徑也可以定義為其他路徑。
跨頁表頭效果:
—End—