How to Add Page Numbers in PDF using iTextSharp in C#

Introduction

"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 are going to compare the 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.
  • the process of removing pictures from already existing PDF files.
  • Including elements of a PDF: table, text, photos, bookmarks, watermarks, headers, footers, and others.
  • 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 in the image 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;
static void main(string[] args)
{ 
    var renderer = new IronPdf.HtmlToPdf();
    private string header = "<h1>Hello Ironpdf!<h1>";
    PdfDocument pdf = renderer.RenderHtmlAsPdf(header);
    HtmlHeaderFooter htmlFooter = new HtmlHeaderFooter()
    {
        HtmlFragment = "<center><i>{page} of {total-pages}<i></center>"
    };
    // Add footer
    pdf.AddHtmlFooters(htmlFooter);
    pdf.SaveAs("output.pdf");
}
using IronPdf;
static void main(string[] args)
{ 
    var renderer = new IronPdf.HtmlToPdf();
    private string header = "<h1>Hello Ironpdf!<h1>";
    PdfDocument pdf = renderer.RenderHtmlAsPdf(header);
    HtmlHeaderFooter htmlFooter = new HtmlHeaderFooter()
    {
        HtmlFragment = "<center><i>{page} of {total-pages}<i></center>"
    };
    // Add footer
    pdf.AddHtmlFooters(htmlFooter);
    pdf.SaveAs("output.pdf");
}
Imports IronPdf
Shared Sub main(ByVal args() As String)
	Dim renderer = New IronPdf.HtmlToPdf()
	private String header = "<h1>Hello Ironpdf!<h1>"
	Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(header)
	Dim htmlFooter As New HtmlHeaderFooter() With {.HtmlFragment = "<center><i>{page} of {total-pages}<i></center>"}
	' Add footer
	pdf.AddHtmlFooters(htmlFooter)
	pdf.SaveAs("output.pdf")
End Sub
VB   C#

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(document, new FileStream("output.pdf", FileMode.Create));
            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);
            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);
            table.WriteSelectedRows(0, -1, 150, 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(document, new FileStream("output.pdf", FileMode.Create));
            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);
            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);
            table.WriteSelectedRows(0, -1, 150, 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(document, New FileStream("output.pdf", FileMode.Create))
			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)
			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)
			table.WriteSelectedRows(0, -1, 150, 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
VB   C#

First, we are creating 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 the new paragraph to add some sample text for demonstration reasons. The important step is now to add page numbers to the PDF document. We'll use iTextSharp's page events to do this. To be able to override methods that are called when specific events happen during the PDF-generating process, let's first construct a class that inherits from the PdfPageEventHelper class.

The OnEndPage function is overridden in this class to add a table that has a single cell that contains 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 $749 Lite edition. The watermarked trial period allows users to assess the product in practical settings. Visit the license page. Go to this website to learn more about Iron Software.