跳過到頁腳內容
使用IRONPDF

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

"Portable Document Format," or PDF, is a file format created by Adobe. PDFs come in handy when presenting papers that need to have their text and photos formatted. In the current world, PDF files are essential and are utilized for document creation and invoicing across all corporate sectors. Thanks to the several PDF libraries that are now on the market, creating PDFs has become practically instinctive. To choose the appropriate PDF library for you, it is crucial to weigh the benefits and characteristics of each before utilizing one for your project.

In this article, we are going to see how to add page numbers in PDF using iTextSharp C#. Also, we will compare iTextSharp with IronPDF.

How to Add Page Numbers in PDF using iTextSharp C#

  1. Create a new C# project using any IDE.
  2. Create a new PDF object.
  3. Add page numbers to the HTML footer.
  4. Create a PDF from HTML material.
  5. Save a PDF file to your computer.

What is IronPDF

IronPDF is a robust PDF .NET Framework that developers use to produce, view, and edit PDFs with ease. IronPDF is a sophisticated tool that runs on a chromium engine internally. It can convert HTML5, JavaScript, CSS, and picture files to PDF, add custom Headers and Footers, and produce PDFs precisely as they appear in a browser. Many online and net formats, including HTML, ASPX, Razor View, and MVC, are supported by IronPDF.

IronPDF Features

  • Utilizing .NET C# code to create, read, and simply edit PDF files.
  • The process of creating PDFs from a website URL link while managing User-Agents, Proxies, Cookies, HTTP headers, and form variables to enable login using HTML login forms.
  • Removing images from already existing PDF files.
  • Including elements of a PDF: table, text, photos, bookmarks, watermarks, headers, footers, and others.
  • The ability to separate and combine pages of numerous PDF documents with ease.

To know more about the IronPDF documentation, refer here.

Installing IronPDF

Within the Visual Studio Tools, select the NuGet Package Manager, and you can find the Visual Command-Line interface under Tools. The command below should be entered into the package management terminal tab.

Install-Package IronPdf

Or we can use the Package manager method. Installing the package straight into the solution is possible with Visual Studio's NuGet Package Manager option. A search box is available for locating packages on the NuGet website. We only need to look for "IronPDF" in the package manager, as the screenshot below illustrates:

How to Add Page Numbers in PDF using iTextSharp in C#: Figure 1 - Installing IronPDF from the package manager

The list of relevant search results is displayed above. For the package to be installed on your system, please make the necessary selections.

Now that the package has been downloaded and installed, it may be utilized in the current project.

What is iTextSharp

iTextSharp is a flexible library for producing and modifying PDF documents in C#. It offers several features, such as encryption, PDF merging, text and picture extraction, and much more. iTextSharp is an efficient tool for numerous tasks, including adding page numbers to PDFs.

iTextSharp features

  • An API to generate PDF documents is available through the iText library.
  • Both HTML and XML strings may be parsed into PDF files using the iText program.
  • We may add bookmarks, page numbers, and markers to our PDF documents by using the iText library.
  • We can also split a PDF document into numerous PDFs or merge multiple PDF documents into a single PDF by using the iText library.
  • We can modify PDF forms with iText.

Install iTextSharp

Use the NuGet package manager to look for iText. iText7 and iText.pdfhtml are required installations since iText functionalities are divided across many packages.

Should you choose the Visual Command-Line interface, the following packages need to be installed:

Install-Package iTextSharp

Since iText 7 is the most recent version, it is the one we are employing in our solution.

Adding Page Numbers using IronPDF

Adding page numbers to PDF files is made simple through IronPDF's comprehensive library. To illustrate, see the below code.

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

First, we define the HTML text that has to be turned into a PDF. This HTML content may consist of a single HTML paragraph or an entire HTML page. Next, we make an instance of the HtmlToPdf class, which offers the HTML-to-PDF conversion function RenderHtmlAsPdf.

The HTML content is passed as an argument to the RenderHtmlAsPdf function. We specify the HTML material that has to be turned into a PDF. Page numbers are represented as placeholders, or the {page} of {total-pages} in the footer portion of this HTML text.

