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.