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#
- 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 content.
- 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:
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
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
Explanation
- Initialize the Renderer: We create an instance of
HtmlToPdf
, which provides the HTML-to-PDF conversion feature. - Define HTML Content: The HTML content that needs to be converted to a PDF is specified.
- Render HTML Content: The
RenderHtmlAsPdf
function is used to convert the HTML to a PDF document. - Define Footer: Page numbers are represented as placeholders in the HTML footer text.
- Add Footer and Save PDF: Apply the footer to the document and save it as a PDF file.
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
Explanation
- Create PDF Document: Initialize a new
Document
andPdfWriter
to produce an empty PDF file. - Add Content: Add basic content such as paragraphs to the document.
- Page Numbering: We utilize iTextSharp's event handling to include page numbers. We create a custom class inheriting from
PdfPageEventHelper
. - Override
OnEndPage
: In the custom class, override theOnEndPage
method to add page numbers at the bottom of each page. - Close Document: Finalize the document by closing it.
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.
Frequently Asked Questions
How can I add page numbers to a PDF using iTextSharp in C#?
To add page numbers using iTextSharp in C#, you can create a custom class that inherits from PdfPageEventHelper
. Override the OnEndPage
method to insert page numbers and attach this event to the PdfWriter
instance.
Why are PDFs crucial in various sectors?
PDFs maintain consistent formatting of text and images, which is essential for document creation and invoicing across corporate sectors. They are reliable for presenting documents in a professional manner.
What are the advantages of using IronPDF for PDF manipulation?
IronPDF offers robust features for creating, viewing, and editing PDFs within .NET environments. It excels in converting HTML, JavaScript, and images to PDF and supports custom headers, footers, and watermarks.
Can IronPDF handle HTML to PDF conversion with JavaScript support?
Yes, IronPDF can convert HTML content, including JavaScript, into PDFs while maintaining the layout and functionality as it appears in a web browser.
How can I install IronPDF in a C# project?
You can install IronPDF using the NuGet Package Manager in Visual Studio. Simply search for 'IronPDF' and add it to your project to begin using its features.
What is the significance of the trial period offered by IronPDF?
IronPDF's trial period allows developers to explore its features and functionality in real-world applications with a watermarked trial, helping them assess its suitability before purchasing a license.
How does iTextSharp compare to IronPDF for adding page numbers?
While iTextSharp uses event handling for adding page numbers, IronPDF provides a more straightforward approach with HTML templates for headers and footers, making it ideal for .NET developers seeking ease of use.
What should be considered when choosing a PDF library for a C# project?
Consider the features each library offers. For instance, IronPDF specializes in HTML to PDF conversion and integrates well with .NET frameworks, while iTextSharp offers strong encryption and text extraction capabilities.