首页 > 解决方案 > 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);
                       

标签: c#ms-wordoffice-interop

解决方案


为了在文档中(重新)开始编号,需要分节符。下面的示例演示了如何在目标页面之前插入“下一页”分节符,然后格式化新节的页脚以使页码从第 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);

推荐阅读