如何在 VB.NET 中將 PDF 轉換為 JPG
Full Comparison
Looking for a detailed feature-by-feature breakdown? See how IronPDF stacks up against Itext on pricing, HTML support, and licensing.
在C#中為PDF文件新增頁眉和頁腳
為PDF文件新增頁眉和頁腳是建立專業報告、發票和商業文件的關鍵。 尋找使用OnEndPage方法的iText解決方案的開發者會發現,現代.NET程式庫提供了實現相同結果的更簡單的方法。
本指南展示如何使用C#在PDF文件中新增頁眉和頁腳,並比較傳統iText方法與IronPDF簡潔的API。 到最後,您將了解從建立新Document到生成最終PDF文件的兩種實現,並可以選擇最適合您專案需求的方法。

為什麼PDF頁眉和頁腳在專業文件中很重要?
頁眉和頁腳在專業PDF文件中起著至關重要的作用。 它們通過形象標識提供一致的品牌,通過頁碼啟用頁面導航,顯示重要的元資料,如日期和文件標題,並通過時間戳和版本資訊建立文件的真實性。
在企業環境中,頁眉和頁腳往往具有法律意義。 財務報告需要時間戳以供審計查詢。 合同需要頁碼以確保完整性。 內部文件可能需要在每頁上顯示保密聲明。 程式化的方式來滿足這些要求需要一個能可靠處理頁面層次內容插入的PDF程式庫。
程式化新增頁眉和頁腳的關鍵原因包括:
- 審計合規 -- 每頁的時間戳和版本號滿足法規要求
- 品牌一致性 -- 公司標識和樣式應用於所有生成的文件
- 導航 -- 頁碼和章節標題幫助讀者快速定位資訊
- 真實性 -- 作者名稱、建立日期和文件ID防止對文件完整性的爭議

如何在C#中新增文字頁眉和頁腳?
IronPDF為在.NET應用程式中向PDF文件新增頁眉和頁腳提供了最直接的方法。 使用HtmlHeaderFooter,您可以用最少的程式碼生成頁眉和頁腳 -- 無需建立單獨的單元或手動管理contentbyte物件。
在編寫任何程式碼之前,使用NuGet將IronPDF新增到您的專案中:
Install-Package IronPdf
該程式庫不需要外部依賴,安裝後即可立即使用。 它針對.NET 5、6、7、8和10,運行於Windows、Linux和macOS,無需特定於平台的配置。
在舊的iText模式中,開發者建立輔助方法如private static void AddContent()以手動插入頁眉和頁腳邏輯。 IronPDF完全消除了這樣的樣板。
這是一個完整範例,新增文字頁眉和頁腳到PDF文件中:
using IronPdf;
// Initialize the PDF renderer
var renderer = new ChromePdfRenderer();
// Configure the text header
renderer.RenderingOptions.TextHeader = new TextHeaderFooter
{
CenterText = "Quarterly Sales Report",
DrawDividerLine = true,
FontSize = 14
};
// Configure the text footer with page number and date
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
renderer.RenderingOptions.TextHeader = new TextHeaderFooter
{
CenterText = "Quarterly Sales Report",
DrawDividerLine = true,
FontSize = 14
};
// Configure the text footer with page number and date
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 = New ChromePdfRenderer()
' Configure the text header
renderer.RenderingOptions.TextHeader = New TextHeaderFooter With {
.CenterText = "Quarterly Sales Report",
.DrawDividerLine = True,
.FontSize = 14
}
' Configure the text footer with page number and date
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")
TextHeaderFooter類提供了用於定位頁眉或頁腳區域中左、中或右文字的屬性。 DrawDividerLine屬性在頁眉或頁腳和主要文件內容之間新增了專業的分隔線。 可合併的字段如{date}在PDF生成過程中自動填充動態值。
IronPDF自動處理邊距計算,確保頁眉和頁腳不與文件內容重疊。 TextHeaderFooter類支持IronSoftware.Drawing.FontTypes中的字體型別,使您在不依賴外部的情況下擁有對排版的控制權。
輸出

請注意,整個實現都適合在單個程式碼塊中,具有明確且可讀的屬性賦值。 無需建立單獨的類文件、計算像素位置或管理畫布物件。 該程式庫抽象了這些複雜性,讓您專注於內容而不是PDF生成的機械。
如何建立HTML樣式的頁眉和頁腳?
對於更複雜的設計,IronPDF的HtmlHeaderFooter類啟用了完整的HTML和CSS樣式。 當頁眉需要包含形象標識、複雜佈局或品牌特定的樣式時,此方法特別有價值 -- 無需手動建立new 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")
此範例程式碼展示了HTML頁眉如何將圖像與文字結合。 BaseUrl屬性確定了解決相對圖像URL的根路徑,這樣可以簡單地包含公司標識或其他圖形。 MaxHeight屬性確保頁眉不超出指定尺寸,保持一致的文件佈局。
在HTML頁眉和頁腳中,合併字段({pdf-title})的功能相同,在不需要額外程式碼的情況下提供動態內容插入。 有關實施各種頁眉樣式的指南,請參閱頁眉和頁腳操作指南。
HTML方法在建立品牌文件時表現出色。 市場推廣團隊可以提供開發人員直接整合的HTML模板,確保經過批准的設計的像素級完美再現。 CSS屬性如border可以按預期工作,使得需要廣泛底層程式碼的其他程式庫中實現的複雜視覺處理變得容易。

如何將頁眉新增到現有的PDF文件中?
常見需求是將頁眉和頁腳新增到已經存在的PDF文件中 -- 無論它們是上傳文件、合併文件還是由其他系統生成的PDF。 IronPDF通過AddHtmlFooters方法處理此情況。
using IronPdf;
// Load an existing PDF document
var pdf = PdfDocument.FromFile("customer-profile.pdf");
// Define the header to add
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
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
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")
PdfDocument類表示已載入或渲染的PDF,並提供用於後期渲染修改的方法。 渲染和修改的分離使PDF文件能夠通過多個處理階段的工作流程。 AddHtmlHeaders方法自動將頁眉應用於每一頁,您也可以通過傳遞頁面索引集合來針對特定頁面。
輸入

輸出

此功能在文件管理系統中變得極為重要,這些系統接收來自各個來源的PDF文件,如掃描文件、使用者上傳文件或第三方API響應。 IronPDF在分發或存檔之前標準化品牌或頁碼。
如何在不同頁面上新增不同的頁眉?
有些文件需要首頁有不同的頁眉(或根本沒有頁眉),而隨後的頁面使用標準格式。 IronPDF通過基於頁面索引的頁眉應用支持這一點 -- 無需在void OnEndPage處理中檢查條件或手動管理迴圈計數器:
using IronPdf;
using System.Collections.Generic;
using System.Linq;
using System.Text;
var renderer = new ChromePdfRenderer();
// Build multi-page HTML with print page-breaks 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("</style>");
sb.AppendLine("</head><body>");
for (int i = 0; i < pages.Count; i++)
{
sb.AppendLine(pages[i]);
if (i < pages.Count - 1)
sb.AppendLine("<div class='page-break'></div>");
}
sb.AppendLine("</body></html>");
var pdf = renderer.RenderHtmlAsPdf(sb.ToString());
// Create the standard header for pages 2 onwards
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)
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.Collections.Generic;
using System.Linq;
using System.Text;
var renderer = new ChromePdfRenderer();
// Build multi-page HTML with print page-breaks 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("</style>");
sb.AppendLine("</head><body>");
for (int i = 0; i < pages.Count; i++)
{
sb.AppendLine(pages[i]);
if (i < pages.Count - 1)
sb.AppendLine("<div class='page-break'></div>");
}
sb.AppendLine("</body></html>");
var pdf = renderer.RenderHtmlAsPdf(sb.ToString());
// Create the standard header for pages 2 onwards
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)
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.Collections.Generic
Imports System.Linq
Imports System.Text
Dim renderer As New ChromePdfRenderer()
' Build multi-page HTML with print page-breaks 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("</style>")
sb.AppendLine("</head><body>")
For i As Integer = 0 To pages.Count - 1
sb.AppendLine(pages(i))
If i < pages.Count - 1 Then
sb.AppendLine("<div class='page-break'></div>")
End If
Next
sb.AppendLine("</body></html>")
Dim pdf = renderer.RenderHtmlAsPdf(sb.ToString())
' Create the standard header for pages 2 onwards
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)
Dim pageIndices = Enumerable.Range(1, pdf.PageCount - 1).ToList()
pdf.AddHtmlHeaders(standardHeader, 1, pageIndices)
pdf.SaveAs("document-skip-first-page-header.pdf")
{page}可合併字段的起始頁碼,而第三個參數接受要收到頁眉的頁面索引集合。 這種細粒度控制允許實現複雜的文件佈局,而無需複雜的條件邏輯。 高級頁眉和頁腳範例涵蓋其他場景,包括奇/偶頁面區分。
輸出

