Remove header from the word document in C#

2014-10-21 09:04:57 Written by  support iceblue
Rate this item
(0 votes)

Spire.Doc for .NET enables developers to add, modify and remove text and Image header for word documents easily. We have already shown you how to insert header for all the pages and only add header for the first page in word document in C#. This article will focus on demonstrate how to remove the header for all the pages in word document and only remove the header for the first page in C#.

In the example, we will load a word document with headers. And then we will show you how to remove the header only from the first page and all the pages independently.

Check the word document with headers:

How to remove header from the word document in C#

Step 1: Create a new document and load from file.

Document doc = new Document();
doc.LoadFromFile("Sample.docx");

Step 2: Get the first section of document.

Section section = doc.Sections[0];

Step 3: Remove the header only from the first page of word document.

//This is necessary
section.PageSetup.DifferentFirstPageHeaderFooter = true;
section.HeadersFooters.FirstPageHeader.ChildObjects.Clear();

Step 4: Remove the header for all the pages.

section.HeadersFooters.Header.ChildObjects.Clear();

Step 5: Save the document to file.

doc.SaveToFile("output.docx", FileFormat.Docx);

Effective screenshot of the removal of the header:

How to remove header from the word document in C#

Full codes:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Doc;
using System.Drawing;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace RemoveHeader
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("Blues.docx");
            Section section = doc.Sections[0];
            //This is necessary
            section.PageSetup.DifferentFirstPageHeaderFooter = true;
            section.HeadersFooters.FirstPageHeader.ChildObjects.Clear();
            //section.HeadersFooters.Header.ChildObjects.Clear();
            doc.SaveToFile("output.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("output.docx");
        }
    }
}

Additional Info

  • tutorial_title:
Last modified on Friday, 03 September 2021 03:56