Hello,
I have the need to migrate many word documents into a new format.
So my idea is:
- setup a new document word with new header, footer.
- create a program that load each old word document (content only, no header, no footer!)
- for each document load the new template word, insert the content and save to a new document.
Is that possible and do anyone have a sample for me?
I seek the documentation but only find part where I can add word to another.
Thanks for your inquiry. The code should be very simple like this:
Document docOld = new Document(MyDir + @"old.docx");
Document docNew = (Document)docOld.Clone(true);
foreach (Section sec in docNew)
{
sec.ClearHeadersFooters();
// here you can set new header/footer per section
}
docNew.Save(MyDir + @"new.docx");
Also, please check following article for adding new headers/footers in new document:
Hello,
thank you for the example.
Is it somehow possible then to load the header and footer from another document into memory so I can place them in the foreach part?
Thanks for your inquiry. You can copy all headers/footers from one document to another using the following code:
// Open A document
Document docA = new Document(MyDir + "a.docx");
DocumentBuilder builderA = new DocumentBuilder(docA);
// Open B document
Document docB = new Document(MyDir + "b.docx");
// Loop through all sections in the B document
foreach (Section sectB in docB.Sections)
{
Section sectA = null;
int sectBIndex = docB.Sections.IndexOf(sectB);
// Check whether document A conteins section with same index
if (docA.Sections.Count > sectBIndex)
{
// Get correcponding section
sectA = docA.Sections[sectBIndex];
}
else
{
// Insert empty section
builderA.MoveToDocumentEnd();
builderA.InsertBreak(BreakType.SectionBreakContinuous);
sectA = builderA.CurrentSection;
}
// Loop throught all Headers/Footers in the B document
foreach (HeaderFooter hfB in sectB.HeadersFooters)
{
// Check whether current section from docA conteins
// Header/Footer with the same type as h/f from docB
if (sectA.HeadersFooters[hfB.HeaderFooterType] != null)
{
// Append content from h/f B to h/f A
foreach (Node childB in hfB.ChildNodes)
{
// Import node
Node childA = docA.ImportNode(childB, true, ImportFormatMode.KeepSourceFormatting);
// Appent node to h/f
sectA.HeadersFooters[hfB.HeaderFooterType].AppendChild(childA);
}
}
else
{
// Copy whole h/f
Node hfA = docA.ImportNode(hfB, true, ImportFormatMode.KeepSourceFormatting);
// Insert h/f
sectA.HeadersFooters.Add(hfA);
}
}
}
// Save output document
docA.Save(MyDir + "out.docx");