Skip to footer content
PRODUCT COMPARISONS

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

"Portable Document Format," or PDF, is a file format created by Adobe. PDFs come in handy when presenting documents that need to have their text and images formatted consistently. 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 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 content.
  5. Save the PDF file to your computer.

What is IronPDF

IronPDF is a robust PDF .NET Framework that developers use to easily create, view, and edit PDFs. IronPDF is a sophisticated tool that runs on a chromium engine internally. It can convert HTML5, JavaScript, CSS, and image 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 easily edit PDF files.
  • 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.
  • Extracting images from existing PDF files.
  • Including elements in a PDF: table, text, images, bookmarks, watermarks, headers, footers, and more.
  • Ability to split and combine pages from multiple PDF documents with ease.

To know more about the IronPDF documentation, refer here.

Installing IronPDF

Within 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 image 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 using the iText library.
  • We can also split a PDF document into several PDFs or merge multiple PDF documents into a single PDF using the iText library.
  • We can modify PDF forms with iText.

Install iTextSharp

Use the NuGet package manager to search 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 iText7
Install-Package itext7.pdfhtml
Install-Package iText7
Install-Package itext7.pdfhtml
SHELL

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 code below:

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        // Initialize the IronPdf renderer
        var renderer = new IronPdf.HtmlToPdf();

        // HTML content to convert to PDF
        string header = "<h1>Hello Ironpdf!</h1>";

        // Render the HTML content to PDF
        PdfDocument pdf = renderer.RenderHtmlAsPdf(header);

        // Define the footer with page number placeholders
        HtmlHeaderFooter htmlFooter = new HtmlHeaderFooter
        {
            HtmlFragment = "<center><i>{page} of {total-pages}</i></center>"
        };

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

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

class Program
{
    static void Main(string[] args)
    {
        // Initialize the IronPdf renderer
        var renderer = new IronPdf.HtmlToPdf();

        // HTML content to convert to PDF
        string header = "<h1>Hello Ironpdf!</h1>";

        // Render the HTML content to PDF
        PdfDocument pdf = renderer.RenderHtmlAsPdf(header);

        // Define the footer with page number placeholders
        HtmlHeaderFooter htmlFooter = new HtmlHeaderFooter
        {
            HtmlFragment = "<center><i>{page} of {total-pages}</i></center>"
        };

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

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

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Initialize the IronPdf renderer
		Dim renderer = New IronPdf.HtmlToPdf()

		' HTML content to convert to PDF
		Dim header As String = "<h1>Hello Ironpdf!</h1>"

		' Render the HTML content to PDF
		Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(header)

		' Define the footer with page number placeholders
		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 output PDF file
		pdf.SaveAs("output.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Explanation

  1. Initialize the Renderer: We create an instance of HtmlToPdf, which provides the HTML-to-PDF conversion feature.
  2. Define HTML Content: The HTML content that needs to be converted to a PDF is specified.
  3. Render HTML Content: The RenderHtmlAsPdf function is used to convert the HTML to a PDF document.
  4. Define Footer: Page numbers are represented as placeholders in the HTML footer text.
  5. Add Footer and Save PDF: Apply the footer to the document and save it as a 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 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 page numbers:

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 document = new Document();
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("output.pdf", FileMode.Create));

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

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

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

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

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

            // Add page number to the table cell
            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, 150, document.Bottom, writer.DirectContent);
        }
    }
}
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 document = new Document();
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("output.pdf", FileMode.Create));

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

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

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

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

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

            // Add page number to the table cell
            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, 150, document.Bottom, writer.DirectContent);
        }
    }
}
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 document As New Document()
			Dim writer As PdfWriter = PdfWriter.GetInstance(document, New FileStream("output.pdf", FileMode.Create))

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

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

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

	Public Class PageNumberEventHandler
		Inherits PdfPageEventHelper

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

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

			' Add page number to the table cell
			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, 150, document.Bottom, writer.DirectContent)
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

Explanation

  1. Create PDF Document: Initialize a new Document and PdfWriter to produce an empty PDF file.
  2. Add Content: Add basic content such as paragraphs to the document.
  3. Page Numbering: We utilize iTextSharp's event handling to include page numbers. We create a custom class inheriting from PdfPageEventHelper.
  4. Override OnEndPage: In the custom class, override the OnEndPage method to add page numbers at the bottom of each page.
  5. Close Document: Finalize the document by closing it.

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 generated 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 to learn more. For more details about Iron Software, visit their website.

Please note
iTextSharp is a registered trademark of its respective owner. This site is not affiliated with, endorsed by, or sponsored by iTextSharp. All product names, logos, and brands are property of their respective owners. Comparisons are for informational purposes only and reflect publicly available information at the time of writing.

Frequently Asked Questions

What is the purpose of using a PDF manipulation library in C#?

iTextSharp is used for creating and modifying PDF documents in C#. It offers features like encryption, PDF merging, text and image extraction, and adding page numbers to PDFs.

How do you add page numbers to a PDF using a PDF library?

To add page numbers using iTextSharp, you create a custom class inheriting from PdfPageEventHelper, override the OnEndPage method to insert page numbers, and attach this event to the PdfWriter.

What are the steps to add page numbers using a PDF library?

In IronPDF, you initialize the HtmlToPdf renderer, define the HTML footer with page number placeholders, add the footer to the PDF, and save the PDF file.

What are some key features of a PDF manipulation tool?

IronPDF allows creation, viewing, and editing of PDFs using .NET C# code. It supports HTML5, JavaScript, CSS conversion to PDF, and includes options for custom headers, footers, watermarks, and more.

How can a PDF library be installed in a C# project?

IronPDF can be installed using the NuGet Package Manager in Visual Studio. You can search for 'IronPDF' and install it directly into your project.

What sets one PDF library apart from another?

IronPDF specializes in HTML to PDF conversion and integrates seamlessly with .NET environments, making it ideal for dynamically generating documents from HTML content. It is robust and user-friendly for modern development needs.

Is there a trial version available for a PDF library?

Yes, IronPDF offers a watermarked trial period that allows users to assess the product in practical settings.

What functionalities does a PDF manipulation library provide?

iTextSharp provides functionalities such as generating PDF documents from HTML/XML, adding bookmarks and page numbers, and splitting or merging PDFs.

Can a PDF library handle HTML5 and JavaScript during PDF conversion?

Yes, IronPDF can convert HTML5 and JavaScript content to PDF, maintaining the layout and functionality as it appears in a browser.

What are the installation requirements for a PDF library?

To install iTextSharp, use the NuGet package manager to search for and install iText7 and itext7.pdfhtml, as these are required for its functionalities.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.