DEV Community

CodeSharing
CodeSharing

Posted on

Remove Blank Lines in Word Document in Java

There may be some blank lines/empty paragraphs left in the process of processing our Word documents, and it must be time-consuming if you manually remove these blank lines. Therefore, this article will introduce a simple solution to batch remove these blank lines/empty paragraphs with Free Spire.Doc for Java.

Installation
Method 1: Download the Free Spire.Doc for Java and unzip it. Then add the Spire.Doc.jar file to your Java application as dependency.

Method 2: You can also add the jar dependency to maven project by adding the following configurations to the pom.xml.

<repositories>
   <repository>
      <id>com.e-iceblue</id>
      <name>e-iceblue</name>
      <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
   </repository>
</repositories>
<dependencies>
   <dependency>
      <groupId>e-iceblue</groupId>
      <artifactId>spire.doc.free</artifactId>
      <version>3.9.0</version>
   </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Below is the sample document which contains many blank lines:

Code Snippet

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("sample2.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);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Top comments (0)