在这个循序渐进的教程中,我们将解释如何在没有互操作的情况下使用 C#** 插入 Word 页眉和页脚。在 MS Word 文档中,您可以在 Word 中使用 C# 在第一页、偶数页和奇数页中插入页眉页脚。本主题中的 C# 代码示例在 Word 文档的页眉和页脚中插入文本并将其保存为 DOCX 文件格式。
使用 C# 插入 Word 页眉和页脚的步骤
- 安装 Aspose.Words for .NET 包
- 创建 Document 和 DocumentBuilder 类的实例
- 设置页面设置以对第一页、奇数页和偶数页使用不同的页眉和页脚
- 将光标移动到页眉和页脚并在其中插入一些文本
- 在文档正文中插入分页符以查看所有页眉和页脚
- 最后,将文档保存为 DOCX 文件格式
在这些步骤中,文档类对象用于创建和保存新的 Word 文档。而 DocumentBuilder 类对象用于设置页面设置,将光标移动到 Word 文件的不同部分、页眉和页脚以插入文本和插入分页符。最后,使用 C# 在 Word 中添加页眉和页脚后,将 Word 文档另存为 DOCX。
使用 C# 在 Word 中插入页眉和页脚的代码
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Aspose.Words; | |
using System; | |
namespace KBCodeExamples | |
{ | |
class how_to_insert_word_header_and_footer_using_c_sharp | |
{ | |
public static void InsertHeaderFooter(String MyDir) | |
{ | |
//Set Aspose license before creating header and footer | |
Aspose.Words.License AsposeWordsLicense = new Aspose.Words.License(); | |
AsposeWordsLicense.SetLicense("Aspose.Words.lic"); | |
// Create a blank Word document | |
Document doc = new Document(); | |
// Initialize a new instance DocumentBuilder | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
//Set different headers and footers for first, even and odd pages | |
builder.PageSetup.DifferentFirstPageHeaderFooter = true; | |
builder.PageSetup.OddAndEvenPagesHeaderFooter = true; | |
// Move the cursor to the beginning of header and | |
// insert some text into it | |
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary); | |
builder.Write("<<<<<<< HeaderPrimary >>>>>>>"); | |
builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst); | |
builder.Write("<<<<<<< HeaderFirst >>>>>>>"); | |
builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven); | |
builder.Write("<<<<<<< HeaderEven >>>>>>>"); | |
// Move the cursor to the beginning of footer and | |
// insert some text into it | |
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary); | |
builder.Write("<<<<<<< FooterPrimary >>>>>>>"); | |
builder.MoveToHeaderFooter(HeaderFooterType.FooterFirst); | |
builder.Write("<<<<<<< FooterFirst >>>>>>>"); | |
builder.MoveToHeaderFooter(HeaderFooterType.FooterEven); | |
builder.Write("<<<<<<< FooterEven >>>>>>>"); | |
//Move the cursor to the beginning of body in first section. | |
builder.MoveToSection(0); | |
builder.Writeln("Page1"); | |
builder.InsertBreak(BreakType.PageBreak); | |
builder.Writeln("Page2"); | |
builder.InsertBreak(BreakType.PageBreak); | |
builder.Writeln("Page3"); | |
//Save the document to DOCX file format | |
doc.Save(MyDir + @"output.docx", SaveFormat.Docx); | |
} | |
} | |
} |
在此示例代码中,DocumentBuilder 类包含用于设置页眉页脚类型的 PageSetup 成员。另一个成员 MoveToHeaderFooter 用于将光标移动到 Word 文档的不同页眉、页脚和部分。您还可以使用此类设置分页符。
在本文中,我们学习了使用 C# 在 Word 中添加页眉和页脚。但是,如果您想在 Word 文件中执行一些其他操作,请参阅 如何使用 C# 在 Word 文档中插入注释 上的文章。