Articles in this section
Category / Section

Is it possible to fetch page numbers in a Word document using WinForms DocIO?

5 mins read

No, the Word document is a flow document in which contents (paragraphs, tables, etc.,) will not be preserved page by page; instead the contents will be preserved sequentially section by section. Word viewer/editor renders the contents of the Word document page by page dynamically when opened for viewing or editing. This page wise rendered information will not be preserved in the file level.

Syncfusion .NET Word library is a non-UI component that provides a full-fledged document object model to manipulate the Word document contents. Therefore, it is not feasible to fetch page numbers from a Word document using DocIO.

Alternatively, you can get the page number by following the steps below:

  1. Set the PAGE field in each section and keep each section as a separate page.
  2. Next, update the fields in the document programmatically using DocIO.
  3. Finally, locate the PAGE field and retrieve the updated result.

Steps to set page numbers in a Word document

  1. Create a new C# console application project.

Create console app in Visual Studio

  1. Install the Syncfusion.DocIO.Winforms NuGet package as a reference to your project from Nuget.org.

Add DocIO NuGet package reference to the project

Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering a Syncfusion license key in your application to use the components without trail message.

  1. Include the below code snippet to set page numbers in a Word document.
    C#
using System;
using System.Collections.Generic;
using System.IO;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;

VB.NET

Imports Syncfusion.DocIO
Imports Syncfusion.DocIO.DLS
  1. Include the below code snippet to set page numbers in a Word document.
    C#
string[] filePaths = {"../../../Data/Heading1Items.docx","../../../Data/Heading2Items.docx"};
//Open the file as Stream.
//Creates a new instance of WordDocument.
using (WordDocument document = new WordDocument())
{

    //Adds new section to the document.
    IWSection section1 = document.AddSection();
    //Inserts the default page header.
    IWParagraph paragraph = section1.HeadersFooters.OddHeader.AddParagraph();
    //Adds the new Page field in header with field name and its type
    IWField field1 = paragraph.AppendField("Page", FieldType.FieldPage);

    //Adds a paragraph to created section.
    paragraph = section1.AddParagraph();
    //Appends the text to the created paragraph.
    paragraph.AppendText("AdventureWorks Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company.");

    //Sets the section break.
    section1.BreakCode = SectionBreakCode.NewPage;

    IWSection section2 = document.AddSection();
    //Inserts the default page header.
    paragraph = section2.HeadersFooters.OddHeader.AddParagraph();
    //Adds the new Page field in header with field name and its type
    IWField field2 = paragraph.AppendField("Page", FieldType.FieldPage);


    //Updates the fields present in a document, to update page fields.
    document.UpdateDocumentFields(true);

    //Find and print the page numbers in the Word document.
    FindAndPrintPageNumbers(document);

    //Saves the Word document to file system.    
    using (FileStream outputStream = new FileStream(Path.GetFullPath(@"../../../Result.docx"), FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
    {
        document.Save(outputStream,FormatType.Docx);
    }
}

VB.NET

'Creates a new instance of WordDocument.
Using document As WordDocument = New WordDocument()

   'Adds new section to the document.
   Dim section1 As IWSection = document.AddSection()
   'Inserts the default page header.
   Dim paragraph As IWParagraph = section1.HeadersFooters.OddHeader.AddParagraph()
   'Adds the new Page field in header with field name and its type
   Dim field1 As IWField = paragraph.AppendField("Page", Syncfusion.DocIO.FieldType.FieldPage)

   'Adds a paragraph to created section.
   paragraph = section1.AddParagraph()
   'Appends the text to the created paragraph.
   paragraph.AppendText("AdventureWorks Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company.")

   'Sets the section break.
   section1.BreakCode = SectionBreakCode.NewPage

   Dim section2 As IWSection = document.AddSection()
   'Inserts the default page header.
   paragraph = section2.HeadersFooters.OddHeader.AddParagraph()
   'Adds the new Page field in header with field name and its type
   Dim field2 As IWField = paragraph.AppendField("Page", Syncfusion.DocIO.FieldType.FieldPage)


   'Updates the fields present in a document, to update page fields.
   document.UpdateDocumentFields()

   'Find and print the page numbers in the Word document.
   FindAndPrintPageNumbers(document)

   'Saves the Word document.    
   document.Save(Path.GetFullPath("../../Result.docx"), FormatType.Docx)
End Using
  1. Use the following methods to find and print the page numbers in a Word document.
    C#
/// <summary>
/// Finds and prints the page numbers in a Word document.
/// </summary>
private static void FindAndPrintPageNumbers(WordDocument document)
{
    //Find all page fields by EntityType in Word document.
    List<Entity> pageField = document.FindAllItemsByProperty(EntityType.Field, "FieldType", "FieldPage");

    if (pageField != null)
    {
        //Print the page numbers in the Word document.
        for (int i = 0; i < pageField.Count; i++)
        {
            Console.WriteLine((pageField[i] as WField).Text);
        }
    }
}

VB.NET

   ''' <summary>
   ''' Finds and prints the page numbers in a Word document.
   ''' </summary>
   Private Sub FindAndPrintPageNumbers(document As WordDocument)
       'Find all page fields by EntityType in Word document.
       Dim pageField As List(Of Entity) = document.FindAllItemsByProperty(EntityType.Field, "FieldType", "FieldPage")

       If pageField IsNot Nothing Then
           'Print the page numbers in the Word document.
           For i = 0 To pageField.Count - 1
               Console.WriteLine(TryCast(pageField(i), WField).Text)
           Next
       End If
   End Sub

A complete working sample to set page numbers in a Word documentt can be downloaded from GitHub.

Take a moment to peruse the documentation where you can find basic Word document processing options along with the features like mail mergemerge, split, and compare documents, find and replace text in the Word document, protect the Word documents, and most importantly, the PDF and Image conversions with code examples

Conclusion
I hope you enjoyed learning about how to set page numbers in a Word document using WinForms Word Library.

You can refer to our WinForms DocIO feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our WinForms DocIO documentation to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied