2

I use the OpenXML SDK v2.11.3 with .net core 3.1 and when I try to get the total pages count from a word document sometimes it returns a null value.

using (var document = WordprocessingDocument.Open(memoryStream, true))
{​​​​
    var pages = Convert.ToInt32(document.ExtendedFilePropertiesPart.Properties.Pages.Text);
}

System.NullReferenceException: 'Object reference not set to an instance of an object.' DocumentFormat.OpenXml.ExtendedProperties.Properties.Pages.get returned null.

What is the best way to get the total pages count from a docx file ?

kjhughes
  • 106,133
  • 27
  • 181
  • 240
G.Mich
  • 1,607
  • 2
  • 24
  • 42

1 Answers1

1

Since

  1. pagination is a dynamic property dependent upon rendering,
  2. any given DOCX file may or may not have ever been rendered, and
  3. OpenXML SDK does not render or perform calculations needed for rendering,

you cannot necessarily obtain a page count from an arbitrary DOCX file.

For further details and some limited work-arounds, see How to access OpenXML content by page number?

kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • Thanks for your time. I can't understand why sometimes in specific docx files it's works... – G.Mich Nov 13 '20 at 16:52
  • It's going to depend upon the history of the document and perhaps the implementation of the programs that have last manipulated the document. At one extreme, for example, you could create a DOCX file programmatically, never open it in Word, and find it will not know how many pages it will be when rendered for the first time. – kjhughes Nov 13 '20 at 17:56