5

I am using below code to get the page count but it is not giving actual page count(PFA). What is the better way to get the total pages count?

var pageCount = doc.ExtendedFilePropertiesPart.Properties.Pages.Text.Trim();

Wrong page count

Actual pages are 10

Note: We cannot use the Office Primary Interop Assemblies in my Azure web app service

Thanks in advance.

Cindy Meister
  • 25,071
  • 21
  • 34
  • 43
Ganapathi D
  • 81
  • 1
  • 5
  • there are various libraries such as Aspose that can be used to calculate the page number without PIA, but I am not aware of any free alternatives. – Slai Nov 27 '18 at 17:01

2 Answers2

4

In theory, the following property can return that information from the Word Open XML file, using the Open XML SDK:

int pageCount = (int) document.ExtendedFilePropertiesPart.Properties.Pages.Text;

In practice, however, this isn't reliable. It might work, but then again, it might not - it all depends on 1) What Word managed to save in the file before it was closed and 2) what kind of editing may have been done on the closed file.

The only sure way to get a page number or a page count is to open a document in the Word application interface. Page count and number of pages is calculated dynamically, during editing, by Word. When a document is closed, this information is static and not necessarily what it will be when the document is open or printed.

See also https://github.com/OfficeDev/Open-XML-SDK/issues/22 for confirmation.

Cindy Meister
  • 25,071
  • 21
  • 34
  • 43
  • 1
    in addition the property is not "correct" if the document is not viewed or saved in the default Word Print Layout view. For example, it is always 1 page if the document is viewed or saved in Word Web Layout view. – Slai Nov 27 '18 at 17:08
3

This code worked for me. It adds "Page X of Y" to the document.

para = new Paragraph(new Run(
       new Text() { Text = "Page ", Space = SpaceProcessingModeValues.Preserve },
       new SimpleField() { Instruction = "PAGE" }, 
       new Text() { Text = " of ", Space = SpaceProcessingModeValues.Preserve },  
       new SimpleField() { Instruction = "NUMPAGES \\*MERGEFORMAT" }));
Sohaib Afzal
  • 105
  • 1
  • 9