跳過到頁腳內容
使用IRONPDF

如何在PDF中使用C#添加頁碼

"便攜式文件格式",或 PDF,是一種由 Adobe 創建的檔案格式。 在展示需要對文字和圖片進行格式化的論文時,PDF 文件非常方便。 在現今世界中,PDF 檔案是不可或缺的,並被所有企業部門用來建立文件和開立發票。 由於目前市場上有多種 PDF 函式庫,建立 PDF 實際上已成為一種本能。為了選擇適合您的 PDF 函式庫,在使用其中一個函式庫進行專案之前,權衡每個函式庫的優點與特性是非常重要的。

本文將介紹如何使用 iTextSharp C# 在 PDF 中加入頁碼。 此外,我們也將比較iTextSharpIronPDF

如何使用 iTextSharp C# 在 PDF 中加入頁碼

1.使用任何 IDE 建立新的 C# 專案。 2.建立新的 PDF 物件。 3.在 HTML 頁尾加入頁數。

  1. 從 HTML 內容建立 PDF。
  2. 將 PDF 檔案儲存到您的電腦。

什麼是 IronPDF

IronPDF是一個強大的 PDF .NET 框架,開發人員可以使用它來輕鬆產生、檢視和編輯 PDF 文件。 IronPDF 是一個精密的工具,內部以 chromium 引擎執行。 它可以將 HTML5、JavaScript、CSS 和圖片檔案轉換為 PDF,新增自訂頁首和頁腳,並產生與瀏覽器中顯示效果完全相同的 PDF 檔案。 IronPDF for .NET 支援許多線上和網路格式,包括 HTML、ASPX、Razor View 和 MVC。

IronPDF 功能

  • 使用 .NET C# 程式碼建立、讀取和簡單編輯 PDF 檔案。
  • 透過網站 URL 連結建立 PDF,同時管理 User-Agent、Proxy、Cookie、HTTP 標頭和表單變量,以啟用使用 HTML 登入表單進行登入。
  • 從現有 PDF 檔案中刪除影像。
  • 包含 PDF 的元素:表格、文字、照片、書籤、浮水印、頁首、頁尾等。
  • 能夠輕鬆地分離和合併多個 PDF 文件的頁面。

要了解有關 IronPDF 文件的更多信息,請參閱此處

安裝 IronPDF。

在 Visual Studio 工具中,選擇 NuGet 套件管理器,即可在"工具"下找到 Visual 命令列介面。 以下指令應輸入套件管理終端標籤。

Install-Package IronPdf

或者我們可以使用套件管理員的方法。 使用 Visual Studio 的 NuGet Package Manager 選項,可以直接將套件安裝到解決方案中。 在 NuGet 網站上有一個搜尋方塊可用來尋找套件。我們只需要在套件管理員中尋找"IronPDF",如下截圖所示:

How to Add Page Numbers in PDF using iTextSharp in C#:圖 1 - 從套件管理員安裝 IronPDF

上方顯示的是相關搜尋結果清單。 若要在您的系統上安裝套件,請進行必要的選擇。

現在套件已經下載並安裝完成,可以在目前的專案中使用。

什麼是 iTextSharp

iTextSharp 是用 C# 製作和修改 PDF 文件的靈活函式庫。 它提供了多種功能,例如加密、PDF合併、文字和圖片提取等等。 iTextSharp 是一種高效的工具,可執行多種任務,包括在 PDF 中加入頁碼。

iTextSharp 功能

  • 可透過 iText 函式庫使用 API 來產生 PDF 文件。
  • HTML 和 XML 字串均可使用 iText 程式解析為 PDF 檔案。
  • 我們可以使用 iText 庫為 PDF 文件添加書籤、頁碼和標記。
  • 我們也可以使用 iText 函式庫將一個 PDF 文件拆分成多個 PDF,或將多個 PDF 文件合併成一個 PDF。
  • 我們可以使用 iText 修改 PDF 表單。

安裝 iTextSharp

使用 NuGet 套件管理器尋找 iText。 iText7 和 iText.pdfhtml 是必要的安裝程式,因為 iText 功能分佈在許多套件中。

如果您選擇 Visual Command-Line 介面,則需要安裝下列套件:

Install-Package iTextSharp

由於 iText 7 是最新的版本,因此我們在解決方案中採用了 iText 7。

使用 IronPDF 添加頁碼。

透過 IronPDF 的綜合資料庫,在 PDF 檔案中加入頁碼變得非常簡單。 為了便於理解,請參閱以下程式碼。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        // Create a new HtmlToPdf renderer instance
        var renderer = new HtmlToPdf();

        // Define the HTML content with a header
        string header = "<h1>Hello IronPDF!</h1>";

        // Render the HTML as a PDF document
        PdfDocument pdf = renderer.RenderHtmlAsPdf(header);

        // Define the HTML footer with page numbers
        HtmlHeaderFooter htmlFooter = new HtmlHeaderFooter()
        {
            HtmlFragment = "<center><i>{page} of {total-pages}</i></center>"
        };

        // Add footer to the PDF
        pdf.AddHtmlFooters(htmlFooter);

        // Save the PDF document to a file
        pdf.SaveAs("output.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        // Create a new HtmlToPdf renderer instance
        var renderer = new HtmlToPdf();

        // Define the HTML content with a header
        string header = "<h1>Hello IronPDF!</h1>";

        // Render the HTML as a PDF document
        PdfDocument pdf = renderer.RenderHtmlAsPdf(header);

        // Define the HTML footer with page numbers
        HtmlHeaderFooter htmlFooter = new HtmlHeaderFooter()
        {
            HtmlFragment = "<center><i>{page} of {total-pages}</i></center>"
        };

        // Add footer to the PDF
        pdf.AddHtmlFooters(htmlFooter);

        // Save the PDF document to a file
        pdf.SaveAs("output.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create a new HtmlToPdf renderer instance
		Dim renderer = New HtmlToPdf()

		' Define the HTML content with a header
		Dim header As String = "<h1>Hello IronPDF!</h1>"

		' Render the HTML as a PDF document
		Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(header)

		' Define the HTML footer with page numbers
		Dim htmlFooter As New HtmlHeaderFooter() With {.HtmlFragment = "<center><i>{page} of {total-pages}</i></center>"}

		' Add footer to the PDF
		pdf.AddHtmlFooters(htmlFooter)

		' Save the PDF document to a file
		pdf.SaveAs("output.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

首先,我們定義要轉換為 PDF 的 HTML 文字。 此HTML內容可以包含單一HTML段落或整個HTML頁面。 接下來,我們建立一個HtmlToPdf類別的實例,該類別提供 HTML 到 PDF 的轉換函數RenderHtmlAsPdf

HTML 內容作為參數傳遞給RenderHtmlAsPdf函數。 我們指定需要轉換為 PDF 的 HTML 內容。 頁碼以佔位符的形式表示,或如 HTML 文字頁尾部分中的 {page} of {total-pages}

此方法會將建立的 PDF 文件作為PdfDocument物件傳回。 使用SaveAs方法,我們將 PDF 文件儲存到名為"output.pdf"的檔案中。 或者,我們可以使用OpenInDefaultPDFViewer函數,以系統的預設 PDF 閱讀器開啟已建立的 PDF 文件。 我們也可以使用上述方法為現有的 PDF 檔案添加頁碼。

如何在 C# 中使用 iTextSharp 在 PDF 中新增頁碼:圖 2 - IronPDF:帶有頁碼的輸出 PDF

要了解有關 IronPDF 代碼的更多信息,請參閱此處

使用 iTextSharp 新增頁碼。

首先,讓我們使用 iTextSharp 來產生一個新的 PDF 文件。 以下是建立帶有頁碼的新 PDF 文件的基本範例:

using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a new PDF document
            Document doc = new Document();
            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream("output.pdf", FileMode.Create));

            // Open the document to add content
            doc.Open();
            doc.Add(new Paragraph("Hello, world!"));

            // Attach page number event to PDF writer
            writer.PageEvent = new PageNumberEventHandler();

            // Close the document
            doc.Close();
        }
    }

    public class PageNumberEventHandler : PdfPageEventHelper
    {
        public override void OnOpenDocument(PdfWriter writer, Document document)
        {
            base.OnOpenDocument(writer, document);
        }

        public override void OnEndPage(PdfWriter writer, Document document)
        {
            base.OnEndPage(writer, document);

            // Create a table to hold the page number
            PdfPTable table = new PdfPTable(1);
            table.TotalWidth = 300f;
            table.HorizontalAlignment = Element.ALIGN_CENTER;

            PdfPCell cell = new PdfPCell(new Phrase($"Page {writer.PageNumber}"));
            cell.Border = 0;
            table.AddCell(cell);

            // Write the table at the bottom of the page
            table.WriteSelectedRows(0, -1, 150f, document.Bottom, writer.DirectContent);
        }

        public override void OnCloseDocument(PdfWriter writer, Document document)
        {
            base.OnCloseDocument(writer, document);
        }
    }
}
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a new PDF document
            Document doc = new Document();
            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream("output.pdf", FileMode.Create));

            // Open the document to add content
            doc.Open();
            doc.Add(new Paragraph("Hello, world!"));

            // Attach page number event to PDF writer
            writer.PageEvent = new PageNumberEventHandler();

            // Close the document
            doc.Close();
        }
    }

    public class PageNumberEventHandler : PdfPageEventHelper
    {
        public override void OnOpenDocument(PdfWriter writer, Document document)
        {
            base.OnOpenDocument(writer, document);
        }

        public override void OnEndPage(PdfWriter writer, Document document)
        {
            base.OnEndPage(writer, document);

            // Create a table to hold the page number
            PdfPTable table = new PdfPTable(1);
            table.TotalWidth = 300f;
            table.HorizontalAlignment = Element.ALIGN_CENTER;

            PdfPCell cell = new PdfPCell(new Phrase($"Page {writer.PageNumber}"));
            cell.Border = 0;
            table.AddCell(cell);

            // Write the table at the bottom of the page
            table.WriteSelectedRows(0, -1, 150f, document.Bottom, writer.DirectContent);
        }

        public override void OnCloseDocument(PdfWriter writer, Document document)
        {
            base.OnCloseDocument(writer, document);
        }
    }
}
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf

