DEV Community

Pilalo Jovanitho
Pilalo Jovanitho

Posted on

C#: Add Header and Footer in Word Documents

Many C# developers face the same repetitive task: adding a header and footer to Word documents automatically. Manual editing not only wastes time but also leads to formatting inconsistencies across dozens or hundreds of files. What if you could insert a uniform header/footer programmatically, control page numbers, and even embed images with a few lines of code? This article shows a practical, end‑to‑end solution using Spire.Doc for .NET, a lightweight library that eliminates the need for Office Interop.

Why programmatic headers/footers?

Adding headers and footers through code brings three concrete benefits:

Consistency – Every generated document follows the same layout, font, and branding.

Automation – Batch‑process dozens of reports, contracts, or invoices in a single run.

Maintainability – Changing the header/footer style requires only a code change, not a manual edit of each file.

Typical scenarios include:

  • Monthly financial reports that must show the company logo and page numbers.
  • Legal contracts where each page needs a confidential notice in the footer.
  • Invoices that require a dynamic “Generated on {date}” line.

Core APIs & Libraries

Feature Microsoft.Office.Interop.Word Spire.Doc for .NET
Installation Requires Office installed on the server; COM registration. Simple NuGet package; no Office dependency.
Licensing Free with Office, but not suitable for server‑side use. Free version (limited features) + commercial license for full support.
Performance Slower, heavy COM overhead. Faster, pure .NET, works in ASP.NET Core.
Platform Windows only. .NET 6+, .NET Core, cross‑platform.
API Simplicity Verbose COM objects, many interop calls. Fluent, object‑oriented API.

While Microsoft.Office.Interop.Word is the official automation API, it is unsuitable for server environments and requires Microsoft Word to be installed. Spire.Doc for .NET offers a clean, license‑friendly alternative that works on Windows, Linux, and macOS, making it the preferred choice for most modern C# projects.

Step‑by‑step implementation with Spire.Doc

Prerequisites

  1. .NET 6 (or later) SDK installed.
  2. Add the NuGet package:
dotnet add package Spire.Doc --version 9.0.0
Enter fullscreen mode Exit fullscreen mode
  1. (Optional) Obtain a commercial license if you need the full feature set.

Code example

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

// 1️⃣ Create a new document
Document doc = new Document();
Section section = doc.AddSection();

// 2️⃣ Set basic page layout (optional)
section.PageSetup.PageSize = PageSize.A4;
section.PageSetup.Margins.Top = 72f;
section.PageSetup.Margins.Bottom = 72f;

// 3️⃣ Insert Header
HeaderFooter header = section.HeadersFooters.Header;
Paragraph hdrPara = header.AddParagraph();
DocPicture logo = hdrPara.AppendPicture(Image.FromFile("Header.png"));
logo.TextWrappingStyle = TextWrappingStyle.Behind;
logo.HorizontalAlignment = ShapeHorizontalAlignment.Left;
hdrPara.AppendText("  Demo of Spire.Doc")
       .CharacterFormat.FontName = "Arial";
hdrPara.Format.HorizontalAlignment = HorizontalAlignment.Right;
hdrPara.Format.Borders.Bottom.BorderType = BorderStyle.Single;

// 4️⃣ Insert Footer with page numbers
HeaderFooter footer = section.HeadersFooters.Footer;
Paragraph ftrPara = footer.AddParagraph();
ftrPara.AppendField(FieldType.FieldPage);
ftrPara.AppendText(" of ");
ftrPara.AppendField(FieldType.FieldNumPages);
ftrPara.Format.HorizontalAlignment = HorizontalAlignment.Right;
ftrPara.Format.Borders.Top.BorderType = BorderStyle.Single;

// 5️⃣ Save the document
doc.SaveToFile("Report.docx", FileFormat.Docx);
Enter fullscreen mode Exit fullscreen mode

Explanation

  • Document & SectionDocument is the root object; each Section represents a page group.
  • HeaderFootersection.HeadersFooters.Header and .Footer give direct access to the respective containers.
  • Paragraph & DocPicture – Adding a paragraph lets you mix text and images. The picture’s TextWrappingStyle set to Behind ensures it does not interfere with the text flow.
  • Page NumbersFieldType.FieldPage and FieldNumPages automatically render the current page and total page count.
  • Borders – Adding a thin line (BorderStyle.Single) visually separates header/footer from the body.

Adding images or dynamic fields

If you need a company logo in the footer, simply duplicate the picture‑insertion code and adjust VerticalAlignment to Bottom. For dynamic fields such as the current date:

ftrPara.AppendField(FieldType.FieldDate);
Enter fullscreen mode Exit fullscreen mode

Common pitfalls (and how to avoid them)

Missing image path – Ensure the image file exists relative to the executable or use an absolute path.

Incorrect alignment – Remember that HorizontalAlignment is applied to the paragraph, not the picture.

License restrictions – The free edition truncates images larger than 500 KB; acquire a license for production use.

Tip: Always set section.PageSetup.DifferentFirstPageHeaderFooter = true before adding content if the first page requires a unique header (e.g., a title page).

Extending the solution

Different headers/footers per section

Section sec2 = doc.AddSection();
sec2.PageSetup.DifferentFirstPageHeaderFooter = true;
HeaderFooter firstPageHeader = sec2.HeadersFooters.FirstPageHeader;
firstPageHeader.AddParagraph().AppendText("Chapter 2 – Overview");
Enter fullscreen mode Exit fullscreen mode

Using templates

Create a Word template (Template.docx) containing a pre‑designed header/footer, then load it:

Document tmpl = new Document("Template.docx");
Document newDoc = tmpl.Clone();
Enter fullscreen mode Exit fullscreen mode

The cloned document inherits all header/footer settings, allowing you to focus only on body content.

Performance tips for large batches

  • Reuse a single Document instance when processing many files in a loop; call doc.Clear() after saving.
  • Disable unnecessary features (e.g., doc.LayoutOptions.EnableHyphenation = false).
  • Run the process in parallel only if the CPU and I/O resources can handle it; Spire.Doc is thread‑safe for read‑only operations.

Conclusion

Programmatically inserting a header and footer in Word documents becomes trivial with Spire.Doc for .NET. By following the steps above—installing the NuGet package, creating a document, configuring header/footer content, and handling common issues—you can generate consistent, professional‑looking files at scale. Try the sample code, adapt it to your own templates, and explore additional Spire.Doc features such as tables, charts, and mail‑merge to further automate your document workflow. Happy coding!

Top comments (0)