TX Text Control .NET Server

Headers and Footers

Topic

A letterhead on the first page, a report title at the top of every page and "Page 3 of 12" at the bottom are headers and footers. ServerTextControl adds them to a whole document or to single sections, gives the first page and the even pages versions of their own, fills them with page number fields and removes them from documents you load.

Create a Document adds a first header with a line of text. The code of each example goes into Program.cs of a console application and runs on its own. A section is a part of a document with its own page settings; Sections explains how to insert one.

How Headers and Footers Work

A header or footer is a HeaderFooter object. It has its own Selection and its own collections, such as Paragraphs, Tables and Images, so you insert and format text in it the same way as in the main text.

Headers and footers belong to a HeaderFooterCollection, which you get in two places:

  • For the document, ServerTextControl.HeadersAndFooters. A header added here goes to the first section, and every other section receives a header that is connected to the header of its previous section. Connected headers always have the same content.
  • For one section, Section.HeadersAndFooters. Use this collection as soon as a document has more than one section: through the document's collection, most collections of a HeaderFooter are then null.

Both collections have the same methods. Add adds a header or footer and returns true if it was added, GetItem returns one that has been added, and Remove removes it. Each takes a value of HeaderFooterType, and Add and Remove accept several values combined, such as HeaderFooterType.Header | HeaderFooterType.Footer:

TypeAppears on
Header, FooterAll pages. If the document or section has an even header or footer, the odd pages
FirstPageHeader, FirstPageFooterThe first page of the document or section
EvenHeader, EvenFooterThe even pages. Adding an even header also creates the odd header, because the two only exist together
AllAll headers and footers, for Add and Remove

There is no separate setting for a different first page or for different odd and even pages: a document has them when it contains headers or footers of these types.

HeaderFooter.Distance sets the position in twips, 1/1440 inch. For a header, it is the distance from the top of the page to the top of the header; for a footer, from the bottom of the page to the bottom of the footer. The default is 567 twips, which is 1 cm.

Use a Cover Page and Odd and Even Headers

A report often has a cover page without a header and different headers on odd and even pages. The following program adds an empty first page header and an even header, which also creates the odd header:

using TXTextControl;

using (ServerTextControl tx = new ServerTextControl())
{
    tx.Create();

    for (int i = 1; i <= 200; i++)
    {
        tx.Selection.Text = "This is paragraph " + i + ".\r\n";
    }

    // A header for the first page, which stays empty
    tx.HeadersAndFooters.Add(HeaderFooterType.FirstPageHeader);

    // An even header; the odd header is created with it
    tx.HeadersAndFooters.Add(HeaderFooterType.EvenHeader);

    // Header returns the odd header once an even header exists
    HeaderFooter oddHeader = tx.HeadersAndFooters.GetItem(HeaderFooterType.Header);
    oddHeader.Selection.Text = "Annual Report";
    oddHeader.Selection.ParagraphFormat.Alignment = HorizontalAlignment.Right;

    HeaderFooter evenHeader = tx.HeadersAndFooters.GetItem(HeaderFooterType.EvenHeader);
    evenHeader.Selection.Text = "Text Control, LLC";

    tx.Save("odd-even-headers.pdf", StreamType.AdobePDF);
}

The first page has no header text. From the second page on, even pages show "Text Control, LLC" on the left, and odd pages show "Annual Report" on the right.

Give a Section Its Own Header

A new section starts with the settings of the previous section, including its headers and footers, and its headers are connected to the previous ones. To give a section a header with different content, get the header from the section and set ConnectedToPrevious to false before you change its text:

using TXTextControl;

using (ServerTextControl tx = new ServerTextControl())
{
    tx.Create();

    tx.Selection.Text = "Chapter 1\r\nThe first chapter.";
    tx.Sections.Add(SectionBreakKind.BeginAtNewPage);
    tx.Selection.Text = "Chapter 2\r\nThe second chapter.";

    // Section 2 receives a header that is connected to section 1
    tx.HeadersAndFooters.Add(HeaderFooterType.Header);

    // With more than one section, get the headers from the sections
    HeaderFooter header1 = tx.Sections[1].HeadersAndFooters.GetItem(HeaderFooterType.Header);
    HeaderFooter header2 = tx.Sections[2].HeadersAndFooters.GetItem(HeaderFooterType.Header);

    // Connected headers always have the same content
    header2.ConnectedToPrevious = false;

    header1.Selection.Text = "Chapter 1";
    header2.Selection.Text = "Chapter 2";

    foreach (Section section in tx.Sections)
    {
        foreach (HeaderFooter headerFooter in section.HeadersAndFooters)
        {
            Console.WriteLine($"Section {section.Number}: {headerFooter.Type}, connected: {headerFooter.ConnectedToPrevious}");
        }
    }

    tx.Save("section-headers.pdf", StreamType.AdobePDF);
}

The code works as follows:

  • Sections.Add inserts a section break, and the second chapter starts on a new page.
  • tx.Sections[1] and tx.Sections[2] return the sections by their number, which starts at 1.
  • header2.ConnectedToPrevious = false separates the header of the second section from the first, so each header keeps its own text.
  • HeaderFooter.Type returns the type of each header or footer the loop finds.

Restart Page Numbers in a Section

Page numbers continue from section to section. SectionFormat.RestartPageNumbering restarts them at the beginning of a section, with the number that the page number field's StartNumber sets. The following program numbers the pages of an appendix with Roman numbers, starting at I:

using TXTextControl;

using (ServerTextControl tx = new ServerTextControl())
{
    tx.Create();

    tx.Selection.Text = "Main part of the document.";
    tx.Sections.Add(SectionBreakKind.BeginAtNewPage);
    tx.Selection.Text = "Appendix";

    Section appendix = tx.Sections[2];
    appendix.Format.RestartPageNumbering = true;

    // A footer for the appendix only
    appendix.HeadersAndFooters.Add(HeaderFooterType.Footer);
    HeaderFooter footer = appendix.HeadersAndFooters.GetItem(HeaderFooterType.Footer);
    footer.ConnectedToPrevious = false;

    footer.Selection.Text = "Appendix page ";
    footer.PageNumberFields.Add(new PageNumberField(1, NumberFormat.RomanNumbers));

    tx.Save("appendix.pdf", StreamType.AdobePDF);
}

Read and Remove Headers and Footers

Documents that you load bring their headers and footers along. To list them, loop through the sections and their collections. The following program prints the type, the distance and the text of every header and footer of Documents/sample.docx and then removes all of them:

using TXTextControl;

using (ServerTextControl tx = new ServerTextControl())
{
    tx.Create();
    tx.Load("Documents/sample.docx", StreamType.WordprocessingML);

    foreach (Section section in tx.Sections)
    {
        foreach (HeaderFooter headerFooter in section.HeadersAndFooters)
        {
            Console.WriteLine($"Section {section.Number}: {headerFooter.Type}, distance {headerFooter.Distance} twips");

            foreach (Paragraph paragraph in headerFooter.Paragraphs)
            {
                Console.WriteLine("  " + paragraph.Text);
            }
        }
    }

    // Remove all headers and footers of every section
    foreach (Section section in tx.Sections)
    {
        section.HeadersAndFooters.Remove(HeaderFooterType.All);
    }

    tx.Save("no-headers.docx", StreamType.WordprocessingML);
}

Remove works for single types too. Remove(HeaderFooterType.Header) removes the header, and the even header with it if there is one. Remove(HeaderFooterType.EvenHeader) removes only the even header, and the odd header becomes the header of all pages.

Other Content in Headers and Footers

  • Images and watermarks. HeaderFooter.Images adds images to a header or footer. An image placed behind the text of a header is repeated on every page of the section, which is how the blog article Generating and Adding Watermarks to Documents using C# adds a watermark to each section. Watermarks covers watermarks in PDF documents.
  • Fields. HeaderFooter.ApplicationFields contains the fields of a header or footer, such as merge fields. As for the main text, set LoadSettings.ApplicationFieldFormat before you load a Word document, otherwise the collection is empty. Fields describes the kinds of fields.
  • Merge fields in templates. MailMerge fills merge fields in headers and footers as well. When several records are merged into one document, each record starts a new section; the blog article Merging Multiple Records with First-Page Headers and Footers shows how ConnectedToPrevious gives each record's first page its own header data.

Next Steps

  • Sections: insert sections with their own page size, orientation and columns.
  • Fields: work with the other fields of a document.
  • Merge Fields: fill fields in headers and footers with data.
  • Headers and Footers in the Document Editor: add headers and footers from JavaScript.