The created PDF document is returned by this method as a PdfDocument object. Using the SaveAs method, we save the PDF document to a file with the name "output.pdf". Alternatively, we can use the OpenInDefaultPDFViewer function to open the created PDF document with the system's default PDF reader. We can also use the above method to add page numbers to an existing PDF file.

How to Add Page Numbers in PDF using iTextSharp in C#: Figure 2 - IronPDF: Outputted PDF with page numbers

To learn more about the IronPDF code, refer here.

Adding Page Numbers using iTextSharp

First, let's use iTextSharp to generate a new PDF document. Here's a basic illustration of how to make a new PDF document with a page number:

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

First, we create a new object for Document and PdfWriter, which allows us to create an empty PDF file. You may include text, photos, tables, and other types of material in your PDF document. Let's use a Paragraph to add some sample text for demonstration purposes. The important step is now to add page numbers to the PDF document. We'll use iTextSharp's page events for this. We start by defining a class that inherits from the PdfPageEventHelper class to be able to override methods that are called when specific events happen during the PDF-generating process.

The OnEndPage function is overridden in this class to add a table that has a single cell containing the current page number. Lastly, before we close the document, we need to connect an instance of our PageNumberEventHandler class to the PdfWriter object. With this configuration, the PageNumberEventHandler class's OnEndPage function will be called each time a new page is added to the PDF document, adding the page number at the bottom of each page. We can also use an existing PDF document to add page numbers.

How to Add Page Numbers in PDF using iTextSharp in C#: Figure 3 - iTextSharp: Outputted PDF with page numbers

Conclusion

In summary, IronPDF's specialization, usability, and seamless integration with .NET environments position it as the best option for scenarios requiring HTML to PDF conversion and related functionalities, even though iTextSharp is still a strong competitor in the landscape of C# PDF manipulation libraries. With IronPDF, you can create invoices, reports, and dynamically produced documents from HTML content with the ease, effectiveness, and adaptability required to succeed in the modern development environment.

A permanent license, upgrade options, and a year of software maintenance are all included in IronPDF's Lite edition. The watermarked trial period allows users to assess the product in practical settings. Visit the license page for more details. Go to this website to learn more about Iron Software.

常見問題解答

如何使用 C# 為 PDF 新增頁碼?

您可以使用 IronPDF 為 PDF 新增頁碼,方法是定義具有頁碼佔位符的 HTML 內容,然後使用AddHtmlFooters方法將其作為頁腳套用到 PDF 中。

使用 IronPDF 進行 PDF 處理有哪些好處?

IronPDF 提供強大的 PDF.NET 框架功能,支援 HTML5、JavaScript、CSS 和圖像到 PDF 的轉換,使用戶能夠輕鬆地使用自訂頁首和頁尾來操作 PDF。

iTextSharp 在新增頁碼方面與 IronPDF 相比如何?

iTextSharp 使用PdfPageEventHelper類別來處理頁碼,而 IronPDF 提供了一種更簡單的方法,可讓您定義具有頁碼佔位符的 HTML 頁尾。

我可以修改現有的PDF檔案來新增頁碼嗎?

是的,使用 IronPDF,您可以透過渲染帶有頁碼佔位符的 HTML 頁腳並將其與原始文件合併,為現有的 PDF 文件添加頁碼。

將 HTML 轉換為 PDF 的最佳方法是什麼?

IronPDF 是 HTML 轉換 PDF 的首選工具,因為它與 .NET 環境無縫集成,並且能夠處理 HTML5、JavaScript 和 CSS。

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

您可以使用 Visual Studio 中的 NuGet 套件管理器在 C# 專案中安裝 IronPDF,只需搜尋「IronPDF」並將其新增至您的專案即可。

如何使用 C# 確保我的 PDF 檔案擁有準確的頁碼?

使用 IronPDF,透過定義具有頁碼佔位符的 HTML 範本並一致地套用至所有 PDF 頁面,確保頁碼準確無誤。

IronPDF有哪些授權許可選項?

IronPDF 提供“精簡版”,包含永久授權、升級選項和一年的軟體維護,以及帶有浮水印的試用期供評估。

在哪裡可以找到使用 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 機器人,結合科技與創意的樂趣。