In this step-by-step tutorial, we will explain how to insert Word header and footer using C# without interop. In MS Word document, you can insert header footer in Word using C# differently for first, even and odd pages. The C# code example in this topic inserts text in the header and footer of the Word document and saves it to DOCX file format.
Steps to Insert Word header and footer using C#
- Install Aspose.Words for .NET package
- Create an instance of Document and DocumentBuilder classes
- Set page setup to use different headers and footers for first, odd, and even pages
- Move the cursor to the header and footer and insert some text into them
- Insert page breaks into document’s body to view all headers and footers
- Finally, save the document to DOCX file format
In these steps, the document class object is used to create and save the new Word document. Whereas the DocumentBuilder class object is used to set page setup, move the cursor to different sections, header, and footer of the Word file for inserting text and inserting page breaks. Finally, the Word document is saved as DOCX after adding header and footer in Word using C#.
Code to Insert header and footer in Word using C#
In this sample code, the DocumentBuilder class contains PageSetup member that is used for setting the header footer type. The other member MoveToHeaderFooter is used for moving the cursor to different headers, footers, and sections of the Word document. You can also set page breaks using this class.
In this article, we have learned to add a header and footer in Word using C#. However, if you want to perform some other operations in the Word file, refer to the article on how to insert comment into Word document using C#.