Back to Devexpress

How to: Remove or Replace Blank Lines in a Document

officefileapi-120432-word-processing-document-api-examples-search-and-replace-how-to-remove-blank-lines-from-a-document.md

latest3.1 KB
Original Source

How to: Remove or Replace Blank Lines in a Document

  • Feb 21, 2025
  • 2 minutes to read

This code example shows how to retrieve excessive blank lines from a document. You can remove them or replace them with line break symbols.

Remove Blank Lines

Call the SubDocument.ReplaceAll method with the corresponding regular expression as the search parameter. Then save the result.

csharp
using DevExpress.XtraRichEdit;
using DevExpress.XtraRichEdit.API.Native;
using System.Text.RegularExpressions;

using (var wordProcessor = new RichEditDocumentServer()) {
    Document document = wordProcessor.Document;
    document.LoadDocument("Grimm.docx");
    string pattern = @"((?<=^)|(?<=\n))\n";
    string replacementString = string.Empty;
    Regex myRegEx = new Regex(pattern);
    document.ReplaceAll(myRegEx, replacementString);
}
vb
Imports DevExpress.XtraRichEdit
Imports DevExpress.XtraRichEdit.API.Native
Imports System.Text.RegularExpressions

Using wordProcessor = New RichEditDocumentServer()
    Dim document As Document = wordProcessor.Document
    document.LoadDocument("Grimm.docx")
    Dim pattern As String = "((?<=^)|(?<=\n))\n"
    Dim replacementString As String = String.Empty
    Dim myRegEx As New Regex(pattern)
    document.ReplaceAll(myRegEx, replacementString)
End Using

Replace Blank Lines

Use the Characters enumeration to replace blank lines with line breaks. Call the SubDocument.ReplaceAll and pass the Characters.LineBreak enumeration value as a method parameter. You can use the “((?<=^)|(?<=\n))\n” expression to find blank lines.

csharp
using DevExpress.XtraRichEdit;
using DevExpress.XtraRichEdit.API.Native;
using System.Text.RegularExpressions;
using DevExpress.Office;

using (var wordProcessor = new RichEditDocumentServer())
{
    Document document = wordProcessor.Document;
    document.LoadDocument(@"C:\Docs\Word (RTF) Document API for NET.docx");
    string pattern = @"((?<=^)|(?<=\n))\n";
    Regex myRegEx = new Regex(pattern);
    document.ReplaceAll(myRegEx, Characters.LineBreak.ToString());
    wordProcessor.SaveDocument("updated.docx", DocumentFormat.Docx);
}
vb
Imports DevExpress.XtraRichEdit
Imports DevExpress.XtraRichEdit.API.Native
Imports System.Text.RegularExpressions
Imports DevExpress.Office

Using wordProcessor = New RichEditDocumentServer()
    Dim document As Document = wordProcessor.Document
    document.LoadDocument("C:\Docs\Word (RTF) Document API for NET.docx")
    Dim pattern As String = "((?<=^)|(?<=\n))\n"
    Dim myRegEx As New Regex(pattern)
    document.ReplaceAll(myRegEx, Characters.LineBreak.ToString())
    wordProcessor.SaveDocument("updated.docx", DocumentFormat.Docx)
End Using