Get Total Number of Pages in any Section of Word DOCX Document using Java | Page Count | SECTIONPAGES Field

Hi - we have been trying to reliably get the page count of a given section in a document. Here is the code we have been using:

public Document copy(Document source, int sectionIndex) throws Exception {
try {
Section sourceSection = source.getSections().get(sectionIndex).deepClone();
Document target = newDoc();
target.appendChild(target.importNode(sourceSection, true,
ImportFormatMode.USE_DESTINATION_STYLES));
return target;
} catch (Exception e) {
throw new
HacpsException(ErrorKey.PAGE_COUNT_FAIL_CLONING_SECTION,
e);
}
}

We then use target.getPageCount() in another method. A problem arises when there is a section break (next page) at the very end of the last page in the section - we end up seeing an extraneous paragraph appended to the end of the section and there is a resulting blank page. This throws off the page count as the original document did not have this extra page.

I have tried stripping off empty paragraphs from the newly created document but this has not remedied the problem.

private Document removeBlanksAtEndOfDocument(Document doc) throws Exception {		
		if (doc.getLastSection().getBody().getLastParagraph().getText().trim().isEmpty()) {
			doc.getLastSection().getBody().getLastParagraph().remove();
		}
		return doc;
	}

Any insights as to what we may be doing incorrectly would be greatly appreciated.

@troy.l.parrish,

Please try using the following Java code to get Page Count of a given Section in Word Document:

int sectionIndex = 2;
Document doc = new Document("E:\\Temp\\in.docx");

Document tempDoc = (Document) doc.deepClone(true);
tempDoc.removeAllChildren();

Section targetSection = (Section) tempDoc.importNode(doc.getSections().get(sectionIndex), true);
tempDoc.appendChild(targetSection);

System.out.println(tempDoc.getPageCount()); 

Hope, this helps.

@awais.hafeez
Is the deep clone required at this point? What value does it give compared to shallow cloning?

@PROCUREMENT2,

Please follow your other thread for further proceedings.