We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Remove all headers and footers from a directory of documents

Hello,

We needed to clear the headers and footers of a few hundred documents so i prepared this crude code snippet in ~15 minutes. Just wanted to share it incase any one looks for a quick fix like I did.



Aspose.Words.License license = new Aspose.Words.License();
license.SetLicense(“ADD LICENSE HERE”);

string baseDir = @“C:\DirectoryContainingDocs”;
var files = Directory.GetFiles(baseDir, “*”, SearchOption.AllDirectories);


string outputBaseDir = @“C:\Output”;
int loopIndex = 0;
foreach (var file in files)
{
Console.WriteLine(string.Format(“Processing {0} / {1}”, loopIndex, files.Length));
loopIndex++;
int index = new List(file.ToCharArray()).LastIndexOf(’\’);
string fileName = file.Substring(index + 1, file.Length - index - 1);
string newDir = file.Replace(baseDir, outputBaseDir).Replace(fileName, string.Empty);
Directory.CreateDirectory(newDir);

Document doc = new Document(file);

foreach (Section section in doc)
{
// Up to three different footers are possible in a section (for first, even and odd pages).
// We check and delete all of them.
HeaderFooter headerfooter;

headerfooter = section.HeadersFooters[HeaderFooterType.FooterFirst];
if (headerfooter != null)
headerfooter.Remove();

// Primary footer is the footer used for odd pages.
headerfooter = section.HeadersFooters[HeaderFooterType.FooterPrimary];
if (headerfooter != null)
headerfooter.Remove();

headerfooter = section.HeadersFooters[HeaderFooterType.FooterEven];
if (headerfooter != null)
headerfooter.Remove();

headerfooter = section.HeadersFooters[HeaderFooterType.HeaderFirst];
if (headerfooter != null)
headerfooter.Remove();

// Primary footer is the footer used for odd pages.
headerfooter = section.HeadersFooters[HeaderFooterType.HeaderPrimary];
if (headerfooter != null)
headerfooter.Remove();

headerfooter = section.HeadersFooters[HeaderFooterType.HeaderEven];
if (headerfooter != null)
headerfooter.Remove();
}

doc.Save(newDir + fileName);
}

Hi there,


Thanks for sharing the code example. We always appreciate positive feedback from our customers. You may also remove header/footer from a section using Section.HeadersFooters.Clear method. Hope this helps you.

Document doc = new Document(MyDir + “in.docx”);<o:p></o:p>

foreach (Section section in doc.Sections)

{

section.HeadersFooters.Clear();

}