如何使用 C# 删除 Word 中的所有分页符

本分步教程指导如何使用 C# 删除 Word 中的所有分页符。它包含设置开发环境的详细信息、编程任务列表和可运行的示例代码以使用 C# 在 Word 中删除分页符。它将分享有关 Word 文档结构和 Word 文件中发现的不同类型的分页符的详细信息。

使用 C# 在 Word 中删除分页符的步骤

  1. 设置开发环境使用Aspose.Words for .NET消除分页符
  2. 将目标 Word 文件加载到 Document 对象并访问所有 paragraphs
  3. 解析所有段落并检查段落前的分页符
  4. 删除每个段落前的分页符
  5. 解析每个段落中的所有运行并将所有分页符替换为空字符串
  6. 保存生成的 Word 文件,其中没有分页符

这些步骤描述了如何使用 C# 在 Word 上删除分页符的过程。每个 Word 文件都有一个段落集合,其中每个段落都有 ParagraphFormat.PageBreakBefore 属性,需要将其设置为false”以从开头删除分隔符。反过来,每个段落都有一组运行,其中每个运行可以在多个地方有分页符,可以通过用空字符串替换它来删除分页符。

使用 C# 消除 Word 中分页符的代码

using Aspose.Words;
class Program{
static void Main(string[] args) // Remove page breaks in a Word file using C#
{
// Set PDF license
new License().SetLicense("Aspose.Total.lic");
// Load the sample Word file having page breaks in it
Document doc = new Document("DocWithPageBreaks.docx");
// Get access to all the paragraphs
NodeCollection docParagraphs = doc
.GetChildNodes(NodeType.Paragraph, true);
foreach (Paragraph currentPara in docParagraphs)
{
// Check if the page break is there before
// the paragraph
if (currentPara.ParagraphFormat.PageBreakBefore)
{
// Remove the page break from the start
currentPara.ParagraphFormat
.PageBreakBefore = false;
}
// Parse through all the runs in the paragraph
foreach (Run currentRun in currentPara.Runs)
{
// Check page break
if (currentRun.Text.Contains(ControlChar.PageBreak))
{
// Replace the page break with an empty string
currentRun.Text = currentRun.Text
.Replace(ControlChar.PageBreak, string.Empty);
}
}
}
// Save the resultant DOCX without any page break in it
doc.Save("DocxWithoutPageBreaks.docx");
}
}

在这段代码中,我们观察了如何使用 C# 在 Word 中删除分页符。它通过提供 NodeType.Paragraph 作为参数来使用 GetChildNodes() 方法来访问段落集合。每次运行中的文本可以有不同类型的控制字符,如换行符、段落符和分栏符,也可以使用与分页符相同的方法删除。

这篇文章教我们去除Word文件中的分页符。如果您想了解删除 Word 文件中空白页的过程,请参阅 如何使用C#删除Word中的空白页 上的文章。

 简体中文