Добавление номеров страниц в PDF-документе на C# и .NET

Добавление номеров страниц в PDF-документ — распространённая задача как для личных, так и для профессиональных документов. Это помогает упорядочить страницы и улучшить навигацию по документу.

В этой статье мы рассмотрим процесс добавления номеров страниц в существующий PDF-документ с помощью SautinSoft.Pdf.

Пошаговое руководство:

  1. Добавить SautinSoft.PDF из NuGet.
  2. Загрузить a PDF-документ. Выполните итерацию по всем страницам.
  3. Нарисовать нумерацию страниц оранжевым цветом поверх всего содержимого..
  4. Сохранить документ.

Полный код

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


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу support@sautinsoft.ru или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



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

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