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

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

Полный код

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/

            EditPageNumbering();
        }

        /// <summary>
        /// How to edit Page Numbering in an existing DOCX document. 
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/edit-page-numbering-in-docx-document-net-csharp-vb.php
        /// </remarks>
        public static void EditPageNumbering()
        {
            // Modify the Page Numbering from: "Page N of M" to "Página N".
            string inpFile = @"..\..\..\PageNumbering.docx";
            string outFile = @"PageNumbering-modified.pdf";

            // Load a DOCX document with Page Numbering (PageNumbering.docx).
            DocumentCore dc = DocumentCore.Load(inpFile);
            Section s = dc.Sections[0];

            foreach (HeaderFooter hf in s.HeadersFooters)
            {
                foreach (Field field in hf.GetChildElements(true, ElementType.Field).Reverse())
                {
                    // Page numbering is a Field,
                    // so we have to find the fields with the type Page or NumPages and remove.
                    if (field.FieldType == FieldType.Page || field.FieldType == FieldType.NumPages)
                    {
                        // Save the paragraph containing the page numbering and character formatting.
                        Paragraph parWithNumbering = null;
                        CharacterFormat cf = field.CharacterFormat.Clone();

                        // Also assume that our page numbering located in a paragraph,
                        // so let's remove the paragraph's content too.
                        if (field.Parent is Paragraph)
                        {
                            parWithNumbering = (field.Parent as Paragraph);
                            // If we'll delete only the fields (field.Content.Delete()), our paragraph
                            // may contain text "Page of ".
                            // Based on this, we remove all items in this paragraph.
                            // Fields {Page} and {NumPages} will be also deleted here, because they are Inlines too.
                            parWithNumbering.Inlines.Clear();
                        }

                        if (parWithNumbering != null)
                        {
                            // Insert new Page Numbering: "Página N":                        
                            // Insert "Página ".
                            parWithNumbering.Inlines.Add(new Run(dc, "Página ", cf.Clone()));
                            // Insert field {Page}.
                            Field fPage = new Field(dc, FieldType.Page);
                            fPage.CharacterFormat = cf.Clone();
                            parWithNumbering.Inlines.Add(fPage);
                        }
                    }
                }
            }
            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 System.Collections.Generic
Imports System.Linq
Imports SautinSoft.Document

Module Sample
    Sub Main()
        EditPageNumbering()
    End Sub
    ''' Get your free 30-day key here:   
    ''' https://sautinsoft.com/start-for-free/
    ''' <summary>
    ''' How to edit Page Numbering in an existing DOCX document. 
    ''' </summary>
    ''' <remarks>
    ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/edit-page-numbering-in-docx-document-net-csharp-vb.php
    ''' </remarks>
    Sub EditPageNumbering()
        ' Modify the Page Numbering from: "Page N of M" to "Página N".
        Dim inpFile As String = "..\..\..\PageNumbering.docx"
        Dim outFile As String = "PageNumbering-modified.pdf"

        ' Load a DOCX document with Page Numbering (PageNumbering.docx).
        Dim dc As DocumentCore = DocumentCore.Load(inpFile)
        Dim s As Section = dc.Sections(0)

        For Each hf As HeaderFooter In s.HeadersFooters
            For Each field As Field In hf.GetChildElements(True, ElementType.Field).Reverse()
                ' Page numbering is a Field,
                ' so we have to find the fields with the type Page or NumPages and remove.
                If field.FieldType = FieldType.Page OrElse field.FieldType = FieldType.NumPages Then
                    ' Save the paragraph containing the page numbering and character formatting.
                    Dim parWithNumbering As Paragraph = Nothing
                    Dim cf As CharacterFormat = field.CharacterFormat.Clone()

                    ' Also assume that our page numbering located in a paragraph,
                    ' so let's remove the paragraph's content too.
                    If TypeOf field.Parent Is Paragraph Then
                        parWithNumbering = (TryCast(field.Parent, Paragraph))
                        ' If we'll delete only the fields (field.Content.Delete()), our paragraph
                        ' may contain text "Page of ".
                        ' Based on this, we remove all items in this paragraph.
                        ' Fields {Page} and {NumPages} will be also deleted here, because they are Inlines too.
                        parWithNumbering.Inlines.Clear()
                    End If

                    If parWithNumbering IsNot Nothing Then
                        ' Insert new Page Numbering: "Página N":                        
                        ' Insert "Página ".
                        parWithNumbering.Inlines.Add(New Run(dc, "Página ", cf.Clone()))
                        ' Insert field {Page}.
                        Dim fPage As New Field(dc, FieldType.Page)
                        fPage.CharacterFormat = cf.Clone()
                        parWithNumbering.Inlines.Add(fPage)
                    End If
                End If
            Next field
        Next hf
        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. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.