Delete all Empty Paragraphs & Table of Contents from Start of Word DOCX Document | Java

image.png (73.8 KB)

String content = StrUtil.cleanBlank(MyStringUtils.getString(paragraph.getText()));
if (StrUtil.isBlank(content) || paragraph.getChildNodes().getCount() == 0){
    section.getBody().getParagraphs().remove(paragraph);
}

You cannot delete the blank line before the paragraph with the code above

test.docx (11.6 KB)

This is my word document, I hope to provide the corresponding deletion code

@qazwsxedcrfv123,

You can use the following code of Aspose.Words for Java API to remove all empty Paragraphs from the start of Word DOCX document.

Document doc = new Document("c:\\temp\\test.docx");

for (Paragraph para : (Iterable<Paragraph>)
        doc.getFirstSection().getBody().getChildNodes(NodeType.PARAGRAPH, true))
    if (para.toString(SaveFormat.TEXT).replace((char) 160, ' ').trim().equals(""))
        para.remove();
    else
        break;
    
doc.save("c:\\temp\\awjava-21.7.docx");

oa.docx (13.3 KB)
image.png (24.6 KB)

If there is a table of contents before my paragraph, I cannot locate my paragraph through “doc.getFirstSection()”, how should I locate my paragraph and then delete the blanks.
Thank you very much for your reply

for (Section section : doc.getSections()) {
            for (Paragraph para : (Iterable<Paragraph>) section.getBody().getChildNodes(NodeType.PARAGRAPH, true)){
                System.out.println("para ===== "+para.getText());
                if (para.toString(SaveFormat.TEXT).replace((char) 160, ' ').trim().equals("")) {
                    System.out.println("para ===== "+para.getText());
                    para.remove();
                } else {
                    break;
                }
            }
        }

I tried to use this method doc.getSections() to get Sections, but doc.getSections() .getCount() = 1, why is that, my word has two pages

@qazwsxedcrfv123,

Do you also want to delete Table of Content along with empty paragraphs? Please also provide your expected Word DOCX file showing the desired output here for our reference. You can create this file manually by using MS Word. We will then start further investigation into your particular scenario and provide you code to achieve the same output by using Aspose.Words.