Spire.Doc for .NET是一款专门对 Word 文档进行操作的 .NET 类库。在于帮助开发人员无需安装 Microsoft Word情况下,轻松快捷高效地创建、编辑、转换和打印 Microsoft Word 文档。拥有近10年专业开发经验Spire系列办公文档开发工具,专注于创建、编辑、转换和打印Word/PDF/Excel等格式文件处理,小巧便捷。
E-iceblue 功能类库Spire 系列文档处理组件均由中国本土团队研发,不依赖第三方软件,不受其他国家的技术或法律法规限制,同时适配国产操作系统如中科方德、中标麒麟等,兼容国产文档处理软件 WPS(如 .wps/.et/.dps 等格式
Spire.Doc for.NET 最新下载https://www.evget.com/product/3368/download
页码是页眉和页脚的格式之一。它给出了文档的总页数,方便读者索引。Spire.Doc 支持添加文本和图像页眉和页脚。本教程将指导您如何使用 C# 在文档的页眉/页脚上添加页码。
Spire.Doc 提供了 HeaderFooter 类来设置 word 文档的页眉或页脚。然后调用header/footer.AddParagraph()方法添加页眉/页脚段落,调用paragraph.AppendText方法添加内容。下面介绍如何为word文档添加页码的代码片段。
第 1 步:创建一个新文档并从文件中加载文档。
Document doc = new Document(); doc.LoadFromFile("Sample.docx");
第 2 步:为第一部分创建页脚并为页脚添加一个段落。
HeaderFooter footer = doc.Sections[0].HeadersFooters.Footer; Paragraph footerParagraph = footer.AddParagraph();
第 3 步:将页码添加到页脚并设置段落的对齐方式。
footerParagraph.AppendField("page number", FieldType.FieldPage); footerParagraph.AppendText(" of "); footerParagraph.AppendField("number of pages", FieldType.FieldNumPages); footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right;
第 4 步:将文档保存到文件。
doc.SaveToFile("Add.docx", FileFormat.Docx);
有效截图:
完整代码:
namespace AddPagenumbers { class Program { static void Main(string[] args) { Document doc = new Document(); doc.LoadFromFile("Sample.docx"); HeaderFooter footer = doc.Sections[0].HeadersFooters.Footer; Paragraph footerParagraph = footer.AddParagraph(); footerParagraph.AppendField("page number", FieldType.FieldPage); footerParagraph.AppendText(" of "); footerParagraph.AppendField("number of pages", FieldType.FieldNumPages); footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right; doc.SaveToFile("Add.docx", FileFormat.Docx); } } }
以上便是文档的页眉/页脚添加页码,如果您有其他问题也可以继续浏览本系列文章,获取相关教程,你还可以给我留言或者加入我们的官方技术交流群。