Uređivanje

Dijeli putem


Programmatically add headers and footers to documents

You can add text to headers and footers in your document by using the Headers property and Footers property of the Section. Each section of a document contains three headers and footers:

Document-level customizations

To use the following code examples, run them from the ThisDocument class in your project.

To add text to footers in the document

  1. The following code example sets the font of the text to be inserted into the primary footer of each section of the document, and then inserts text into the footer.

    foreach (Word.Section wordSection in this.Sections)
    {
        Word.Range footerRange = wordSection.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
        footerRange.Font.ColorIndex = Word.WdColorIndex.wdDarkRed;
        footerRange.Font.Size = 20;
        footerRange.Text = "Confidential";
    }
    

To add text to headers in the document

  1. The following code example adds a field to show the page number in each header in the document, and then sets the paragraph alignment so that the text aligns to the right of the header.

    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 Add-ins

To use the following code examples, run them from the ThisAddIn class in your project.

To add text to footers in a document

  1. The following code example sets the font of the text to be inserted into the primary footer of each section of the document, and then inserts text into the footer. This code example uses the active document.

    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";
    }
    

To add text to headers in the document

  1. The following code example adds a field to show the page number in each header in the document, and then sets the paragraph alignment so that the text aligns to the right of the header. This code example uses the active document.

    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;
    }