Calculate the total number of pages starting from the table of contents

Hello, may I ask if Word documents can calculate the total number of pages starting from the table of contents? Please use a code example. Thank you

@Mikeykiss You can use Document.PageCount property to get total page count in the document. Then you can use LayoutCollector to get page where TOC ends:

Document doc = new Document(@"C:\Temp\in.docx");
LayoutCollector collector = new LayoutCollector(doc);

// Get total page count of pages in the document.
int pageCount = doc.getPageCount();

// Get TOC field and get page index where TOC ends.
for (Field f : doc.getRange().getFields())
{
    if (f.getType() == FieldType.FIELD_TOC)
    {
        int tocEndPageIndex = collector.getEndPageIndex(f.End);
    }
}

@alexey.noskov Hello, may I ask if aspose. word for Java uses documentBuilder. insertField to insert nested domain code? I hope the domain code for the generated document will be as follows {={NUMPAGES \* MERGEFORMAT}-3}. Please use the code example. Thank you

@Mikeykiss You can use code like the following to insert nested fields:

Document doc = new Document();
DocumentBuilder docBuilder = new DocumentBuilder(doc);

// Insert formula field
Field formulaField = docBuilder.insertField(FieldType.FIELD_FORMULA, false);

// Move DocumentBuilder inside formula field code
docBuilder.moveTo(formulaField.getSeparator());
// Insert PAGE field.
docBuilder.insertField(FieldType.FIELD_PAGE, false);
// Continue writing formula
docBuilder.write("-3");

doc.updateFields();
doc.save("C:\\Temp\\out.docx");

很实用 谢谢提供的代码片段

1 Like