Remove Blank Lines in Word Document in Java

Tuesday, 24 November 2020 07:03 Written by  support iceblue
Rate this item
(0 votes)

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

Additional Info

  • tutorial_title:
Last modified on Tuesday, 31 August 2021 09:16