We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Can't remove empty para at end of document

I’m trying to remove an empty paragraph at the end of my document which is unstyled or “Normal” style. I am using Aspose.Words.for.Java 14.12.0. My code is as follows, but for some reason the paragraph still appears in the output document. See attachments. Can you please let me know what I’m doing wrong? Thanks!

private void removeLastEmptyPara() throws Exception {
//Find and remove the last empty para in document:
Document mydocument = new Document(“C:\temp\filewithemptypara-input.docx”);
DocumentBuilder builder = new DocumentBuilder(mydocument);
Paragraph last = mydocument.getLastSection().getBody().getLastParagraph();
if(last != null && last.getParagraphFormat().getStyleName().equals(“Normal”) && last.getCount() == 0){
last.remove();
}
mydocument.save(“C:\temp\filewithoutemptypara-output.docx”);
}

Hi Linda,


Thanks for your inquiry. Please use following code example to achieve your requirements. Hope this helps you. Please let us know if you have any more queries.

Document doc = new Document(MyDir + “filewithemptypara-input.docx”);<o:p></o:p>

Paragraph last = doc.getLastSection().getBody().getLastParagraph();

if(doc.getLastSection().getBody().getParagraphs().getCount() == 1 && last.toString(SaveFormat.TEXT).trim().length() == 0)

doc.getLastSection().remove();

if(last != null && last.getParagraphFormat().getStyleName().equals("Normal") && last.getCount() == 0){

last.remove();

}

doc.save(MyDir + "Out.docx");