USING IRONPDF How to Add Header and Footer in PDF Using iTextSharp and IronPDF in C# with Example Curtis Chau 更新:2025年12月4日 下載 IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 開始免費試用 法學碩士副本 法學碩士副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在 Grok 中打開 向 Grok 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 在PDF文件中新增頁首和頁尾 在 PDF 文件中新增頁首和頁尾對於建立專業的報告、發票和商業文件至關重要。 雖然許多開發人員使用PdfPageEventHelper和OnEndPage方法來尋找 iTextSharp 解決方案,但現代 .NET 程式庫提供了更簡單的方法來實現相同的結果。 本教學課程示範如何使用 C# 在 PDF 中加入範例頁首和頁腳,並將傳統的 iText 7 方法與 IronPDF 的簡化方法進行比較。 最後,您將了解兩種實作方式——從建立新文件到產生最終 PDF 文件——並可以選擇最適合您的專案要求的方法。 如何使用 iTextSharp 和 IronPDF 在 C# 中為 PDF 新增頁首和頁尾(附圖 1 - IronPDF) 為什麼PDF文件生成中的頁首和頁尾很重要? 頁首和頁尾在專業PDF文件中發揮著至關重要的作用。 它們透過圖像標誌提供一致的品牌形象,透過頁碼實現頁面導航,顯示日期和文件標題等重要元數據,並透過時間戳記和版本資訊建立文件真實性。 在企業環境中,頁首和頁尾通常具有法律意義。 財務報告需要時間戳以作審計追蹤。 合約需要頁碼以確保完整性。 內部文件可能需要在每一頁上註明保密聲明。 要以程式設計方式滿足這些要求,需要一個能夠可靠地處理頁面層級內容注入的 PDF 庫。 如何使用 iTextSharp 和 IronPDF 在 C# 中為 PDF 新增頁首和頁尾(附圖 2 - 功能) 在 C# 中加入頁首和頁尾的最簡單方法是什麼? IronPDF為 .NET 應用程式中的 PDF 文件新增頁首和頁尾提供了最直接的方法。 結合使用ChromePdfRenderer類別和TextHeaderFooter或HtmlHeaderFooter ,開發人員可以用最少的程式碼產生頁首和頁尾-無需建立單獨的儲存格或手動管理contentbyte物件。 如何使用 iTextSharp 和 IronPDF 在 C# 中為 PDF 新增頁首和頁尾(附圖 3) - 如何在 PDF 中新增頁首和頁尾 - IronPDF 在較早的 iTextSharp 模式中,開發人員經常會建立諸如private static void AddContent()之類的輔助方法,或類似名稱的例程,如private static void addcontent ,來手動注入頁首和頁尾邏輯。 IronPDF 完全消除了此類樣板程式碼的需求。 以下是一個完整的範例,示範如何為 PDF 文件添加頁首和頁尾: using IronPdf; // Initialize the PDF renderer var renderer = new ChromePdfRenderer(); // Configure the text header with header text renderer.RenderingOptions.TextHeader = new TextHeaderFooter { CenterText = "Quarterly Sales Report", DrawDividerLine = true, FontSize = 14 }; // Configure the text footer with page number renderer.RenderingOptions.TextFooter = new TextHeaderFooter { LeftText = "{date}", RightText = "Page {page} of {total-pages}", DrawDividerLine = true, FontSize = 10 }; // Set margins to accommodate header and footer renderer.RenderingOptions.MarginTop = 25; renderer.RenderingOptions.MarginBottom = 25; // Generate PDF from HTML content var pdf = renderer.RenderHtmlAsPdf("<h1>Sales Data</h1><p>Content goes here...</p>"); pdf.SaveAs("report-with-headers.pdf"); using IronPdf; // Initialize the PDF renderer var renderer = new ChromePdfRenderer(); // Configure the text header with header text renderer.RenderingOptions.TextHeader = new TextHeaderFooter { CenterText = "Quarterly Sales Report", DrawDividerLine = true, FontSize = 14 }; // Configure the text footer with page number renderer.RenderingOptions.TextFooter = new TextHeaderFooter { LeftText = "{date}", RightText = "Page {page} of {total-pages}", DrawDividerLine = true, FontSize = 10 }; // Set margins to accommodate header and footer renderer.RenderingOptions.MarginTop = 25; renderer.RenderingOptions.MarginBottom = 25; // Generate PDF from HTML content var pdf = renderer.RenderHtmlAsPdf("<h1>Sales Data</h1><p>Content goes here...</p>"); pdf.SaveAs("report-with-headers.pdf"); Imports IronPdf ' Initialize the PDF renderer Dim renderer As New ChromePdfRenderer() ' Configure the text header with header text renderer.RenderingOptions.TextHeader = New TextHeaderFooter With { .CenterText = "Quarterly Sales Report", .DrawDividerLine = True, .FontSize = 14 } ' Configure the text footer with page number renderer.RenderingOptions.TextFooter = New TextHeaderFooter With { .LeftText = "{date}", .RightText = "Page {page} of {total-pages}", .DrawDividerLine = True, .FontSize = 10 } ' Set margins to accommodate header and footer renderer.RenderingOptions.MarginTop = 25 renderer.RenderingOptions.MarginBottom = 25 ' Generate PDF from HTML content Dim pdf = renderer.RenderHtmlAsPdf("<h1>Sales Data</h1><p>Content goes here...</p>") pdf.SaveAs("report-with-headers.pdf") $vbLabelText $csharpLabel 上面的源代碼演示了幾個關鍵概念。 TextHeaderFooter TextHeaderFooter提供了用於將文字定位在頁首/頁尾區域的左側、中間或右側的屬性。 DrawDividerLine屬性可在頁首/頁尾和文件正文內容之間新增一條專業的分隔線。 像{page} 、 {total-pages}和{date}這樣的可合併欄位在 PDF 產生過程中會自動填入動態值。 輸出 如何使用 iTextSharp 和 IronPDF 在 C# 中新增 PDF 的頁首和頁尾(附圖 4 - PDF 輸出) IronPDF 會自動處理邊距計算,確保頁首和頁尾不會與文件內容重疊。 TextHeaderFooter 類別支援 IronSoftware.Drawing 中的字型類型。 FontTypes 枚舉可讓您在不依賴外部資源的情況下控製排版。 如何使用 iTextSharp 和 IronPDF 在 C# 中為 PDF 新增頁首和頁尾(附圖 5 - 跨平台相容性) 請注意,整個實作都包含在一個程式碼區塊中,屬性賦值清晰易讀。 無需建立單獨的類別檔案、計算像素位置或管理畫布物件。 該程式庫抽象化了這些複雜性,使開發人員能夠專注於內容,而不是使用 iTextSharp 風格的模式來產生 PDF 的機制。 如何建立HTML樣式的頁首和頁尾? 對於更複雜的設計,IronPDF 的HtmlHeaderFooter 類別支援完整的 HTML 和 CSS 樣式。 當標題需要包含圖像徽標、複雜佈局或品牌特定的樣式時,這種方法尤其有價值——無需手動創建PdfPCell物件或使用新的Phrase建構函數。 using IronPdf; using System; var renderer = new ChromePdfRenderer(); // Create an HTML header with logo and styling renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter { HtmlFragment = @" <div style='width: 100%; font-family: Arial, sans-serif;'> <img src='logo.png' style='height: 30px; float: left;' /> <span style='float: right; font-size: 12px; color: #666;'> Confidential Document </span> </div>", MaxHeight = 25, DrawDividerLine = true, BaseUrl = new Uri(@"C:\assets\").AbsoluteUri }; // Create an HTML footer with page numbering renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter { HtmlFragment = @" <div style='text-align: center; font-size: 10px; color: #999;'> <span>Generated on {date} at {time}</span> <br/> <span>Page {page} of {total-pages}</span> </div>", MaxHeight = 20 }; renderer.RenderingOptions.MarginTop = 30; renderer.RenderingOptions.MarginBottom = 25; var pdf = renderer.RenderHtmlAsPdf("<h1>Project Proposal</h1><p>Document content...</p>"); pdf.SaveAs("styled-document.pdf"); using IronPdf; using System; var renderer = new ChromePdfRenderer(); // Create an HTML header with logo and styling renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter { HtmlFragment = @" <div style='width: 100%; font-family: Arial, sans-serif;'> <img src='logo.png' style='height: 30px; float: left;' /> <span style='float: right; font-size: 12px; color: #666;'> Confidential Document </span> </div>", MaxHeight = 25, DrawDividerLine = true, BaseUrl = new Uri(@"C:\assets\").AbsoluteUri }; // Create an HTML footer with page numbering renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter { HtmlFragment = @" <div style='text-align: center; font-size: 10px; color: #999;'> <span>Generated on {date} at {time}</span> <br/> <span>Page {page} of {total-pages}</span> </div>", MaxHeight = 20 }; renderer.RenderingOptions.MarginTop = 30; renderer.RenderingOptions.MarginBottom = 25; var pdf = renderer.RenderHtmlAsPdf("<h1>Project Proposal</h1><p>Document content...</p>"); pdf.SaveAs("styled-document.pdf"); Imports IronPdf Imports System Dim renderer As New ChromePdfRenderer() ' Create an HTML header with logo and styling renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter With { .HtmlFragment = " <div style='width: 100%; font-family: Arial, sans-serif;'> <img src='logo.png' style='height: 30px; float: left;' /> <span style='float: right; font-size: 12px; color: #666;'> Confidential Document </span> </div>", .MaxHeight = 25, .DrawDividerLine = True, .BaseUrl = New Uri("C:\assets\").AbsoluteUri } ' Create an HTML footer with page numbering renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter With { .HtmlFragment = " <div style='text-align: center; font-size: 10px; color: #999;'> <span>Generated on {date} at {time}</span> <br/> <span>Page {page} of {total-pages}</span> </div>", .MaxHeight = 20 } renderer.RenderingOptions.MarginTop = 30 renderer.RenderingOptions.MarginBottom = 25 Dim pdf = renderer.RenderHtmlAsPdf("<h1>Project Proposal</h1><p>Document content...</p>") pdf.SaveAs("styled-document.pdf") $vbLabelText $csharpLabel 此範例程式碼展示如何將圖像與文字一起添加到 HTML 標頭中。 BaseUrl屬性用於確定解析字串 filename 中指定的相對圖像 URL 的根路徑,從而可以輕鬆包含公司徽標或其他圖形。 MaxHeight屬性可確保頁首不超過指定尺寸,進而維持文件版面的一致性。 可合併欄位( {page} 、 {total-pages} 、 {url} 、 { {date} 、 {time} 、 {html-title} 、 {pdf-title} )在 HTML 頁首和頁尾中的作用相同,無需額外程式碼即可提供動態內容插入。 有關實現各種頁眉樣式的全面指導,請參閱頁首和頁尾操作指南。 在建立品牌文件時,HTML 方法的優勢尤其突出。 行銷團隊可以提供開發人員直接整合的 HTML 模板,從而確保對已批准的設計進行像素級完美還原。 CSS 屬性(如font-family 、 color 、 background-color和border都能如預期運作,從而實現複雜的視覺效果,而這在其他函式庫中需要大量的底層程式碼才能實現。 如何為現有PDF文件新增頁首? 常見的需求是為已存在的 PDF 文件添加頁首和頁尾——無論這些文件是上傳的文檔、合併的文件,還是其他系統生成的 PDF 文件。 IronPDF 使用AddHtmlHeaders和AddHtmlFooters方法優雅地處理了這種情況。 using IronPdf; // Load an existing PDF document var pdf = PdfDocument.FromFile("customer-profile.pdf"); // Define the header to add with header description var header = new HtmlHeaderFooter { HtmlFragment = "<div style='text-align: center;'>REVISED COPY - {date}</div>", MaxHeight = 20 }; // Define the footer to add var footer = new HtmlHeaderFooter { HtmlFragment = "<div style='text-align: right;'>Page {page}</div>", MaxHeight = 15 }; // Apply headers and footers to all pages pdf.AddHtmlHeaders(header); pdf.AddHtmlFooters(footer); pdf.SaveAs("document-with-new-headers.pdf"); using IronPdf; // Load an existing PDF document var pdf = PdfDocument.FromFile("customer-profile.pdf"); // Define the header to add with header description var header = new HtmlHeaderFooter { HtmlFragment = "<div style='text-align: center;'>REVISED COPY - {date}</div>", MaxHeight = 20 }; // Define the footer to add var footer = new HtmlHeaderFooter { HtmlFragment = "<div style='text-align: right;'>Page {page}</div>", MaxHeight = 15 }; // Apply headers and footers to all pages pdf.AddHtmlHeaders(header); pdf.AddHtmlFooters(footer); pdf.SaveAs("document-with-new-headers.pdf"); Imports IronPdf ' Load an existing PDF document Dim pdf = PdfDocument.FromFile("customer-profile.pdf") ' Define the header to add with header description Dim header As New HtmlHeaderFooter With { .HtmlFragment = "<div style='text-align: center;'>REVISED COPY - {date}</div>", .MaxHeight = 20 } ' Define the footer to add Dim footer As New HtmlHeaderFooter With { .HtmlFragment = "<div style='text-align: right;'>Page {page}</div>", .MaxHeight = 15 } ' Apply headers and footers to all pages pdf.AddHtmlHeaders(header) pdf.AddHtmlFooters(footer) pdf.SaveAs("document-with-new-headers.pdf") $vbLabelText $csharpLabel PdfDocument類別表示已載入或已渲染的 PDF,並提供渲染後修改的方法。 渲染和修改的分離使得 PDF 文件能夠經過多個處理階段的工作流程成為可能。 AddHtmlHeaders方法會自動將標頭套用到每個頁面,但您也可以透過傳遞頁面索引集合來定位特定頁面。 輸入 如何使用 iTextSharp 和 IronPDF 在 C# 中新增 PDF 的頁首和頁尾(附圖 6 - 範例輸入) 輸出 如何使用 iTextSharp 和 IronPDF 在 C# 中為 PDF 新增頁首和頁尾(範例):圖 7 - 現有 PDF 頁首輸出 對於從各種來源(例如掃描文件、使用者上傳或第三方 API 回應)接收 PDF 文件的文件管理系統而言,此功能非常有價值。 IronPDF 在分發或存檔之前會對品牌識別或頁碼進行標準化。 iText 7 的設計理念是怎麼樣的? 熟悉 iText 7(iTextSharp 的繼任者)的開發人員都知道,新增頁首和頁尾需要實作事件處理程序。 此庫使用頁面事件系統,您只需建立一個類別文件即可回應文件生命週期事件,例如OnEndPage和OnCloseDocument 。 以下是使用 iText 7 和公用類別ITextEvents模式實作相同頁首/頁尾的範例: using iText.Kernel.Pdf; using iText.Layout; using iText.Layout.Element; using iText.Kernel.Events; using iText.Kernel.Geom; using iText.Layout.Properties; // Event handler class for headers and footers - similar to PdfPageEventHelper public class ITextEvents : IEventHandler { // Private string for header text private string _header; public string Header { get { return _header; } set { _header = value; } } public void HandleEvent(Event currentEvent) { PdfDocumentEvent docEvent = (PdfDocumentEvent)currentEvent; PdfDocument pdfDoc = docEvent.GetDocument(); PdfPage page = docEvent.GetPage(); Rectangle pageSize = page.GetPageSize(); // Create new PdfCanvas for the contentbyte object PdfCanvas pdfCanvas = new PdfCanvas( page.NewContentStreamBefore(), page.GetResources(), pdfDoc); Canvas canvas = new Canvas(pdfCanvas, pageSize); // Add header text canvas.ShowTextAligned( new Paragraph("Quarterly Sales Report"), pageSize.GetWidth() / 2, pageSize.GetTop() - 20, TextAlignment.CENTER); // Add footer with page number int pageNumber = pdfDoc.GetPageNumber(page); canvas.ShowTextAligned( new Paragraph($"Page {pageNumber}"), pageSize.GetWidth() / 2, pageSize.GetBottom() + 20, TextAlignment.CENTER); canvas.Close(); } } // Usage in main code - private void CreatePdf pattern public static void Main(string[] args) { PdfWriter writer = new PdfWriter("report.pdf"); PdfDocument pdfDoc = new PdfDocument(writer); Document document = new Document(pdfDoc); // Register the event handler for END_PAGE pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, new ITextEvents()); document.Add(new Paragraph("Sales Data")); document.Add(new Paragraph("Content goes here...")); document.Close(); } using iText.Kernel.Pdf; using iText.Layout; using iText.Layout.Element; using iText.Kernel.Events; using iText.Kernel.Geom; using iText.Layout.Properties; // Event handler class for headers and footers - similar to PdfPageEventHelper public class ITextEvents : IEventHandler { // Private string for header text private string _header; public string Header { get { return _header; } set { _header = value; } } public void HandleEvent(Event currentEvent) { PdfDocumentEvent docEvent = (PdfDocumentEvent)currentEvent; PdfDocument pdfDoc = docEvent.GetDocument(); PdfPage page = docEvent.GetPage(); Rectangle pageSize = page.GetPageSize(); // Create new PdfCanvas for the contentbyte object PdfCanvas pdfCanvas = new PdfCanvas( page.NewContentStreamBefore(), page.GetResources(), pdfDoc); Canvas canvas = new Canvas(pdfCanvas, pageSize); // Add header text canvas.ShowTextAligned( new Paragraph("Quarterly Sales Report"), pageSize.GetWidth() / 2, pageSize.GetTop() - 20, TextAlignment.CENTER); // Add footer with page number int pageNumber = pdfDoc.GetPageNumber(page); canvas.ShowTextAligned( new Paragraph($"Page {pageNumber}"), pageSize.GetWidth() / 2, pageSize.GetBottom() + 20, TextAlignment.CENTER); canvas.Close(); } } // Usage in main code - private void CreatePdf pattern public static void Main(string[] args) { PdfWriter writer = new PdfWriter("report.pdf"); PdfDocument pdfDoc = new PdfDocument(writer); Document document = new Document(pdfDoc); // Register the event handler for END_PAGE pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, new ITextEvents()); document.Add(new Paragraph("Sales Data")); document.Add(new Paragraph("Content goes here...")); document.Close(); } Imports iText.Kernel.Pdf Imports iText.Layout Imports iText.Layout.Element Imports iText.Kernel.Events Imports iText.Kernel.Geom Imports iText.Layout.Properties ' Event handler class for headers and footers - similar to PdfPageEventHelper Public Class ITextEvents Implements IEventHandler ' Private string for header text Private _header As String Public Property Header As String Get Return _header End Get Set(value As String) _header = value End Set End Property Public Sub HandleEvent(currentEvent As [Event]) Implements IEventHandler.HandleEvent Dim docEvent As PdfDocumentEvent = CType(currentEvent, PdfDocumentEvent) Dim pdfDoc As PdfDocument = docEvent.GetDocument() Dim page As PdfPage = docEvent.GetPage() Dim pageSize As Rectangle = page.GetPageSize() ' Create new PdfCanvas for the contentbyte object Dim pdfCanvas As New PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc) Dim canvas As New Canvas(pdfCanvas, pageSize) ' Add header text canvas.ShowTextAligned(New Paragraph("Quarterly Sales Report"), pageSize.GetWidth() / 2, pageSize.GetTop() - 20, TextAlignment.CENTER) ' Add footer with page number Dim pageNumber As Integer = pdfDoc.GetPageNumber(page) canvas.ShowTextAligned(New Paragraph($"Page {pageNumber}"), pageSize.GetWidth() / 2, pageSize.GetBottom() + 20, TextAlignment.CENTER) canvas.Close() End Sub End Class ' Usage in main code - private void CreatePdf pattern Public Module Program Public Sub Main(args As String()) Dim writer As New PdfWriter("report.pdf") Dim pdfDoc As New PdfDocument(writer) Dim document As New Document(pdfDoc) ' Register the event handler for END_PAGE pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, New ITextEvents()) document.Add(New Paragraph("Sales Data")) document.Add(New Paragraph("Content goes here...")) document.Close() End Sub End Module $vbLabelText $csharpLabel 此實作體現了這兩個函式庫之間根本的架構差異。 iText 7 需要建立一個單獨的處理程序類別來實作IEventHandler (類似於舊版PdfPageEventHelper ),使用浮點座標手動計算頁面位置,並管理PdfCanvas和Canvas物件以進行繪圖操作。 處理程序透過END_PAGE事件類型接收每個頁面的事件-這個細節讓許多開發人員感到困惑,他們錯誤地使用了START_PAGE 。 輸出 如何使用 iTextSharp 和 IronPDF 在 C# 中為 PDF 新增頁首和頁尾(附圖 8) iText 7 中的座標係以頁面左下角為起點,需要進行明確的定位計算。 要取得最終頁數,需要使用範本PdfTemplate headerTemplate 模式,該模式在public override void OnCloseDocument事件期間填充,這會增加更多樣板程式碼,從而增加複雜性。 對於有 Web 開發背景的開發者來說,這種基於座標的方法與聲明式 HTML/CSS 模型相比感覺很陌生。 每個定位決策都需要了解頁面尺寸、邊距偏移和文字測量——這些問題在基於 HTML 的方法中都被抽象化了。 iText 7 採用 AGPL 許可,這意味著使用 iTextSharp 或 iText 7 的應用程式必須是開源的,除非購買商業許可證。 在為商業項目選擇庫時,這是一個重要的考慮因素。 在常見情況下,這兩種方法有何異同? 當實現諸如帶有總計的頁碼等功能時,這種差異會更加明顯。 使用 IronPDF 時, {total-pages}可合併欄位會自動處理此問題。 使用 iText 7 時,您需要使用在OnCloseDocument事件期間填入的PdfFormXObject範本-此模式需要了解 PDF 產生生命週期。 在排查問題時,開發體驗也有顯著差異。 IronPDF 以 HTML 為基礎的方法表示您可以在瀏覽器中預覽頁首設計,然後再將其整合到 PDF 生成程式碼中。 如果發現有問題,您可以使用熟悉的瀏覽器開發者工具調整 HTML 和 CSS。 使用 iText 7 時,調試定位問題需要反覆產生測試 PDF 並手動測量座標。 基於 HTML 的方法意味著開發人員可以利用現有的 Web 開發技能。 IronPDF 的頁首和頁尾支援使用 HTML 和 CSS 實現的任何佈局,從 flexbox 佈局到響應式設計。 HTML 頁首和頁尾範例展示了其他樣式可能性。 相較之下,iText 方法需要建立新的PdfPTable結構,使用新的Phrase建構函數來新增文本,並使用新的浮點陣列手動定位元素。 跨平台和容器部署又該如何實現? 現代 .NET 應用程式通常部署到 Linux 容器、Azure 應用程式服務或 AWS Lambda 函數。 IronPDF 支援跨平台部署,可在 Windows、Linux 和 macOS 之間運行,無需額外配置。 該庫開箱即用,可在 Docker 容器中運行,因此適用於微服務架構和雲端原生應用程式。 這種跨平台功能也延伸到了頁首和頁尾功能——在 Windows 開發機器上產生具有頁眉的 PDF 的相同程式碼,在部署到 Linux 生產伺服器時會產生相同的輸出。 無需安裝額外的字體、配置渲染引擎或處理特定於平台的程式碼路徑。 對於執行容器化工作負載的團隊,IronPDF 的 Docker 部署文件提供了各種基礎映像和編排平台的配置指南。 該庫在不同環境下的一致性行為消除了 PDF 生成工作流程中常見的"在我的機器上運行正常"的錯誤來源。 如何處理不同頁面的不同頁首? 有些文件要求首頁使用不同的頁首(或不使用頁首),而後續頁面則使用標準格式。 IronPDF 透過基於頁面索引的標頭應用程式來支援此功能-無需檢查void OnEndPage處理程序中的條件或管理int i循環計數器: using IronPdf; using System.Linq; var renderer = new ChromePdfRenderer(); // Build multi-page HTML and include a print page-break between pages var pages = new List<string> { "<section><h1>Title Page</h1><p>Intro text on page 1.</p></section>", "<section><h2>Report</h2><p>Detailed report content on page 2.</p></section>", "<section><h2>Appendix</h2><p>Appendix content on page 3.</p></section>" }; var sb = new StringBuilder(); sb.AppendLine("<!doctype html><html><head><meta charset='utf-8'>"); sb.AppendLine("<style>"); sb.AppendLine(" body { font-family: Arial, sans-serif; margin: 20px; }"); sb.AppendLine(" .page-break { page-break-after: always; }"); sb.AppendLine(" @media print { .page-break { display:block; } }"); sb.AppendLine("</style>"); sb.AppendLine("</head><body>"); for (int i = 0; i < pages.Count; i++) { sb.AppendLine(pages[i]); // add page break between pages, but not after last page if (i < pages.Count - 1) sb.AppendLine("<div class='page-break'></div>"); } sb.AppendLine("</body></html>"); var multiPageHtmlContent = sb.ToString(); var pdf = renderer.RenderHtmlAsPdf(multiPageHtmlContent); // Create the standard header for checking header footer placement var standardHeader = new HtmlHeaderFooter { HtmlFragment = "<div style='text-align: center;'>Standard Header - Page {page}</div>", MaxHeight = 20 }; // Apply to all pages except the first (index 0) - start row at 1 var pageIndices = Enumerable.Range(1, pdf.PageCount - 1).ToList(); pdf.AddHtmlHeaders(standardHeader, 1, pageIndices); pdf.SaveAs("document-skip-first-page-header.pdf"); using IronPdf; using System.Linq; var renderer = new ChromePdfRenderer(); // Build multi-page HTML and include a print page-break between pages var pages = new List<string> { "<section><h1>Title Page</h1><p>Intro text on page 1.</p></section>", "<section><h2>Report</h2><p>Detailed report content on page 2.</p></section>", "<section><h2>Appendix</h2><p>Appendix content on page 3.</p></section>" }; var sb = new StringBuilder(); sb.AppendLine("<!doctype html><html><head><meta charset='utf-8'>"); sb.AppendLine("<style>"); sb.AppendLine(" body { font-family: Arial, sans-serif; margin: 20px; }"); sb.AppendLine(" .page-break { page-break-after: always; }"); sb.AppendLine(" @media print { .page-break { display:block; } }"); sb.AppendLine("</style>"); sb.AppendLine("</head><body>"); for (int i = 0; i < pages.Count; i++) { sb.AppendLine(pages[i]); // add page break between pages, but not after last page if (i < pages.Count - 1) sb.AppendLine("<div class='page-break'></div>"); } sb.AppendLine("</body></html>"); var multiPageHtmlContent = sb.ToString(); var pdf = renderer.RenderHtmlAsPdf(multiPageHtmlContent); // Create the standard header for checking header footer placement var standardHeader = new HtmlHeaderFooter { HtmlFragment = "<div style='text-align: center;'>Standard Header - Page {page}</div>", MaxHeight = 20 }; // Apply to all pages except the first (index 0) - start row at 1 var pageIndices = Enumerable.Range(1, pdf.PageCount - 1).ToList(); pdf.AddHtmlHeaders(standardHeader, 1, pageIndices); pdf.SaveAs("document-skip-first-page-header.pdf"); Imports IronPdf Imports System.Linq Imports System.Text Dim renderer As New ChromePdfRenderer() ' Build multi-page HTML and include a print page-break between pages Dim pages As New List(Of String) From { "<section><h1>Title Page</h1><p>Intro text on page 1.</p></section>", "<section><h2>Report</h2><p>Detailed report content on page 2.</p></section>", "<section><h2>Appendix</h2><p>Appendix content on page 3.</p></section>" } Dim sb As New StringBuilder() sb.AppendLine("<!doctype html><html><head><meta charset='utf-8'>") sb.AppendLine("<style>") sb.AppendLine(" body { font-family: Arial, sans-serif; margin: 20px; }") sb.AppendLine(" .page-break { page-break-after: always; }") sb.AppendLine(" @media print { .page-break { display:block; } }") sb.AppendLine("</style>") sb.AppendLine("</head><body>") For i As Integer = 0 To pages.Count - 1 sb.AppendLine(pages(i)) ' add page break between pages, but not after last page If i < pages.Count - 1 Then sb.AppendLine("<div class='page-break'></div>") End If Next sb.AppendLine("</body></html>") Dim multiPageHtmlContent As String = sb.ToString() Dim pdf = renderer.RenderHtmlAsPdf(multiPageHtmlContent) ' Create the standard header for checking header footer placement Dim standardHeader As New HtmlHeaderFooter With { .HtmlFragment = "<div style='text-align: center;'>Standard Header - Page {page}</div>", .MaxHeight = 20 } ' Apply to all pages except the first (index 0) - start row at 1 Dim pageIndices = Enumerable.Range(1, pdf.PageCount - 1).ToList() pdf.AddHtmlHeaders(standardHeader, 1, pageIndices) pdf.SaveAs("document-skip-first-page-header.pdf") $vbLabelText $csharpLabel AddHtmlHeaders中的第二個參數指定{page}可合併欄位的起始頁碼,而第三個參數接受要接收標頭的頁面索引集合(不需要結束行-此清單精確定義了哪些頁面)。 這種精細的控制方式使得複雜的文件佈局無需複雜的條件邏輯即可實現。 進階頁首和頁尾範例涵蓋了其他場景,包括奇數/偶數頁區分。 輸出 如何使用 iTextSharp 和 IronPDF 在 C# 中為 PDF 新增頁首和頁尾(範例):圖 9 - 不同頁面使用不同的頁眉 哪些設定控制頁首和頁尾的外觀? 微調頁首和頁尾涉及影響定位和視覺呈現的多個屬性。 TextHeaderFooter類別提供了以下自訂選項,用於控制單獨的頁首部分和單獨的頁尾部分的顯示方式: var footer = new TextHeaderFooter { LeftText = "Confidential", CenterText = "{pdf-title}", RightText = "Page {page}", Font = IronSoftware.Drawing.FontTypes.Arial, FontSize = 9, DrawDividerLine = true, DrawDividerLineColor = IronSoftware.Drawing.Color.Gray }; renderer.RenderingOptions.TextFooter = footer; renderer.RenderingOptions.MarginBottom = 20; var footer = new TextHeaderFooter { LeftText = "Confidential", CenterText = "{pdf-title}", RightText = "Page {page}", Font = IronSoftware.Drawing.FontTypes.Arial, FontSize = 9, DrawDividerLine = true, DrawDividerLineColor = IronSoftware.Drawing.Color.Gray }; renderer.RenderingOptions.TextFooter = footer; renderer.RenderingOptions.MarginBottom = 20; Imports IronSoftware.Drawing Dim footer As New TextHeaderFooter With { .LeftText = "Confidential", .CenterText = "{pdf-title}", .RightText = "Page {page}", .Font = FontTypes.Arial, .FontSize = 9, .DrawDividerLine = True, .DrawDividerLineColor = Color.Gray } renderer.RenderingOptions.TextFooter = footer renderer.RenderingOptions.MarginBottom = 20 $vbLabelText $csharpLabel Font屬性接受來自IronSoftware.Drawing.FontTypes的值,包括 Helvetica、Arial、Courier 和 Times New Roman。 Spacing屬性控制分隔線與文字內容之間的間距。 這些屬性無需CSS知識即可實現排版控制。 對於基於 HTML 的頁首和頁腳, LoadStylesAndCSSFromMainHtmlDocument屬性可以選擇從正在渲染的主文檔繼承樣式,從而確保頁首和正文內容之間的視覺一致性。 當您的主文檔使用自訂 CSS,而這些 CSS 也應該套用於頁首和頁尾區域時,這將特別有用。 DrawDividerLine屬性新增了一條專業的水平線,用於在頁首/頁尾和主要內容之間繪製分隔線。 您可以使用DrawDividerLineColor自訂線條顏色,以符合您的品牌顏色或文件主題。 除了頁碼之外,如何實現動態內容? 可合併欄位系統支援多個動態值,這些值會在渲染過程中自動填入: {page} - 當前頁碼 {total-pages} - 文件的最終頁數 {date} - 本機格式的目前日期 {time} - 本機格式的目前時間 {html-title} - <title></code> tag from the source HTML</title>的內容 {pdf-title} - PDF 文件元資料標題 {url} - 從網址渲染時的來源 URL 這些欄位的組合可以實現商務文件中常見的複雜頁尾設計。 法務部門通常要求在文件頁腳顯示文件標題、日期和頁數。 為了符合監管要求,財務報告可能需要添加時間戳。 可合併欄位可以滿足這些要求,而無需為每種文件類型編寫自訂程式碼。 對於真正動態的內容(即在執行時間確定的值),您可以在將 HTML 片段字串指派給HtmlFragment屬性之前,使用插值建構該字串。 這種方法允許在標頭中包含從資料庫檢索的值、使用者資訊或計算資料: string userName = GetCurrentUserName(); string documentVersion = "v2.3.1"; renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter { HtmlFragment = $"<div>Prepared by: {userName} Version: {documentVersion} Page {{page}}</div>", MaxHeight = 20 }; string userName = GetCurrentUserName(); string documentVersion = "v2.3.1"; renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter { HtmlFragment = $"<div>Prepared by: {userName} Version: {documentVersion} Page {{page}}</div>", MaxHeight = 20 }; Dim userName As String = GetCurrentUserName() Dim documentVersion As String = "v2.3.1" renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter With { .HtmlFragment = $"<div>Prepared by: {userName} Version: {documentVersion} Page {{page}}</div>", .MaxHeight = 20 } $vbLabelText $csharpLabel 使用字串插值時,請注意{page}周圍的雙花括號-這樣可以轉義花括號字符,以便在最終字串中保留可合併欄位。 這種模式的工作方式類似於在事件驅動程式碼中處理object sender, EventArgs e參數的方式,在註入自己的值的同時保持框架的佔位符不變。 開始使用 IronPdf 使用 IronPDF,只需幾分鐘即可在 PDF 文件中實現頁首和頁尾。 透過 NuGet 套件管理器安裝庫: Install-Package IronPdf 如何使用 iTextSharp 和 IronPDF 在 C# 中加入 PDF 頁首和頁尾(附圖 10 - 安裝) 或使用 .NET CLI: dotnet add package IronPDF dotnet add package IronPDF SHELL 該庫不需要任何外部依賴項,安裝後即可立即使用。 首先閱讀入門文檔,以了解 PDF 生成和操作的全部功能。 使用 IronPDF 的免費試用版,在您自己的專案中測試這些頁首和頁尾實作方式。 對於生產部署,授權選項可滿足從個人開發人員到企業團隊的各種需求。 如何使用 iTextSharp 和 IronPDF 在 C# 中為 PDF 新增頁首和頁尾(附圖 11 - 許可) 結論 在 C# 中為 PDF 文件新增頁首和頁尾的難易度取決於您選擇的庫。 iText 7 透過事件處理程序(例如public override void OnEndPage和使用PdfWriter writer 、 PdfContentByte cb模式的畫布操作提供底層控制,而 IronPDF 則透過一個利用熟悉的 HTML 和 CSS 概念的直覺 API 提供相同的功能。 對於優先考慮快速實作和可維護程式碼的開發人員來說,IronPDF 的方法將頁首和頁尾的實作從幾十行程式碼(包括public class PdfFooter處理程序、 PdfPCell cell配置和新的PdfPTable結構)減少到只需幾個屬性賦值。 基於 HTML 的樣式選項為複雜的設計提供了可能性,而無需學習 PDF 特有的座標系統或管理內容佈局標頭。 無論是產生帶有公司品牌標識的發票、帶有頁面導航的報告,還是需要時間戳的合同,專業的頁眉和頁腳都能建立文檔的可信度。 IronPDF 文件提供了更多範例和 API 參考資料,用於在您的 .NET 應用程式中實現這些以及其他 PDF 功能。 常見問題解答 如何使用 iTextSharp 在 PDF 中加入頁首和頁尾? 若要使用 iTextSharp 為 PDF 加入頁首和頁尾,您可以定義一個頁面事件處理器,在 PDF 建立過程中自訂文件的頁面。這包括覆寫 OnEndPage 方法,以包含所需的頁首和頁尾內容。 使用 IronPDF 添加页眉和页脚有什么好处? IronPDF 透過提供直接的 API 簡化了新增頁首和頁尾的流程,並支援多種樣式選項。它可與 C# 專案無縫整合,並提供 HTML 至 PDF 轉換等額外功能,使其成為處理 PDF 的多功能工具。 IronPDF 和 iTextSharp 可以一起使用嗎? 是的,IronPDF 和 iTextSharp 可以在 C# 專案中一起使用。iTextSharp 非常適合程式化的 PDF 操作,而 IronPDF 則是它的補充,提供額外的功能,例如將 HTML 轉換為 PDF,這對於動態產生頁首和頁尾非常有用。 是否有辦法使用 IronPDF 設定頁首和頁尾的樣式? IronPDF 允許您使用 HTML 和 CSS 設定頁首和頁尾的樣式。這讓開發人員可以靈活地為他們的 PDF 文件創建具有視覺吸引力的設計和佈局。 IronPDF 如何處理頁首和頁尾的頁數? IronPDF 可在頁首和頁尾自動插入頁碼。它可根據您的需求提供格式化頁碼的選項,例如包含總頁數或調整起始頁碼。 IronPDF 使用 C# 進行 PDF 操作的優勢是什麼? 使用 IronPDF 的 C# 進行 PDF 操作具有強大的類型安全性,可輕鬆與 .NET 應用程式整合,並可存取廣泛的函式庫和工具,以強化開發流程。IronPdf 的 C# API 設計得既直觀又人性化,讓不同技術水準的開發人員都能使用。 我可以使用 IronPDF 將現有文件轉換為 PDF 嗎? 是的,IronPDF 可以將各種文件格式(包括 HTML、ASPX 和其他基於 Web 的內容)轉換為 PDF。這項功能對於從網頁或動態產生的內容建立 PDF 尤其有用。 Curtis Chau 立即與工程團隊聊天 技術撰稿人 Curtis Chau 擁有電腦科學學士學位(卡爾頓大學),專長於前端開發,精通 Node.js、TypeScript、JavaScript 和 React。Curtis 對製作直覺且美觀的使用者介面充滿熱情,他喜歡使用現代化的架構,並製作結構良好且視覺上吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 也有濃厚的興趣,他喜歡探索整合硬體與軟體的創新方式。在空閒時間,他喜歡玩遊戲和建立 Discord bots,將他對技術的熱愛與創意結合。 相關文章 更新2026年1月22日 How to Create PDF Documents in .NET with IronPDF: Complete Guide Discover effective methods to create PDF files in C# for developers. Enhance your coding skills and streamline your projects. Read the article now! 閱讀更多 更新2026年1月21日 How to Merge PDF Files in VB.NET: Complete Tutorial Merge PDF VB NET with IronPDF. Learn to combine multiple PDF files into one document using simple VB.NET code. Step-by-step examples included. 閱讀更多 更新2026年1月21日 C# PDFWriter Tutorial: Create PDF Documents in .NET Learn to create PDFs efficiently using C# PDFWriter with this step-by-step guide for developers. Read the article to enhance your skills today! 閱讀更多 Dynamic PDF Generation .NET Using IronPDFHow to Retrieve PDF File from Datab...
更新2026年1月22日 How to Create PDF Documents in .NET with IronPDF: Complete Guide Discover effective methods to create PDF files in C# for developers. Enhance your coding skills and streamline your projects. Read the article now! 閱讀更多
更新2026年1月21日 How to Merge PDF Files in VB.NET: Complete Tutorial Merge PDF VB NET with IronPDF. Learn to combine multiple PDF files into one document using simple VB.NET code. Step-by-step examples included. 閱讀更多
更新2026年1月21日 C# PDFWriter Tutorial: Create PDF Documents in .NET Learn to create PDFs efficiently using C# PDFWriter with this step-by-step guide for developers. Read the article to enhance your skills today! 閱讀更多