When coping content from the Internet into a Word document, you may find that there are a lot of blank lines between paragraphs, which will not only make the document look lengthier but also affect the readability. In this article, you will learn how to programmatically remove empty lines/blank paragraphs in an existing Word document using Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Remove Empty Lines in an Existing Word Document
The detailed steps are as follows:
- Create a Document instance.
- Load a sample Word document using Document.LoadFromFile() method.
- Loop through all paragraphs in the document and determine whether the paragraph is a blank paragraph.
- Remove blank paragraphs from the document using DocumentObjectCollection.Remove() method.
- Save the document to another file using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using System; namespace RemoveEmptyLines { class Program { static void Main(string[] args) { //Create a Document instance Document doc = new Document(); //Load a sample Word document doc.LoadFromFile(@"D:\Files\input.docx"); //Loop through all paragraphs in the document foreach (Section section in doc.Sections) { for (int i = 0; i < section.Body.ChildObjects.Count; i++) { if (section.Body.ChildObjects[i].DocumentObjectType == DocumentObjectType.Paragraph) { //Determine if the paragraph is a blank paragraph if (String.IsNullOrEmpty((section.Body.ChildObjects[i] as Paragraph).Text.Trim())) { //Remove blank paragraphs section.Body.ChildObjects.Remove(section.Body.ChildObjects[i]); i--; } } } } //Save the document doc.SaveToFile("RemoveEmptyLines.docx", FileFormat.Docx2013); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.