以程式設計方式在文件中新增頁首和頁尾
您可以使用 Section 的 Headers 屬性和 Footers 屬性,將文字加入文件的頁首和頁尾。 文件的每個區段都包含三個頁首和頁尾:
-
文件層級自訂與 VSTO 增益集的程序不同。
適用對象:本主題資訊適用於文件層級的專案和 Word 的 VSTO 增益集專案。 如需詳細資訊,請參閱依 Office 應用程式和專案類型提供的功能。
文件層級自訂
若要使用下列程式碼範例,請從專案的 ThisDocument
類別中執行範例。
將文字加入文件的頁尾
下列程式碼範例會設定文件每個區段的主要頁尾要插入的文字字型,然後將文字插入頁尾。
將文字加入文件的頁首
下列程式碼範例會在文件的每個頁首加入顯示頁碼的欄位,然後設定段落對齊方式,讓文字向頁首的右邊靠齊。
foreach (Word.Section section in this.Sections) { Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage); headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; }
VSTO 增益集
若要使用下列程式碼範例,請從專案的 ThisAddIn
類別中執行範例。
將文字加入文件的頁尾
下列程式碼範例會設定文件每個區段的主要頁尾要插入的文字字型,然後將文字插入頁尾。 這個程式碼範例使用使用中文件。
foreach (Word.Section wordSection in this.Application.ActiveDocument.Sections) { Word.Range footerRange = wordSection.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; footerRange.Font.ColorIndex = Word.WdColorIndex.wdDarkRed; footerRange.Font.Size = 20; footerRange.Text = "Confidential"; }
將文字加入文件的頁首
下列程式碼範例會在文件的每個頁首加入顯示頁碼的欄位,然後設定段落對齊方式,讓文字向頁首的右邊靠齊。 這個程式碼範例使用使用中文件。
foreach (Word.Section section in this.Application.ActiveDocument.Sections) { Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage); headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; }