Remove Blank Lines in Word Document in Java

This article demonstrates how to remove blank lines/empty paragraphs in a Word document by using Spire.Doc for Java.

Below is the sample document which contains many blank lines:

Remove Blank Lines in Word Document in Java

import com.spire.doc.*;
import com.spire.doc.documents.*;

public class removeBlankLines {
    public static void main(String[] args) {

        //Load the sample document
        Document document = new Document();
        document.loadFromFile("sample.docx");

        //Traverse every section in the word document and remove the null and empty paragraphs
        for (Object sectionObj : document.getSections()) {
            Section section=(Section)sectionObj;
            for (int i = 0; i < section.getBody().getChildObjects().getCount(); i++) {
                if ((section.getBody().getChildObjects().get(i).getDocumentObjectType().equals(DocumentObjectType.Paragraph) )) {
                    String s= ((Paragraph)(section.getBody().getChildObjects().get(i))).getText().trim();
                    if (s.isEmpty()) {
                        section.getBody().getChildObjects().remove(section.getBody().getChildObjects().get(i));
                        i--;
                    }
                }
            }
        }
        
        //Save the document to file
        String result = "removeBlankLines.docx";
        document.saveToFile(result, FileFormat.Docx_2013);
    }
}

Remove Blank Lines in Word Document in Java