How to: Remove or Replace Blank Lines in a Document
- 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.
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);
}
#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.
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.OpenXml);
}