Copy Header/Footer between Word Documents in C#, VB.NET

When you create several Word documents that are closely related, you may want the header or footer of one document to be used as the header or footer of other documents. For example, you're creating internal documents with your company logo or name or other material been placed in header, you only have to create the header once and copy the header to other places.

In this article, I'll introduce you a simple and efficient solution to copy the entire header (including text and graphic) from one Word document and insert it to another.

Source Document:

Copy Header/Footer between Word Documents in C#, VB.NET

Detail Steps:

Step 1: Create a new instance of Document class and load the source file.

Document doc1 = new Document();
doc1.LoadFromFile("test1.docx");

Step 2: Get the header section from the source document.

HeaderFooter header = doc1.Sections[0].HeadersFooters.Header;

Step 3: Initialize a new instance of Document and load another file that you want to insert header.

Document doc2 = new Document("test2.docx");

Step 4: Call DocuentObject.Clone() method to copy each object in the header of source file, then call DocumentObjectCollection.Add() method to insert copied object into the header of destination file.

foreach (Section section in doc2.Sections)
{
    foreach (DocumentObject obj in header.ChildObjects)
    {
        section.HeadersFooters.Header.ChildObjects.Add(obj.Clone());
    }
}

Step 5: Save the changes and launch the file.

doc2.SaveToFile("test2.docx", FileFormat.Docx2013);
System.Diagnostics.Process.Start("test2.docx");

Destination Document:

Copy Header/Footer between Word Documents in C#, VB.NET

Full Code:

[C#]
Document doc1 = new Document();
doc1.LoadFromFile("test1.docx");
HeaderFooter header = doc1.Sections[0].HeadersFooters.Header;
Document doc2 = new Document("test2.docx");
foreach (Section section in doc2.Sections)
{
    foreach (DocumentObject obj in header.ChildObjects)
    {
        section.HeadersFooters.Header.ChildObjects.Add(obj.Clone());
    }
}
doc2.SaveToFile("test2.docx", FileFormat.Docx2013);
System.Diagnostics.Process.Start("test2.docx");
[VB.NET]
Dim doc1 As New Document()
doc1.LoadFromFile("test1.docx")
Dim header As HeaderFooter = doc1.Sections(0).HeadersFooters.Header
Dim doc2 As New Document("test2.docx")
For Each section As Section In doc2.Sections
	For Each obj As DocumentObject In header.ChildObjects
		section.HeadersFooters.Header.ChildObjects.Add(obj.Clone())
	Next
Next
doc2.SaveToFile("test2.docx", FileFormat.Docx2013)
System.Diagnostics.Process.Start("test2.docx")