Remove last page if it's body does not contain any text


I have a doucment with Empty Page at last .

I would like to remove that empty page at last and return remaining document using java.

Please let me know ,which is the optimal solution for this.

PFA source.docx and expected.docx (22.2 KB)


You can build on the following code that removes the empty Paragraphs from the end of document. In this case, this will also remove the empty blank page.

Document doc = new Document("E:\\Temp\\Data\\source.docx");

Section lastSec = doc.getLastSection();
Paragraph para = (Paragraph) lastSec.getBody().getLastParagraph();
while (para != null && para.toString(SaveFormat.TEXT).trim().equals("")) {
    para = (Paragraph) lastSec.getBody().getLastParagraph();