Inserting Page Numbers in C# and .NET PDFs

Adding page numbers to a PDF document is a common requirement for both personal and professional documents. It helps in keeping the pages organized and enhances the navigability of the document.

In this article, we will look at the process of adding page numbers to an existing PDF document using PDF.NET.

  1. Add SautinSoft.Pdf from NuGet.
  2. Load a PDF document. Iterate by all pages.
  3. Draw the page numbering using "orange" color atop of all content.
  4. Save the document.

By following the steps outlined in this article, you can quickly implement page numbering in your PDF documents, enhancing their professionalism and readability.

Полный код

using System;
using System.IO;
using SautinSoft;
using SautinSoft.Pdf;
using SautinSoft.Pdf.Content;

namespace Sample
{
    class Sample
    {
        /// <summary>
        /// Add page numbers to a PDF document in C# and .NET
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/add-page-numbers-to-a-pdf-document-in-csharp-dotnet.php
        /// </remarks>
        static void Main(string[] args)
        {
            // Before starting this example, please get a free 100-day trial key:
            // https://sautinsoft.com/start-for-free/

            // Apply the key here:
            // PdfDocument.SetLicense("...");

            string inpFile = Path.GetFullPath(@"..\..\..\Wine turism.pdf");
            string outFile = Path.GetFullPath("Result.pdf");

            using (PdfDocument document = PdfDocument.Load(inpFile))
            {
                // Iterate by all pages
                int pageNum = 1;
                foreach (var page in document.Pages)
                {
                    // Draw the page numbering atop of all.
                    // The method PdfContent(PdfContentGroup).DrawText always adds text to the end of the content.
                    using (var formattedText = new PdfFormattedText())
                    {
                        formattedText.Font = new PdfFont(new PdfFontFace("Helvetica"), 16.0);
                        // Set "orange" color
                        formattedText.Color = PdfColor.FromRgb(1, 0.647, 0);
                        formattedText.AppendLine($"Page {pageNum++}");
                        page.Content.DrawText(formattedText, new PdfPoint((page.CropBox.Width / 2) - formattedText.Width, page.CropBox.Height - 50));

                        // Because of the trial version, we'll add page numbers only to two pages.
                        if (pageNum > 2)
                            break;
                    }
                }
                document.Save(outFile);
            }
            // Show the result.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
        }
    }
}

Download

Option Infer On

Imports System
Imports System.IO
Imports SautinSoft
Imports SautinSoft.Pdf
Imports SautinSoft.Pdf.Content

Namespace Sample
	Friend Class Sample
		''' <summary>
		''' Add page numbers to a PDF document in C# and .NET
		''' </summary>
		''' <remarks>
		''' Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/add-page-numbers-to-a-pdf-document-in-csharp-dotnet.php
		''' </remarks>
		Shared Sub Main(ByVal args() As String)
			' Before starting this example, please get a free license:
			' https://sautinsoft.com/start-for-free/

			' Apply the key here:
			' PdfDocument.SetLicense("...");

			Dim inpFile As String = Path.GetFullPath("..\..\..\Wine turism.pdf")
			Dim outFile As String = Path.GetFullPath("Result.pdf")

			Using document As PdfDocument = PdfDocument.Load(inpFile)
				' Iterate by all pages
				Dim pageNum As Integer = 1
				For Each page In document.Pages
					' Draw the page numbering atop of all.
					' The method PdfContent(PdfContentGroup).DrawText always adds text to the end of the content.
					Using formattedText = New PdfFormattedText()
						formattedText.Font = New PdfFont(New PdfFontFace("Helvetica"), 16.0)
						' Set "orange" color
						formattedText.Color = PdfColor.FromRgb(1, 0.647, 0)
' INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
' ORIGINAL LINE: formattedText.AppendLine(string.Format("Page {0}", pageNum++));
						formattedText.AppendLine($"Page {pageNum}")
						pageNum += 1
						page.Content.DrawText(formattedText, New PdfPoint((page.CropBox.Width \ 2) - formattedText.Width, page.CropBox.Height - 50))

						' Because of the trial version, we'll add page numbers only to two pages.
						If pageNum > 2 Then
							Exit For
						End If
					End Using
				Next page
				document.Save(outFile)
			End Using
			' Show the result.
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(outFile) With {.UseShellExecute = True})
		End Sub
	End Class
End Namespace

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.