這是之前寫的程式的加強版,我要用C#產生word文件,且該文件「需要有兩個段落」,且這兩頁的頁碼需要重編

但不希望用word內建的 Page X of Y

 

 

註:此程式在經過一些測試,發現有時候頁碼不會成功跳成~詳細原因還在研究

這個頁碼的插入,發現真的很麻煩,最後我還是使用activate() 該視窗的方式,然後再進行step by step的處理

 

 private void insertPageNumber(Word._Document oDoc)
        {

            Word.Section section = oDoc.Sections[1];
           
            object fieldEmpty = Word.WdFieldType.wdFieldEmpty;
            object autoText = "Page";  //頁碼
            object autoNumPage = "SectionPages";//頁數(該段落)
            object preserveFormatting = true;

            Range footer = section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;

            footer.Fields.Add(section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range, ref fieldEmpty, ref autoText, ref preserveFormatting);
            footer.InsertBefore("第");
            footer.InsertAfter("頁,共頁");

         
           
            footer.SetRange(29, 29);//直接指定位置。

            footer.Fields.Add(footer, ref fieldEmpty, ref autoNumPage, ref preserveFormatting);
            section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//置中對齊

           
            //接下來是將第二段以後的section的頁碼可以被重新編號,因為無法使用range,必需要將視窗切過去,所以要activate()
            oDoc.Activate();//激發它?
           
            oDoc.ActiveWindow.ActivePane.View.SeekView = WdSeekView.wdSeekCurrentPageHeader;
            //oDoc.ActiveWindow.ActivePane.View.NextHeaderFooter();//到第二個headerFooter
            oDoc.ActiveWindow.Selection.HeaderFooter.LinkToPrevious = false;//不要連結到前一段的頁碼
            Word.Selection currentSelection =oDoc.ActiveWindow.Application.Selection;
            currentSelection.HeaderFooter.PageNumbers.RestartNumberingAtSection =true;  //將頁碼重編
            currentSelection.HeaderFooter.PageNumbers.StartingNumber = 1;               //起始頁碼為1

            oDoc.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出頁面設置
        }

 

重點在上面三行,但是上面的頁碼插入方式還是一樣 是用暴力插入法~~因為還是沒有好的方法將之插入

 

by the way,此方法需要有將文件分段

我本身是使用此段落

        private void nextPage(Word._Document oDoc,bool isSectionBreak)
        {
            //Range finalRange = createFinalWorkRange(oDoc);
            Object num = oDoc.Characters.Count;
            Range finalRange = oDoc.Range(ref num, ref num);
            object Type;
            if(isSectionBreak)
                Type = Word.WdBreakType.wdSectionBreakNextPage;//分頁符號//應該是分節符號吧?
            else
                Type = Word.WdBreakType.wdPageBreak;//不要插入SectionPageBreak;
            finalRange.InsertBreak(ref Type);

        }

 

只要是插入Word.WdBreakType.wdSectionBreakNextPage的,他就會被判斷是分節,

若是只要分頁,不要分段,則使用Word.WdBreakType.wdPageBreak

 

這應該是很常用的東西…但不知道為什麼我查了很久查不到,最後是在一個英文網站上找到這幾個指令的。

arrow
arrow
    全站熱搜

    ccas 發表在 痞客邦 留言(2) 人氣()