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 in advance.
Yves
Hi Yves,
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");
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?
Best regards,Yves
Hi Yves,
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");
Hello,
I tried your code and it works so far, but only for the first page header and footer.
I have documents where
- first header and footer differs from the following header/footers
- header and footer differs on even and odd pages
How can I replace those headers- and footers, too?
***
EDIT: I found out that my template just need the different header- / footer options as well.