Zum Fußzeileninhalt springen
PRODUKTVERGLEICHE

Wie man Seitenzahlen in PDF mit iTextSharp in C# hinzufügt

"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.

Hinweis: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.

Häufig gestellte Fragen

Wie kann ich mit iTextSharp in C# Seitenzahlen zu einem PDF hinzufügen?

Um mit iTextSharp in C# Seitenzahlen hinzuzufügen, können Sie eine benutzerdefinierte Klasse erstellen, die von PdfPageEventHelper erbt. Überschreiben Sie die OnEndPage-Methode, um Seitenzahlen einzufügen, und fügen Sie dieses Ereignis der PdfWriter-Instanz hinzu.

Warum sind PDFs in verschiedenen Sektoren entscheidend?

PDFs bewahren das konsistente Format von Text und Bildern, was für die Dokumentenerstellung und Rechnungsstellung wichtig ist. Sie sind zuverlässig für professionelle Dokumente.

Was sind die Vorteile der Verwendung von IronPDF für die PDF-Manipulation?

IronPDF bietet robuste Funktionen zum Erstellen, Ansehen und Bearbeiten von PDFs in .NET-Umgebungen. Es zeichnet sich durch das Konvertieren von HTML, JavaScript und Bildern in PDF aus und unterstützt benutzerdefinierte Kopf- und Fußzeilen sowie Wasserzeichen.

Kann IronPDF HTML-zu-PDF-Konvertierungen mit JavaScript-Unterstützung durchführen?

Ja, IronPDF kann HTML-Inhalte, einschließlich JavaScript, in PDFs umwandeln und dabei das Layout und die Funktionalität beibehalten, wie es in einem Webbrowser angezeigt wird.

Wie kann ich IronPDF in einem C#-Projekt installieren?

Sie können IronPDF mit dem NuGet-Paket-Manager in Visual Studio installieren. Suchen Sie einfach nach 'IronPDF' und fügen Sie es zu Ihrem Projekt hinzu, um seine Funktionen zu nutzen.

Was ist die Bedeutung der Testphase, die von IronPDF angeboten wird?

Die Testphase von IronPDF ermöglicht es Entwicklern, seine Funktionen und Funktionalitäten in realen Anwendungen mit einem wassergezeichneten Test zu erkunden, wodurch sie seine Eignung vor dem Kauf einer Lizenz beurteilen können.

Wie vergleicht sich iTextSharp mit IronPDF beim Hinzufügen von Seitenzahlen?

Während iTextSharp Ereignisbehandlung zum Hinzufügen von Seitenzahlen verwendet, bietet IronPDF einen einfacheren Ansatz mit HTML-Vorlagen für Kopf- und Fußzeilen, was es ideal für .NET-Entwickler macht, die nach Benutzerfreundlichkeit suchen.

Was sollte bei der Wahl einer PDF-Bibliothek für ein C#-Projekt berücksichtigt werden?

Berücksichtigen Sie die Funktionen, die jede Bibliothek bietet. Beispielsweise spezialisiert sich IronPDF auf HTML-zu-PDF-Konvertierung und integriert sich gut mit .NET-Frameworks, während iTextSharp starke Verschlüsselungs- und Textextraktionsmöglichkeiten bietet.

Ist iTextSharp mit .NET 10 kompatibel, um Seitenzahlen hinzuzufügen, oder sollte ich iText 7 verwenden?

iTextSharp (Version 5.x) ist offiziell veraltet und wird nur noch im Wartungsmodus weiterentwickelt. Es erhält lediglich Sicherheitsupdates, keine neuen Funktionen mehr. Da es nicht direkt für .NET 10 entwickelt wurde, kann die Verwendung in aktuellen .NET-Versionen zu Kompatibilitätsproblemen führen. Für neue Projekte oder solche, die auf .NET 10 aktualisieren, wird iText 7 (oder iText Core) dringend empfohlen, da es die neuesten Frameworks unterstützt und Verbesserungen gegenüber iTextSharp bietet. ([itextpdf.com](https://itextpdf.com/products/itextsharp?utm_source=openai))

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen