如何使用 C# 在 Word 中删除空白页

如何使用 C# 在 Word 中删除空白页

这个快速的教程解释了如何从Word文档(DOCX,DOC,等)中删除白页,使用C#,这个过程包括上传Word文件,分析个别页面,识别空页面,并最终创建一个没有白页的新文档。

在Word文档中删除白页的好处

  • 清理文件:- 提高阅读力和专业性。

  • 缩小文件大小:- 有效存储,通过消除不必要的页面。

  • 自动化能力:- 非常适合自动清理大型文件。

原标题:准备环境

  • Visual Studio 或其他 .NET IDE。
  • Aspose.Words 通过 NuGet Package Manager 添加。

步骤指南 用 C# 在 Word 中删除白色页面

步骤1:设置环境

通过 NuGet 包管理器安装 Aspose.Words 图书馆。

Install-Package Aspose.Words

步骤2:下载文档

使用文档类对象下载您的原始Word文件。

Document originalDoc = new Document("WordFileWithBlankPages.docx");

步骤3:单独提取每个页面

通过每个页面,并将每个页面提取到一个单独的文档分析。

int totalPages = originalDoc.PageCount;

for (int i = 0; i < totalPages; i++)
{
    Document singlePageDoc = originalDoc.ExtractPages(i, 1);
    // Analyze singlePageDoc in next steps
}

步骤4:分析单页文件

检查单页文档是否包含文本或格式。

int shapesCounter = 0;
string pageText = "";

foreach (Section docSection in singlePageDoc.Sections)
{
    pageText += docSection.Body.ToString(SaveFormat.Text);
    shapesCounter += docSection.Body.GetChildNodes(NodeType.Shape, true).Count;
}

步骤5:保持非空页列表

跟踪包含内容的页数。

ArrayList blankPages = new ArrayList();
blankPages.Add(-1);

if (string.IsNullOrEmpty(pageText.Trim()) && shapesCounter == 0)
    blankPages.Add(i); // i is page index in loop

步骤6:将非空页添加到新文档

创建一个新的文档,并使用跟踪列表仅添加非空页面。

Document finalDoc = (Document)originalDoc.Clone(false);
finalDoc.RemoveAllChildren();

blankPages.Add(totalPages);

for (int i = 1; i < blankPages.Count; i++)
{
    int index = (int)blankPages[i - 1] + 1;
    int count = (int)blankPages[i] - index;

    if (count > 0)
        finalDoc.AppendDocument(originalDoc.ExtractPages(index, count), ImportFormatMode.KeepSourceFormatting);
}

步骤7:保存已修改的文件

保存新文件与白色页面删除。

finalDoc.Save(@"cleaned.docx");

完整的代码示例 用 C# 在 Word 中删除白页

下面是完整的可执行代码示例,表明上述步骤:

Document originalDoc = new Document("WordFileWithBlankPages.docx");

ArrayList blankPages = new ArrayList();
blankPages.Add(-1);

int totalPages = originalDoc.PageCount;

for (int i = 0; i < totalPages; i++)
{
    Document singlePageDoc = originalDoc.ExtractPages(i, 1);
    int shapesCounter = 0;
    string pageText = "";

    foreach (Section docSection in singlePageDoc.Sections)
    {
        pageText += docSection.Body.ToString(SaveFormat.Text);
        shapesCounter += docSection.Body.GetChildNodes(NodeType.Shape, true).Count;
    }

    if (string.IsNullOrEmpty(pageText.Trim()) && shapesCounter == 0)
        blankPages.Add(i);
}

blankPages.Add(totalPages);

Document finalDoc = (Document)originalDoc.Clone(false);
finalDoc.RemoveAllChildren();

for (int i = 1; i < blankPages.Count; i++)
{
    int index = (int)blankPages[i - 1] + 1;
    int count = (int)blankPages[i] - index;

    if (count > 0)
        finalDoc.AppendDocument(originalDoc.ExtractPages(index, count), ImportFormatMode.KeepSourceFormatting);
}

finalDoc.Save(@"NonEmptyPages.docx");
System.Console.WriteLine("Blank pages removed successfully.");

结论

本文解释了如何在Word文件中删除空白页面使用C#。 通过遵循所提供的步骤,您可以编程地检测空白页面并删除它们,从而获得更清洁的文档。

 中文