如何實現超出頁碼的動態內容?
可合併字段系統支持幾個在渲染過程中自動填充的動態值。 下表列出所有可用字段及其含義:
| 字段 | 插入值 | 典型用途 |
|---|---|---|
{page} |
當前頁碼 | 顯示"第3頁"的頁腳 |
{total-pages} |
總頁數 | 顯示"第3頁,共10頁"的頁腳 |
{date} |
當地格式的當前日期 | 審計時間戳,報告日期 |
{time} |
當地格式的當前時間 | 法規遵從頁腳 |
{html-title} |
HTML <title>標籤的內容 |
顯示頁面標題的文件頁眉 |
{pdf-title} |
PDF文件元資料標題 | 帶有文件名的品牌頁腳 |
{url} |
從網頁地址渲染時的源URL | 用於網路內容歸檔的頁腳 |
對於真正的動態內容 -- 運行時確定的值 -- 您可以在將其賦予HtmlFragment屬性之前構建帶有插值值的HTML片段字串。 這種方法允許在頁眉中包含資料庫檢索的值、使用者資訊或計算資料:
using IronPdf;
string userName = GetCurrentUserName();
string documentVersion = "v2.3.1";
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
HtmlFragment = $"<div style='font-size:10px;'>Prepared by: {userName} " +
$"| Version: {documentVersion} " +
"| Page {page} of {total-pages}</div>",
MaxHeight = 20
};
var pdf = renderer.RenderHtmlAsPdf("<h1>Annual Report</h1><p>Body content here.</p>");
pdf.SaveAs("dynamic-header-report.pdf");
using IronPdf;
string userName = GetCurrentUserName();
string documentVersion = "v2.3.1";
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
HtmlFragment = $"<div style='font-size:10px;'>Prepared by: {userName} " +
$"| Version: {documentVersion} " +
"| Page {page} of {total-pages}</div>",
MaxHeight = 20
};
var pdf = renderer.RenderHtmlAsPdf("<h1>Annual Report</h1><p>Body content here.</p>");
pdf.SaveAs("dynamic-header-report.pdf");
Imports IronPdf
Dim userName As String = GetCurrentUserName()
Dim documentVersion As String = "v2.3.1"
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter With {
.HtmlFragment = $"<div style='font-size:10px;'>Prepared by: {userName} " &
$"| Version: {documentVersion} " &
"| Page {page} of {total-pages}</div>",
.MaxHeight = 20
}
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Annual Report</h1><p>Body content here.</p>")
pdf.SaveAs("dynamic-header-report.pdf")
請注意,{total-pages}標籤作為純字串留在C#字串串接中 -- 而不是在插值部分中。 在PDF渲染過程中,IronPDF自動替換這些標籤。 此模式適用於任何運行值:來自Active Directory的使用者名、來自資料庫的文件ID、來自構建流水線的版本字串或來自報告引擎的計算總額。
合併字段和字串插值的組合實現了企業文件常見的複雜頁腳設計。 法律部門經常需要顯示文件標題、日期和頁數的頁腳。 財務報告可能需要時間戳以符合法規要求。 這些要求在不需為每種文件型別編寫自定義程式碼的情況下得到滿足。
iText方法看起來怎樣?
熟悉iText(iText的繼任者)的開發者知道,新增頁眉和頁腳需要實現事件處理程式。 該程式庫使用頁面事件系統,您需要建立一個響應文件生命周期事件(如OnCloseDocument)的類。
下面是使用iText和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 _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 a new PdfCanvas for the contentbyte object
PdfCanvas pdfCanvas = new PdfCanvas(
page.NewContentStreamBefore(),
page.GetResources(),
pdfDoc);
Canvas canvas = new Canvas(pdfCanvas, pageSize);
// Add header text at calculated position
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
var writer = new PdfWriter("report.pdf");
var pdfDoc = new PdfDocument(writer);
var 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 _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 a new PdfCanvas for the contentbyte object
PdfCanvas pdfCanvas = new PdfCanvas(
page.NewContentStreamBefore(),
page.GetResources(),
pdfDoc);
Canvas canvas = new Canvas(pdfCanvas, pageSize);
// Add header text at calculated position
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
var writer = new PdfWriter("report.pdf");
var pdfDoc = new PdfDocument(writer);
var 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 _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 a 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 at calculated position
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
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()
這一實現展示了兩個程式庫的基本架構差異。 iText需要建立一個實現Canvas物件進行繪圖操作。 該處理程式通過END_PAGE事件型別接收每個頁面的事件 -- 這一細節讓很多開發者錯誤使用START_PAGE。
輸出

iText的坐標系以頁面左下角為原點,需要顯式計算定位。 獲取最終頁數需要在OnCloseDocument中填入 -- 這一模式為已經繁瑣的工作流程增加了更多樣板程式碼。
對於來自網頁開發背景的開發者來說,基於坐標的方法感覺與聲明式的HTML/CSS模型背道而馳。 每個定位決策都需要了解頁面尺寸、邊距偏移和文字測量 -- 這是HTML方法中抽象掉的問題。
iText還採用AGPL許可證,這意味著使用iText或iText的應用程式必須是開源的,除非購買商業許可證。 這在選擇用於商業專案的程式庫時是一個重要的考慮因素。
這兩種方法如何比較?
當你並排比較具體功能時,差異變得更加明確。下表總結了主要區別:
| 功能 | IronPDF | iText / iText |
|---|---|---|
| 實現風格 | 屬性分配在渲染器選項上 | 實現IEventHandler的事件處理程式類 |
| HTML/CSS支持 | 通過HtmlHeaderFooter支持完整的HTML和CSS | 無原生HTML支持;需要底層畫布繪圖 |
| 頁碼總數 | 通過{total-pages}字段自動實現 |
需要在OnCloseDocument中填寫PdfTemplate |
| 頁眉中的圖像 | 使用BaseUrl的標準HTML <img>標籤 |
需要Image物件和手動定位 |
| 新增到現有PDF | AddHtmlHeaders / AddHtmlFooters方法 | 需要重新通過stamper或事件迴圈處理 |
| 按頁面定位 | 將頁面索引列表傳遞給方法 | 在事件處理程式中加入條件邏輯 |
| 許可模式 | 商業與免費試用 | AGPL(開源)或商業 |
| 跨平台 | Windows、Linux、macOS;可準備好Docker | Windows、Linux、macOS |
在解決問題時,開發經歷也有顯著差異。 IronPDF的HTML方法意味着您可以在將其整合到PDF生成程式碼中之前在瀏覽器中預覽頁眉設計。 如果某些內容看起來不對,您可以使用熟悉的瀏覽器開發人員工具來調整HTML和CSS。 使用iText,除錯定位問題需要反覆生成測試PDF並手動測量坐標。
基於HTML的方法意味著您可以直接應用現有的網頁開發技能。 任何HTML和CSS能實現的佈局在IronPDF頁眉和頁腳中都可行,從flexbox安排到圖像網格。 HTML頁眉和頁腳範例展示了更多樣式可能性。
自定義頁眉和頁腳外觀
微調頁眉和頁腳涉及幾個影響定位和視覺展示的屬性。 TextHeaderFooter類提供了這些自定選項:
using IronPdf;
using IronSoftware.Drawing;
var renderer = new ChromePdfRenderer();
var footer = new TextHeaderFooter
{
LeftText = "Confidential",
CenterText = "{pdf-title}",
RightText = "Page {page} of {total-pages}",
Font = FontTypes.Arial,
FontSize = 9,
DrawDividerLine = true,
DrawDividerLineColor = Color.Gray
};
renderer.RenderingOptions.TextFooter = footer;
renderer.RenderingOptions.MarginBottom = 20;
var pdf = renderer.RenderHtmlAsPdf("<h1>Board Report</h1><p>Executive summary content.</p>");
pdf.SaveAs("board-report.pdf");
using IronPdf;
using IronSoftware.Drawing;
var renderer = new ChromePdfRenderer();
var footer = new TextHeaderFooter
{
LeftText = "Confidential",
CenterText = "{pdf-title}",
RightText = "Page {page} of {total-pages}",
Font = FontTypes.Arial,
FontSize = 9,
DrawDividerLine = true,
DrawDividerLineColor = Color.Gray
};
renderer.RenderingOptions.TextFooter = footer;
renderer.RenderingOptions.MarginBottom = 20;
var pdf = renderer.RenderHtmlAsPdf("<h1>Board Report</h1><p>Executive summary content.</p>");
pdf.SaveAs("board-report.pdf");
Imports IronPdf
Imports IronSoftware.Drawing
Dim renderer As New ChromePdfRenderer()
Dim footer As New TextHeaderFooter With {
.LeftText = "Confidential",
.CenterText = "{pdf-title}",
.RightText = "Page {page} of {total-pages}",
.Font = FontTypes.Arial,
.FontSize = 9,
.DrawDividerLine = True,
.DrawDividerLineColor = Color.Gray
}
renderer.RenderingOptions.TextFooter = footer
renderer.RenderingOptions.MarginBottom = 20
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Board Report</h1><p>Executive summary content.</p>")
pdf.SaveAs("board-report.pdf")
IronSoftware.Drawing.FontTypes中的值,包括Helvetica、Arial、Courier和Times New Roman。 DrawDividerLine屬性在頁腳和主要內容之間新增專業的水平規則。 您可以使用DrawDividerLineColor自定義線條顏色以匹配您的品牌顏色或文件主題。
對於基於HTML的頁眉和頁腳,LoadStylesAndCSSFromMainHtmlDocument屬性可選地繼承來自正在渲染的主要文件的樣式,確保頁眉和正文內容之間的視覺一致性。 當您的主要文件使用自定CSS並且應該同時適用於頁眉和頁腳區域時,這特別有用。

