/// <summary> /// Set a new header in a document /// </summary> /// <param name="header">XDocument containing the header to add in the document</param> /// <param name="type">The header part type</param> public static OpenXmlPowerToolsDocument SetHeader(WmlDocument doc, XDocument header, HeaderType type, int sectionIndex) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { // Removes the reference in the document.xml and the header part if those already // exist XElement headerReferenceElement = GetHeaderReference(document, type, sectionIndex); if (headerReferenceElement != null) { GetHeaderPart(document, type, sectionIndex).RemovePart(); headerReferenceElement.Remove(); } // Add the new header HeaderPart headerPart = document.MainDocumentPart.AddNewPart <HeaderPart>(); headerPart.PutXDocument(header); // Creates the relationship of the header inside the section properties in the document string relID = document.MainDocumentPart.GetIdOfPart(headerPart); AddHeaderReference(document, type, relID, sectionIndex); // add in the settings part the EvendAndOddHeaders. this element // allow to see the odd and even headers and headers in the document. SettingAccessor.AddEvenAndOddHeadersElement(document); } return(streamDoc.GetModifiedDocument()); } }
/// <summary> /// Adds a new header part in the document /// </summary> /// <param name="type">The footer part type</param> /// <returns>A XDocument contaning the added header</returns> public static XDocument AddNewHeader(WordprocessingDocument document, HeaderType type) { // Creates the new header part HeaderPart newHeaderPart = document.MainDocumentPart.AddNewPart <HeaderPart>(); XDocument emptyHeader = CreateEmptyHeaderDocument(); newHeaderPart.PutXDocument(emptyHeader); string newHeaderPartId = document.MainDocumentPart.GetIdOfPart(newHeaderPart); AddHeaderReference(document, type, newHeaderPartId, 0); return(emptyHeader); }