Namespace ConsoleApp1
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Create a new PDF document
			Dim doc As New Document()
			Dim writer As PdfWriter = PdfWriter.GetInstance(doc, New FileStream("output.pdf", FileMode.Create))

			' Open the document to add content
			doc.Open()
			doc.Add(New Paragraph("Hello, world!"))

			' Attach page number event to PDF writer
			writer.PageEvent = New PageNumberEventHandler()

			' Close the document
			doc.Close()
		End Sub
	End Class

	Public Class PageNumberEventHandler
		Inherits PdfPageEventHelper

		Public Overrides Sub OnOpenDocument(ByVal writer As PdfWriter, ByVal document As Document)
			MyBase.OnOpenDocument(writer, document)
		End Sub

		Public Overrides Sub OnEndPage(ByVal writer As PdfWriter, ByVal document As Document)
			MyBase.OnEndPage(writer, document)

			' Create a table to hold the page number
			Dim table As New PdfPTable(1)
			table.TotalWidth = 300F
			table.HorizontalAlignment = Element.ALIGN_CENTER

			Dim cell As New PdfPCell(New Phrase($"Page {writer.PageNumber}"))
			cell.Border = 0
			table.AddCell(cell)

			' Write the table at the bottom of the page
			table.WriteSelectedRows(0, -1, 150F, document.Bottom, writer.DirectContent)
		End Sub

		Public Overrides Sub OnCloseDocument(ByVal writer As PdfWriter, ByVal document As Document)
			MyBase.OnCloseDocument(writer, document)
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

