Как добавить нумерацию страниц в PDF на C# и .NET

  1. Добавьте SautinSoft.Document из Nuget.
  2. Загрузите PDF-документ.
  3. Создайте два поля: Page и NumPages.
  4. Поместите его в нижний колонтитул.
  5. Сохраните документ.

Часто у нас есть документы, в которые необходимо внести какие-либо правки. Например, добавить нумерацию страниц в PDF-файл!

Этот пример кода поможет Вам добавить нумерацию страниц в существующий PDF-файл.

Например: У нас есть PDF-файл и нам нужно добавить Page Numbering

Формат нумерации: "Page N of M"

Мы помещаем номера наших страниц в нижний колонтитул, используя новый параграф.

 

            // Create a footer.
            HeaderFooter footer = new HeaderFooter(dc, HeaderFooterType.FooterDefault); 
 
            // Create a new paragraph to insert a page numbering. 
            // So that, our page numbering looks as: Page N of M. 
            Paragraph par = new Paragraph(dc); 
            par.ParagraphFormat.Alignment = HorizontalAlignment.Right; 
            CharacterFormat cf = new CharacterFormat() { FontName = "Consolas", Size = 14.0 }; 
            par.Content.Start.Insert("Page ", cf.Clone()); 
             
            

Следующий шаг - добавление двух полей: FieldType.Page и FieldType.NumPages


            // Page numbering is a Field. 
            Field fPage = new Field(dc, FieldType.Page); 
            fPage.CharacterFormat = cf.Clone(); 
            par.Content.End.Insert(fPage.Content); 
            par.Content.End.Insert(" of ", cf.Clone()); 
            Field fPages = new Field(dc, FieldType.NumPages); 
            fPages.CharacterFormat = cf.Clone(); 
            par.Content.End.Insert(fPages.Content); 
            footer.Blocks.Add(par);
             

Здесь Вы можете скачать исходный PDF файл и выходной результат.

Полный код

using System;
using System.Collections.Generic;
using System.Linq;
using SautinSoft.Document;

namespace Sample
{
    class Sample
    {
        static void Main(string[] args)
        {
            // Get your free 30-day key here:   
            // https://sautinsoft.com/start-for-free/

            AddPageNumbering();            
        }

        /// <summary>
        /// Add page numbering into an existing PDF document.
        /// </summary>
        /// <remarks>
        /// https://www.sautinsoft.com/products/document/help/net/developer-guide/add-page-numbering-in-pdf-net-csharp-vb.php
        /// </remarks>
        static void AddPageNumbering()
        {
            string inpFile = @"..\..\..\shrek.pdf";
            string outFile = @"With Pages.pdf";
            DocumentCore dc = DocumentCore.Load(inpFile);

            // We place our page numbers into the footer.
            // Therefore we've to create a footer.
            HeaderFooter footer = new HeaderFooter(dc, HeaderFooterType.FooterDefault);

            // Create a new paragraph to insert a page numbering.
            // So that, our page numbering looks as: Page N of M.
            Paragraph par = new Paragraph(dc);
            par.ParagraphFormat.Alignment = HorizontalAlignment.Right;
            CharacterFormat cf = new CharacterFormat() { FontName = "Consolas", Size = 14.0 };
            par.Content.Start.Insert("Page ", cf.Clone());

            // Page numbering is a Field.
            // Create two fields: FieldType.Page and FieldType.NumPages.
            Field fPage = new Field(dc, FieldType.Page);
            fPage.CharacterFormat = cf.Clone();
            par.Content.End.Insert(fPage.Content);
            par.Content.End.Insert(" of ", cf.Clone());
            Field fPages = new Field(dc, FieldType.NumPages);
            fPages.CharacterFormat = cf.Clone();
            par.Content.End.Insert(fPages.Content);
            footer.Blocks.Add(par);

            foreach (Section s in dc.Sections)
            {
                s.HeadersFooters.Add(footer.Clone(true));
            }
            dc.Save(outFile);

            // Open the results for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(inpFile) { UseShellExecute = true });
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
        }
    }
}

Download

Imports System
Imports System.IO
Imports SautinSoft.Document

Module Sample
    Sub Main()
        AddPageNumbering()
    End Sub
    ''' Get your free 30-day key here:   
    ''' https://sautinsoft.com/start-for-free/
    ''' <summary>
    ''' Add page numbering into an existing PDF document.
    ''' </summary>
    ''' <remarks>
    ''' https://www.sautinsoft.com/products/document/help/net/developer-guide/add-page-numbering-in-pdf-net-csharp-vb.php
    ''' </remarks>
    Sub AddPageNumbering()
        Dim inpFile As String = "..\..\..\shrek.pdf"
        Dim outFile As String = "With Pages.pdf"
        Dim dc As DocumentCore = DocumentCore.Load(inpFile)

        ' We place our page numbers into the footer.
        ' Therefore we've to create a footer.
        Dim footer As New HeaderFooter(dc, HeaderFooterType.FooterDefault)

        ' Create a new paragraph to insert a page numbering.
        ' So that, our page numbering looks as: Page N of M.
        Dim par As New Paragraph(dc)
        par.ParagraphFormat.Alignment = HorizontalAlignment.Right
        Dim cf As New CharacterFormat() With {
                .FontName = "Consolas",
                .Size = 14.0
            }
        par.Content.Start.Insert("Page ", cf.Clone())

        ' Page numbering is a Field.
        ' Create two fields: FieldType.Page and FieldType.NumPages.
        Dim fPage As New Field(dc, FieldType.Page)
        fPage.CharacterFormat = cf.Clone()
        par.Content.End.Insert(fPage.Content)
        par.Content.End.Insert(" of ", cf.Clone())
        Dim fPages As New Field(dc, FieldType.NumPages)
        fPages.CharacterFormat = cf.Clone()
        par.Content.End.Insert(fPages.Content)
        footer.Blocks.Add(par)

        For Each s As Section In dc.Sections
            s.HeadersFooters.Add(footer.Clone(True))
        Next s
        dc.Save(outFile)

        ' Open the results for demonstration purposes.
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(inpFile) With {.UseShellExecute = True})
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(outFile) With {.UseShellExecute = True})
    End Sub
End Module

Download


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



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

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