c# - add page number in footer starting from n page in word document
问题描述
I need to add page number (Page 1 of X) starting from say 5th page in the word document. How to do that. The code I have adds to the entire document and I am unable to control it. I am using Word interop in C#. Please help.
oDoc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter;
//Object oMissing = System.Reflection.Missing.Value;
oDoc.ActiveWindow.Selection.TypeText("\t Page ");
Object TotalPages = Microsoft.Office.Interop.Word.WdFieldType.wdFieldNumPages;
Object CurrentPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage;
oDoc.ActiveWindow.Selection.HeaderFooter.LinkToPrevious = false;
oDoc.ActiveWindow.Selection.Fields.Add(oDoc.ActiveWindow.Selection.Range, ref CurrentPage, ref oMissing, ref oMissing);
oDoc.ActiveWindow.Selection.TypeText(" of ");
oDoc.ActiveWindow.Selection.Fields.Add(oDoc.ActiveWindow.Selection.Range, ref TotalPages, ref oMissing, ref oMissing);
解决方案
为了在文档中(重新)开始编号,需要分节符。下面的示例演示了如何在目标页面之前插入“下一页”分节符,然后格式化新节的页脚以使页码从第 1 节开始。
请注意,我还将分配更改为TotalPages
假设总页数应该是新部分的页数,而不是整个文档的页数。
//Go to page where page numbering should start
string pageNum = "3";
wdApp.Selection.GoTo(Word.WdGoToItem.wdGoToPage, Word.WdGoToDirection.wdGoToNext, ref missing, pageNum);
Word.Range rngPageNum = wdApp.Selection.Range;
//Insert Next Page section break so that numbering can start at 1
rngPageNum.InsertBreak(Word.WdBreakType.wdSectionBreakNextPage);
Word.Section currSec = doc.Sections[rngPageNum.Sections[1].Index];
Word.HeaderFooter ftr = currSec.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];
//So that the footer content doesn't propagate to the previous section
ftr.LinkToPrevious = false;
ftr.PageNumbers.RestartNumberingAtSection = true;
ftr.PageNumbers.StartingNumber = 1;
//If the total pages should not be the total in the document, just the section
//use the field SectionPages instead of NumPages
object TotalPages = Microsoft.Office.Interop.Word.WdFieldType.wdFieldSectionPages;
object CurrentPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage;
Word.Range rngCurrSecFooter = ftr.Range;
rngCurrSecFooter.Fields.Add(rngCurrSecFooter, ref CurrentPage, ref missing, false);
rngCurrSecFooter.InsertAfter(" of ");
rngCurrSecFooter.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
rngCurrSecFooter.Fields.Add(rngCurrSecFooter, ref TotalPages, ref missing, false);
推荐阅读
- python - 如何使用 string.split() 拆分具有多个分隔符的字符串?
- python - Kivy 网格布局的 minimum_height 为 0
- python - 如何处理从python程序接收到的数据
- html - 将播放按钮图像放在视频缩略图顶部,并在其下方显示文字
- java - Java 多线程:选项太多
- c# - 加入多个列表并以逗号分隔的字符串形式获取输出
- c# - 如何访问二维数组以输入学生的成绩?C#
- python - 从 .txt 文件 (python) 添加具有不同值的相同变量
- python-3.x - 如何从 python 中的导入模块更改不可变对象?
- reactjs - 如何在 React 中测试上下文?