Skip to content

Instantly share code, notes, and snippets.

How to Remove Blank Page in Word in C#. For more information, please follow link: https://kb.conholdate.com/total/net/how-to-remove-blank-page-in-word-using-c-sharp/
using System.Collections;
using Aspose.Words;
namespace DeleteABlankPageInWordUsingCSharp
{
class Program
{
static void Main(string[] args) // Main function to delete a blank page in Word using CSharp
{
// Instantiate the license to avoid any trial version limitations
// and watermark in the output Word file
Aspose.Words.License licDeleteBlankPages= new Aspose.Words.License();
licDeleteBlankPages.SetLicense("Aspose.Words.lic");
// Load the Word file having blank pages in it
Document originalDocWithFewBlankPages = new Document("WordFileWithBlankPages.docx");
// Declare an array to store page numbers of the empty or blank pages
ArrayList listOfBlankPageNumbers = new ArrayList();
listOfBlankPageNumbers.Add(-1);
// Extract each page of the loaded document as a separate Word document
int totalPagesInOriginalDoc = originalDocWithFewBlankPages.PageCount;
for (int iCount = 0; iCount < totalPagesInOriginalDoc; iCount++)
{
// Create a new Word document containing the single page
Document DocWithOnePage = originalDocWithFewBlankPages.ExtractPages(iCount, 1);
// Parse through all the sections of the newly created document
// to count text segments and shapes if any
int shapesCounter = 0;
string pageText = "";
foreach (Section docSection in DocWithOnePage.Sections)
{
// Extract text from the section and also get shapes count in the newly created document
pageText = pageText + docSection.Body.ToString(SaveFormat.Text);
shapesCounter += docSection.Body.GetChildNodes(NodeType.Shape, true).Count;
}
// Check if the extracted page is null or not and also check if shapes count is 0 or not
// If text is blank and shapes count is 0, it means the page is blank
if (string.IsNullOrEmpty(pageText.Trim()) && shapesCounter == 0)
listOfBlankPageNumbers.Add(iCount);
}
listOfBlankPageNumbers.Add(totalPagesInOriginalDoc);
// Add all the non-empty pages to the final document
Document nonEmptyDocument = (Document)originalDocWithFewBlankPages.Clone(false);
nonEmptyDocument.RemoveAllChildren();
for (int iCount = 1; iCount < listOfBlankPageNumbers.Count; iCount++)
{
int index = (int)listOfBlankPageNumbers[iCount - 1] + 1;
int count = (int)listOfBlankPageNumbers[iCount] - index;
if (count > 0)
nonEmptyDocument.AppendDocument(originalDocWithFewBlankPages.ExtractPages(index, count), ImportFormatMode.KeepSourceFormatting);
}
// Save the output file having all the non-empty pages
nonEmptyDocument.Save(@"NonEmptyPages.docx");
System.Console.WriteLine("Done");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment