Search code examples
c#xmlopenxmldocxopenxml-sdk

Can't get the pages count from a word document with OpenXml


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 ?


Solution

  • 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?