首先,我們為DocumentPdfWriter建立一個新的對象,這樣就可以建立一個空白的 PDF 檔案。您可以在 PDF 文件中包含文字、照片、表格和其他類型的內容。 讓我們使用Paragraph來添加一些範例文字以作演示。 現在最重要的步驟是為PDF文件添加頁碼。 我們將使用 iTextSharp 的頁面事件來實現這一點。 我們首先定義一個繼承自PdfPageEventHelper類別的類,以便能夠重寫在 PDF 生成過程中發生特定事件時呼叫的方法。

此類重寫了OnEndPage函數,以新增包含目前頁碼的單一儲存格表格。 最後,在關閉文件之前,我們需要將PageNumberEventHandler類別的一個實例連接到PdfWriter物件。 透過這種配置,每次在 PDF 文件中新增頁面時,都會呼叫PageNumberEventHandler類別的OnEndPage函數,並在每頁底部新增頁碼。 我們也可以使用現有的PDF文件來新增頁碼。

How to Add Page Numbers in PDF using iTextSharp in C#:圖 3 - iTextSharp:輸出帶有頁碼的 PDF

結論

總而言之, IronPDF的專業性、易用性以及與 .NET 環境的無縫集成,使其成為需要 HTML 到 PDF 轉換及相關功能的場景的最佳選擇,儘管 iTextSharp 在 C# PDF 操作庫領域仍然是一個強大的競爭對手。 透過 IronPDF,您可以輕鬆、有效率且靈活地從 HTML 內容建立發票、報告和動態生成的文檔,從而在現代開發環境中取得成功。

IronPDF 的 Lite 版本中包含永久授權、升級選項以及一年的軟體維護服務。 水印試用期可讓使用者在實際設定中評估產品。 請造訪許可證頁面以了解更多詳情。 請造訪此網站以了解更多關於Iron Software的資訊。

常見問題解答

如何使用 C# 在 PDF 中加入頁碼?

您可以使用 IronPDF 在 PDF 中加入頁碼,方法是定義含頁碼占位符的 HTML 內容,並使用 AddHtmlFooters 方法將其套用為 PDF 中的頁尾。

使用 IronPDF 進行 PDF 操作有哪些優點?

IronPDF 提供強大的 PDF.NET Framework 功能,支援 HTML5、JavaScript、CSS 以及圖片到 PDF 的轉換,讓您可以輕鬆地以自訂的頁首和頁尾來處理 PDF。

iTextSharp 與 IronPDF 相比,在添加頁碼方面有何優勢?

iTextSharp 使用 PdfPageEventHelper 類來處理頁碼,而 IronPDF 則提供更簡單的方法,允許您定義含頁碼占位符的 HTML 頁腳。

我可以處理現有的 PDF 檔案以加入頁碼嗎?

是的,使用 IronPdf,您可以通過渲染帶有頁碼占位符的 HTML 頁腳,將其與原始文件合併,從而在現有 PDF 文件中添加頁碼。

將 HTML 轉換成 PDF 的首選方法是什麼?

IronPDF for .NET 可與 .NET 環境無縫整合,並能處理 HTML5、JavaScript 和 CSS,因此是 HTML 轉換為 PDF 的首選。

在 C# 專案中使用 IronPDF 的安裝步驟是什麼?

您可以使用 Visual Studio 中的 NuGet Package Manager 在 C# 專案中安裝 IronPDF,方法是搜尋「IronPDF」並將其加入專案中。

如何使用 C# 確保我的 PDF 有準確的頁數?

使用 IronPdf,透過定義含頁碼占位符的 HTML 模板,並將其一致地應用於所有 PDF 頁面,以確保您的頁碼正確無誤。

IronPDF 是否有授權選項?

IronPDF 提供「Lite」版,包含永久授權、升級選項和一年的軟體維護,以及水印試用期以供評估。

在哪裡可以找到使用 IronPDF 的詳細範例和說明文件?

使用 IronPDF 的全面說明文件和範例可在其官方網站 ironpdf.com 上找到。

IronPDF 是否與 .NET 10 完全相容?我可以在 .NET 10 專案中使用頁面編號功能嗎?

是的,IronPDF 支持 .NET 10,其所有功能(包括通过页眉或页脚中的占位符进行页码编号)在 .NET 10 项目中均可正常工作,无需任何特殊配置或变通方法。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。