i have a scenario where i have to replace header and footer of an existing document. i have found an article in msdn
private void ReplaceHeaderAndFooter(WordprocessingDocument docx, byte[] byteHeaderArray, byte[] byteFooterArray)
{
docx.MainDocumentPart.DeleteParts(docx.MainDocumentPart.HeaderParts);
docx.MainDocumentPart.DeleteParts(docx.MainDocumentPart.FooterParts);
DocumentFormat.OpenXml.Packaging.HeaderPart headerPart = docx.MainDocumentPart.AddNewPart<HeaderPart>();
DocumentFormat.OpenXml.Packaging.FooterPart footerPart = docx.MainDocumentPart.AddNewPart<FooterPart>();
string strHeaderPartID = docx.MainDocumentPart.GetIdOfPart(headerPart);
string strFooterPartID = docx.MainDocumentPart.GetIdOfPart(footerPart);
using (MemoryStream stream = new MemoryStream())
{
stream.Write(byteHeaderArray, 0, byteHeaderArray.Length);
using (WordprocessingDocument wdDocSource =
WordprocessingDocument.Open(stream, true))
{
DocumentFormat.OpenXml.Packaging.HeaderPart firstHeader = wdDocSource.MainDocumentPart.HeaderParts.FirstOrDefault();
if (firstHeader != null)
{
headerPart.FeedData(firstHeader.GetStream());
}
}
}
using (MemoryStream stream = new MemoryStream())
{
stream.Write(byteFooterArray, 0, byteFooterArray.Length);
using (WordprocessingDocument wdDocSource = WordprocessingDocument.Open(stream, true))
{
DocumentFormat.OpenXml.Packaging.FooterPart firstFooter = wdDocSource.MainDocumentPart.FooterParts.FirstOrDefault();
if (firstFooter != null)
{
footerPart.FeedData(firstFooter.GetStream());
}
}
}
IEnumerable<DocumentFormat.OpenXml.Wordprocessing.SectionProperties> sections = docx.MainDocumentPart.Document.Body.Elements<DocumentFormat.OpenXml.Wordprocessing.SectionProperties>();
foreach (var section in sections)
{
section.RemoveAllChildren<DocumentFormat.OpenXml.Wordprocessing.HeaderFooterReferenceType>();
section.PrependChild<DocumentFormat.OpenXml.Wordprocessing.HeaderReference>(new DocumentFormat.OpenXml.Wordprocessing.HeaderReference() { Type = DocumentFormat.OpenXml.Wordprocessing.HeaderFooterValues.Default, Id = strHeaderPartID });
section.PrependChild<DocumentFormat.OpenXml.Wordprocessing.FooterReference>(new DocumentFormat.OpenXml.Wordprocessing.FooterReference() { Type = DocumentFormat.OpenXml.Wordprocessing.HeaderFooterValues.Default, Id = strFooterPartID });
}
}
If you use merge fields in the document header or footer you will get trouble in replacing the header or footer. In that case you have to replace the below
DocumentFormat.OpenXml.Packaging.FooterPart firstFooter = wdDocSource.MainDocumentPart.FooterParts.FirstOrDefault();
With
DocumentFormat.OpenXml.Packaging.FooterPart firstFooter = wdDocSource.MainDocumentPart.FooterParts.ToList()[1];