跨平台和容器部署
現代.NET應用程式經常部署到Linux容器、Azure App Services或AWS Lambda功能。 IronPDF支持跨平台部署於Windows、Linux和macOS,而不需額外配置。 該程式庫直接在Docker容器中運行,使其適合微服務架構和雲原生應用程式。
這種跨平台能力擴展到頁眉和頁腳功能 -- 在Windows開發機器上生成帶有頁眉的PDF的同一段程式碼在部署到Linux生產伺服器時產生相同的輸出。 無需安裝額外的字體、配置渲染引擎或處理特定於平台的程式碼路徑。
對於運行容器化工作負載的團隊,IronPDF Docker部署文件提供了針對各種基本映像和編排平台的配置指南。 該程式庫在不同環境中一致的行為消除了PDF生成工作流程中常見的錯誤來源。
根據Microsoft的.NET文件,容器化的.NET應用程式受益於不同環境一致的運行行為 -- 這是IronPDF的渲染引擎在PDF生成任務中加強的一個原則。 類似地,Docker的官方文件解釋了適用於PDF生成服務的容器化.NET工作負載的最佳實踐。
iText文件也確認了跨平台支持,但其事件驅動模型的額外複雜性意味著除錯跨平台渲染問題比起聲明式HTML方法更容易相關。
您的下一步該怎麼做?
使用IronPDF新增頁眉和頁腳到您的PDF文件只需幾分鐘。 通過NuGet套件管理器安裝程式庫:
Install-Package IronPdf

從這里開始,這些資源將幫助您更進一步:
- 入門文件 -- 涵蓋完整的PDF生成和操作功能
- 頁眉和頁腳操作指南 -- 所有頁眉和頁腳場景的分步指導
- HTML頁眉和頁腳範例 -- 現成運行的HTML頁眉程式碼範例
- 高級頁眉和頁腳範例 -- 按頁面定位和奇偶頁區分
- TextHeaderFooter API 參考 -- 文字頁眉和頁腳的完整屬性列表
- HtmlHeaderFooter API參考 -- 用於HTML頁眉和頁腳的完整API
- Docker部署指導 -- 用於Linux容器和雲環境的配置
- IronPDF授權選項 -- 從獨立開發者到企業團隊的方案
開始您的免費試用以在您自己的專案中測試頁眉和頁腳實現。 試用包含所有功能,而無時間限制功能,使您在購買許可證之前評估該程式庫是否滿足您真實世界PDF文件需求。

在C#中向PDF文件新增頁眉和頁腳的複雜程度取決於您選擇的程式庫。儘管iText通過事件處理程式和畫布操作提供低層次控制,IronPDF則通過應用既熟悉又易於維護的HTML和CSS概念的API提供相同功能。對於優先考慮快速實施和可維護程式碼的開發者,IronPDF將頁眉和頁腳實現從幾十行程式碼 -- 包括處理程式類、單元配置和表格結構 -- 減少到僅僅幾個屬性分配。
常見問題
如何使用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可以自動將頁碼插入到表頭和頁尾中。它提供了根據您的需求格式化頁碼的選項,例如包括總頁數或調整起始頁碼。
使用C#和IronPDF進行PDF操作的優勢是什麼?
使用C#和IronPDF進行PDF操作提供了強型別安全性、輕鬆整合.NET應用程式的能力,以及存取增強開發過程的各種程式庫和工具的能力。IronPDF的C# API設計直觀且易於使用,使所有技能水平的開發人員都能夠存取。
我可以使用IronPDF將現有文件轉換為PDF嗎?
是的,IronPDF可以將各種文件格式(包括HTML、ASPX和其他基於網頁的內容)轉換為PDF。此功能對於從網頁或動態生成的內容建立PDF特別有用。

