DEV Community


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.

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.

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();

        //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()) {

        //Save the document to file
        String result = "removeBlankLines.docx";
        document.saveToFile(result, FileFormat.Docx_2013);
Enter fullscreen mode Exit fullscreen mode


Top comments (0)