Word控件Spire.Doc 【页面设置】教程(10) ;通过 Spire.Doc 在 Word 文档的不同部分添加页码

开发人员有时需为Word文档不同部分添加页码,本文介绍通过Spire.Doc实现该功能的方法。详细步骤包括创建新文档并加载测试文件、为第一部分创建页脚添加页码、重新开始下一节页码并设起始页为1、用循环处理其余部分,最后保存查看。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有时,开发人员需要在一个 Word 文档中为不同的部分添加页码,例如封面、目录和内容位于不同的部分。本文讨论如何通过Spire.Doc为不同部分添加页码。

Spire.Doc for.NET 最新下载icon-default.png?t=M85Bhttps://www.evget.com/product/3368/download

这里将在 3 个部分内导入一个测试文档,如下图所示。

以下是详细步骤:

第 1 步:创建一个新文档并加载测试字文件。

Document document = new Document("test.docx"); 

第 2 步:为第一部分创建页脚并在其中添加页码。

HeaderFooter footer = document.Sections[0].HeadersFooters.Footer;
Paragraph footerParagraph = footer.AddParagraph();
footerParagraph.AppendField("page number", FieldType.FieldPage);
footerParagraph.AppendText(" of ");
footerParagraph.AppendField("number of pages", FieldType.FieldSectionPages);
footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right;

第 3 步:重新开始下一节的页码,并将起始页码设置为 1。

document.Sections[1].PageSetup.RestartPageNumbering = true;
document.Sections[1].PageSetup.PageStartingNumber = 1;

第 4 步:对其余部分重复第 2 步和第 3 步,因此使用 for 循环更改代码。

for (int i = 0; i < 3; i++)
{
HeaderFooter footer = document.Sections[i].HeadersFooters.Footer;
Paragraph footerParagraph = footer.AddParagraph();
footerParagraph.AppendField("page number", FieldType.FieldPage);
footerParagraph.AppendText(" of ");
footerParagraph.AppendField("number of pages", FieldType.FieldSectionPages);
footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right;

if (i == 2)
break;
else
{
document.Sections[i + 1].PageSetup.RestartPageNumbering = true;
document.Sections[i + 1].PageSetup.PageStartingNumber = 1;
}
}

第 5 步:保存并查看。

document.SaveToFile("result.docx", FileFormat.Docx);
System.Diagnostics.Process.Start("result.docx");

结果截图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值