We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Find the number of pages in a section

Aspose Words can currently report the number of pages in a document. Can it report the number of pages in a section?

As discussed here I need to either (a) get the number of pages in a section or (b) be able to evaluate a Word Field which gets that number for me.

Hi

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your inquiry. If you need to calculate number of pages in the particular section, you can import this section into an empty document and calculate number of pages in this document. Please see the following code for instance:

//Open document with multiple sections

Document doc = new Document(@"Test123\in.doc");

//Loop thouht all sections

foreach (Section sect in doc.Sections)

{

//Create empty document

Document tmp = new Document();

tmp.RemoveAllChildren();

//Import section to the tmp document

Node tmpNode = tmp.ImportNode(sect, true, ImportFormatMode.KeepSourceFormatting);

//Insert section into the tmp document

tmp.AppendChild(tmpNode);

//Calculate number of pages in the setion

Console.WriteLine("Section {0} has {1} pages", doc.Sections.IndexOf(sect), tmp.PageCount);

}

Hope this helps.

Best regards.

Just FYI, we actually had a problem with the code above. We found that formatting, of a node in the source document, changed when we ran the code! It should not have affected the source document, but it did. (We are using Aspose 6.6 for .NET)

So we changed the code to this, instead:

Section sourceSection = ... // the section that we want to get the page count for
Document doc = (Document) sourceSection.ParentNode;
int indexOfSourceSection = doc.IndexOf(sourceSection);
if(indexOfSourceSection < 0)
throw new ArgumentException("Could not find section index number for section");

// clone the whole document, then remove all sections other than the one we want
Document tmp = doc.Clone(); // is a deep clone
var sectionsToRemove = tmp.Sections.OfType().Where(sec => tmp.IndexOf(sec) != indexOfSourceSection).ToList();
foreach (var sec in sectionsToRemove)
tmp.RemoveChild(sec);
if(tmp.Sections.Count != 1)
throw new Exception("Processed clone document does not have the expected one section");

// count the pages...


Hi John,

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thank you for additional information. It is perfect, that you found the solution of the problem. Please let me know in case of any issues, I will be glad to help you.

Best regards.