How to Add Page Numbers in PDF using 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#
- Create a new C# project using any IDE.
- Create a new PDF object.
- Add page numbers to the HTML footer.
- Create a PDF from HTML material.
- 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:
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
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.
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
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.
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.
Frequently Asked Questions
How can I add page numbers to a PDF using C#?
You can add page numbers to a PDF using IronPDF by defining HTML content with page number placeholders and using the AddHtmlFooters
method to apply it as a footer in your PDF.
What are the benefits of using IronPDF for PDF manipulation?
IronPDF offers robust PDF.NET framework capabilities, supporting HTML5, JavaScript, CSS, and image-to-PDF conversions, making it easy to manipulate PDFs with custom headers and footers.
How does iTextSharp compare to IronPDF for adding page numbers?
iTextSharp uses the PdfPageEventHelper
class to handle page numbers, whereas IronPDF provides a simpler approach by allowing you to define HTML footers with page number placeholders.
Can I manipulate existing PDF files to add page numbers?
Yes, using IronPDF, you can add page numbers to existing PDF files by rendering HTML footers with page number placeholders and merging them with the original document.
What is the preferred method for converting HTML to PDF?
IronPDF is preferred for HTML to PDF conversion due to its seamless integration with .NET environments and its ability to handle HTML5, JavaScript, and CSS.
What are the installation steps for using IronPDF in a C# project?
You can install IronPDF in a C# project using the NuGet Package Manager in Visual Studio by searching for 'IronPDF' and adding it to your project.
How do I ensure my PDFs have accurate page numbers using C#?
Using IronPDF, ensure your page numbers are accurate by defining an HTML template with page number placeholders and applying it consistently across all PDF pages.
Are there licensing options available for IronPDF?
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.
Where can I find detailed examples and documentation for using IronPDF?
Comprehensive documentation and examples for using IronPDF can be found on their official website at ironpdf.com.