Test in production without watermarks.
Works wherever you need it to.
Get 30 days of fully functional product.
Have it up and running in minutes.
Full access to our support engineering team during your product trial
"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.
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.
To know more about the IronPDF documentation, refer here.
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:
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.
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.
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 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
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.
To learn more about the IronPDF code, refer here.
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
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.
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.
Adding page numbers to a PDF enhances navigation and allows for easy reference, especially in multi-page documents.
You can add page numbers using IronPDF by defining an HTML footer with page number placeholders and adding it to the PDF using the AddHtmlFooters method.
Install IronPDF using NuGet Package Manager in Visual Studio by searching for 'IronPDF' and selecting the package to add to your project.
Yes, IronPDF allows you to add page numbers to both new and existing PDF files by rendering HTML footers with page number placeholders.
iTextSharp is a library for producing and modifying PDF documents in C#. It supports features like encryption, PDF merging, and adding page numbers using page events.
In iTextSharp, you add page numbers by creating a PdfWriter instance, then overriding the OnEndPage method to insert page numbers at the bottom of each page.
IronPDF supports HTML to PDF conversion, adding custom headers and footers, extracting images, and combining PDF documents, among other features.
IronPDF is preferred for HTML to PDF conversion due to its specialization and seamless integration with .NET environments, whereas iTextSharp is a strong competitor for general PDF manipulation.
IronPDF offers a 'Lite' edition with a permanent license, upgrade options, and a year of software maintenance, along with a watermarked trial period for evaluation.
Comprehensive documentation and examples for IronPDF can be found on their official website at ironpdf.com.