Hi,
Please explain how to remove page break from document in case this is last element and no visible content after, even brak inside SDT or other object. Please see attached example.
Thanks.
Document doc = new Document();
doc.loadFromFile("test.docx");
// Get the body of the first section
Body body = doc.getSections().get(0).getBody();
// Get the last child object in the body (e.g., a Paragraph or StructureDocumentTag)
DocumentObject documentObject = body.getChildObjects().get(body.getChildObjects().getCount() - 1);
// Get the child objects of this last container
DocumentObjectCollection childObjects = documentObject.getChildObjects();
// Traverse child objects in reverse order to find the last paragraph
for (int j = childObjects.getCount() - 1; j >= 0; j--) {
DocumentObject sdtChild = childObjects.get(j);
// Check if the child is a Paragraph
if (sdtChild instanceof Paragraph) {
Paragraph paragraph = (Paragraph) sdtChild;
DocumentObjectCollection paraItems = paragraph.getChildObjects();
// If the paragraph contains items, check the last one
if (paraItems != null && paraItems.getCount() > 0) {
int lastIndex = paraItems.getCount() - 1;
DocumentObject lastParaItem = paraItems.get(lastIndex);
// If the last item is a page break, remove it
if (lastParaItem instanceof Break) {
paraItems.remove(lastParaItem);
System.out.println("Removed the page break at the end of the last paragraph.");
break; // Only process the first (i.e., last) paragraph found
}
}
break; // Exit after handling the first paragraph (which is the last one in reverse order)
}
}
doc.saveToFile("test_modified.docx");