none
Add Different Header and Footer on pages Office OpenXML SDK 2.0 RRS feed

  • Question

  • I am trying to add different header and footer on first page and subsequent default pages in word document using Office Open XML SDK 2.0. But it only adds default page header and not first page. Kindly refer to code below. I appreciate if someone can help me out, as i am not able to figure out what i am doing wrong.

    In Text.docx fill in more than one page so the we have header and footers in more than 1 page.

    Calling Code:

    string strTemplate = ConfigurationManager.AppSettings["WordDoc"] + "Test.docx"; string
    DestinationPath = ConfigurationManager.AppSettings["WordDoc"] + "P_" + "Test.docx";
    File.Copy(strTemplate, DestinationPath, true);
    
    //I have created a class file Office, with methods to perform functions.
    Office officeLetter = new Office(); 
    officeLetter.Open(DestinationPath);
    officeLetter.AddHeaderAndFooter(); 
    
    officeLetter.Close()

    Class File:
    
    using DocumentFormat.OpenXml;
    using DocumentFormat.OpenXml.Packaging;
    using DocumentFormat.OpenXml.Wordprocessing;
    using Oracle.DataAccess.Client;
    using System;
    using System.Configuration;
    using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    using System.Collections.Generic;
    
    
    public class Office{
    
     protected WordprocessingDocument Document;
    
    
    public WordprocessingDocument Open(string documentName, bool openMode = true)
    {
        WordprocessingDocument document = null;
        try
        {
        document = WordprocessingDocument.Open(documentName, openMode);
        }
        catch //(Exception ex)
        {
        throw;
        }
    
        this.Document = document;
        return document;
    }
    
    public void Close()
    {
        this.Document.Close();
    }
    
    public void AddHeaderAndFooter()
    {
    
        // Get the main document part
        var mainPart = Document.MainDocumentPart;
    
        // Delete the existing header and footer parts
        mainPart.DeleteParts(mainPart.HeaderParts);
        mainPart.DeleteParts(mainPart.FooterParts);
    
        // Create a new header and footer parts for first and default pages
        HeaderPart headerPart = mainPart.AddNewPart<HeaderPart>();
        FooterPart footerPart = mainPart.AddNewPart<FooterPart>();
    
        HeaderPart defaultHeaderPart = mainPart.AddNewPart<HeaderPart>();
        FooterPart defaultFooterPart = mainPart.AddNewPart<FooterPart>();
    
        // Get Id of the headerPart and footer parts
        string headerPartId = mainPart.GetIdOfPart(headerPart);
        string footerPartId = mainPart.GetIdOfPart(footerPart);
        string defaultHeaderPartId = mainPart.GetIdOfPart(defaultHeaderPart);
        string defaultFooterPartId = mainPart.GetIdOfPart(defaultFooterPart);
    
        GenerateHeaderPartContentFirst(headerPart);
        GenerateHeaderPartContent(defaultHeaderPart);
        GenerateFooterPartContentFirst(footerPart);
        GenerateFooterPartContent(defaultFooterPart);
    
        // Get SectionProperties and Replace HeaderReference and FooterRefernce with new Id
        IEnumerable<SectionProperties> sections = mainPart.Document.Body.Elements<SectionProperties>();
    
        foreach (var section in sections)
        {
        // Delete existing references to headers and footers
        section.RemoveAllChildren<HeaderReference>();
        section.RemoveAllChildren<FooterReference>();
    
        // Create the new header and footer reference node
        section.PrependChild<HeaderReference>(new HeaderReference() { Id = headerPartId, Type = HeaderFooterValues.First });
        section.PrependChild<HeaderReference>(new HeaderReference() { Id = defaultHeaderPartId, Type = HeaderFooterValues.Default });
        section.PrependChild<FooterReference>(new FooterReference() { Id = footerPartId, Type = HeaderFooterValues.First });
        section.PrependChild<FooterReference>(new FooterReference() { Id = defaultFooterPartId, Type = HeaderFooterValues.Default });
        }
        mainPart.Document.Save();
    }
    
    public void GenerateHeaderPartContent(HeaderPart part)
    {
        Header header1 = new Header() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "w14 wp14" } };
        header1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
        header1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
        header1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
        header1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
        header1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
        header1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
        header1.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
        header1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
        header1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
        header1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
        header1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
        header1.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
        header1.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
        header1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
        header1.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");
    
        Paragraph paragraph1 = new Paragraph() { RsidParagraphAddition = "00164C17", RsidRunAdditionDefault = "00164C17" };
        Paragraph paragraph2 = new Paragraph();
        ParagraphProperties paragraphProperties1 = new ParagraphProperties();
        ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Header" };
    
        paragraphProperties1.Append(paragraphStyleId1);
    
        Run run1 = new Run();
        Text text1 = new Text();
        text1.Text = "Default Header";
    
        run1.Append(text1);
    
        paragraph1.Append(paragraphProperties1);
        paragraph1.Append(run1);
    
        header1.Append(paragraph1);
    
        part.Header = header1;
    }
    
    public void GenerateHeaderPartContentFirst(HeaderPart part)
    {
        Header header1 = new Header() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "w14 wp14" } };
        header1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
        header1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
        header1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
        header1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
        header1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
        header1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
        header1.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
        header1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
        header1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
        header1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
        header1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
        header1.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
        header1.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
        header1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
        header1.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");
    
        Paragraph paragraph1 = new Paragraph() { RsidParagraphAddition = "00164C17", RsidRunAdditionDefault = "00164C17" };
        Paragraph paragraph2 = new Paragraph();
        ParagraphProperties paragraphProperties1 = new ParagraphProperties();
        ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Header" };
    
        paragraphProperties1.Append(paragraphStyleId1);
    
        Run run1 = new Run();
        Text text1 = new Text();
        text1.Text = "First Page Header";
    
        run1.Append(text1);
    
        paragraph1.Append(paragraphProperties1);
        paragraph1.Append(run1);
    
        header1.Append(paragraph1);
    
        part.Header = header1;
    }
    
    static void GenerateFooterPartContentFirst(FooterPart part)
    {
        Footer footer1 = new Footer() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "w14 wp14" } };
        footer1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
        footer1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
        footer1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
        footer1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
        footer1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
        footer1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
        footer1.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
        footer1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
        footer1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
        footer1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
        footer1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
        footer1.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
        footer1.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
        footer1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
        footer1.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");
    
        Paragraph paragraph1 = new Paragraph() { RsidParagraphAddition = "00164C17", RsidRunAdditionDefault = "00164C17" };
    
        ParagraphProperties paragraphProperties1 = new ParagraphProperties();
        ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Footer" };
    
        paragraphProperties1.Append(paragraphStyleId1);
    
        Run run1 = new Run();
        Text text1 = new Text();
        text1.Text = "First Footer";
    
        run1.Append(text1);
    
        paragraph1.Append(paragraphProperties1);
        paragraph1.Append(run1);
    
        footer1.Append(paragraph1);
    
        part.Footer = footer1;
    }
    
    static void GenerateFooterPartContent(FooterPart part)
    {
        Footer footer1 = new Footer() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "w14 wp14" } };
        footer1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
        footer1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
        footer1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
        footer1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
        footer1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
        footer1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
        footer1.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
        footer1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
        footer1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
        footer1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
        footer1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
        footer1.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
        footer1.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
        footer1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
        footer1.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");
    
        Paragraph paragraph1 = new Paragraph() { RsidParagraphAddition = "00164C17", RsidRunAdditionDefault = "00164C17" };
    
        ParagraphProperties paragraphProperties1 = new ParagraphProperties();
        ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Footer" };
    
        paragraphProperties1.Append(paragraphStyleId1);
    
        Run run1 = new Run();
        Text text1 = new Text();
        text1.Text = " Default Footer";
    
        run1.Append(text1);
    
        paragraph1.Append(paragraphProperties1);
        paragraph1.Append(run1);
    
        footer1.Append(paragraph1);
    
        part.Footer = footer1;
    }
    }



    Saturday, July 26, 2014 9:43 AM

Answers

  • Hi,

    According to my investigation, there is a XML element named "TitlePage" missed.

    Please try:

    static void AddHeaderAndFooter(MainDocumentPart mainPart)
            {
                // Delete the existing header and footer parts
                mainPart.DeleteParts(mainPart.HeaderParts);
                mainPart.DeleteParts(mainPart.FooterParts);
    
                // Create a new header and footer parts for first and default pages
                HeaderPart headerPart = mainPart.AddNewPart<HeaderPart>();
                FooterPart footerPart = mainPart.AddNewPart<FooterPart>();
                HeaderPart defaultHeaderPart = mainPart.AddNewPart<HeaderPart>();
                FooterPart defaultFooterPart = mainPart.AddNewPart<FooterPart>();
    
                GenerateHeaderPartContentFirst(headerPart);
                GenerateHeaderPartContent(defaultHeaderPart);
                GenerateFooterPartContentFirst(footerPart);
                GenerateFooterPartContent(defaultFooterPart);
    
                // Get Id of the headerPart and footer parts
                string headerPartId = mainPart.GetIdOfPart(headerPart);
                string footerPartId = mainPart.GetIdOfPart(footerPart);
                string defaultHeaderPartId = mainPart.GetIdOfPart(defaultHeaderPart);
                string defaultFooterPartId = mainPart.GetIdOfPart(defaultFooterPart);
    
                // Get SectionProperties and Replace HeaderReference and FooterRefernce with new Id
                IEnumerable<SectionProperties> sections = mainPart.Document.Body.Elements<SectionProperties>();
    
                foreach (var section in sections)
                {
                    // Delete existing references to headers and footers
                    section.RemoveAllChildren<HeaderReference>();
                    section.RemoveAllChildren<FooterReference>();
                    section.RemoveAllChildren<TitlePage>();
    
                    // Create the new header and footer reference node
                    section.PrependChild<HeaderReference>(new HeaderReference() { Id = headerPartId, Type = HeaderFooterValues.First });
                    section.PrependChild<HeaderReference>(new HeaderReference() { Id = defaultHeaderPartId, Type = HeaderFooterValues.Default });
                    section.PrependChild<FooterReference>(new FooterReference() { Id = footerPartId, Type = HeaderFooterValues.First });
                    section.PrependChild<FooterReference>(new FooterReference() { Id = defaultFooterPartId, Type = HeaderFooterValues.Default });
                    section.PrependChild<TitlePage>(new TitlePage());
                }
                mainPart.Document.Save();
            }

    The result:

    Hope this helps.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Tuesday, July 29, 2014 5:44 AM
    Moderator

All replies

  • I don't see in your code that you include the TitlePage (<w:titlePg/>) property in the corresponding SectionProperties (w:sectPr) for the document Section that should show a First Page Header (or Footer). See

    http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.titlepage(v=office.14).aspx


    Cindy Meister, VSTO/Word MVP, my blog

    Monday, July 28, 2014 1:52 PM
    Moderator
  • Dear Cindy,

    Thankyou for your reply.

    My first page is not the title page. It is just a page with text in it. I am not treating it is a title page.

    Kindly see the below code. I have specified Type enum values of First and Default. Isn't this supposed to set header for first page and default page. If not, what does this type specify?

     // Create the new header and footer reference node
        section.PrependChild<HeaderReference>(new HeaderReference() { Id = headerPartId, Type = HeaderFooterValues.First });
        section.PrependChild<HeaderReference>(new HeaderReference() { Id = defaultHeaderPartId, Type = HeaderFooterValues.Default });
        section.PrependChild<FooterReference>(new FooterReference() { Id = footerPartId, Type = HeaderFooterValues.First });
        section.PrependChild<FooterReference>(new FooterReference() { Id = defaultFooterPartId, Type = HeaderFooterValues.Default });

    Also if this is not right and what you have mentioned regarding TitlePage property. Can you please append that in the above code and help me in that. I don't find many examples related to it.

    Thanks.



    Monday, July 28, 2014 2:06 PM
  • Please read the article for which I gave you the link - that explains that BOTH things are needed and what happens if only one of the two is present.

    Create a new TitlePage object then append it directly to the SectionProperties - no need to set the value. As the article indicates, the required "true" value is the default. In my experience, it's best if this is one of the last elements in the WordOpenXML for the SectionProperties.

    If you still have questions, I recommend you

    1) Look at the native XML for w:sectPr  in the document.xml file and

    2) Look at the code the Open XML SDK Productivity Tool generates for creating the document.xml to see th use of the object.


    Cindy Meister, VSTO/Word MVP, my blog

    Monday, July 28, 2014 2:22 PM
    Moderator
  • Hi,

    According to my investigation, there is a XML element named "TitlePage" missed.

    Please try:

    static void AddHeaderAndFooter(MainDocumentPart mainPart)
            {
                // Delete the existing header and footer parts
                mainPart.DeleteParts(mainPart.HeaderParts);
                mainPart.DeleteParts(mainPart.FooterParts);
    
                // Create a new header and footer parts for first and default pages
                HeaderPart headerPart = mainPart.AddNewPart<HeaderPart>();
                FooterPart footerPart = mainPart.AddNewPart<FooterPart>();
                HeaderPart defaultHeaderPart = mainPart.AddNewPart<HeaderPart>();
                FooterPart defaultFooterPart = mainPart.AddNewPart<FooterPart>();
    
                GenerateHeaderPartContentFirst(headerPart);
                GenerateHeaderPartContent(defaultHeaderPart);
                GenerateFooterPartContentFirst(footerPart);
                GenerateFooterPartContent(defaultFooterPart);
    
                // Get Id of the headerPart and footer parts
                string headerPartId = mainPart.GetIdOfPart(headerPart);
                string footerPartId = mainPart.GetIdOfPart(footerPart);
                string defaultHeaderPartId = mainPart.GetIdOfPart(defaultHeaderPart);
                string defaultFooterPartId = mainPart.GetIdOfPart(defaultFooterPart);
    
                // Get SectionProperties and Replace HeaderReference and FooterRefernce with new Id
                IEnumerable<SectionProperties> sections = mainPart.Document.Body.Elements<SectionProperties>();
    
                foreach (var section in sections)
                {
                    // Delete existing references to headers and footers
                    section.RemoveAllChildren<HeaderReference>();
                    section.RemoveAllChildren<FooterReference>();
                    section.RemoveAllChildren<TitlePage>();
    
                    // Create the new header and footer reference node
                    section.PrependChild<HeaderReference>(new HeaderReference() { Id = headerPartId, Type = HeaderFooterValues.First });
                    section.PrependChild<HeaderReference>(new HeaderReference() { Id = defaultHeaderPartId, Type = HeaderFooterValues.Default });
                    section.PrependChild<FooterReference>(new FooterReference() { Id = footerPartId, Type = HeaderFooterValues.First });
                    section.PrependChild<FooterReference>(new FooterReference() { Id = defaultFooterPartId, Type = HeaderFooterValues.Default });
                    section.PrependChild<TitlePage>(new TitlePage());
                }
                mainPart.Document.Save();
            }

    The result:

    Hope this helps.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Tuesday, July 29, 2014 5:44 AM
    Moderator
  • Hi George,

    Thanks a lot. Appreciate your help. 

    Kind Regards

    Wednesday, July 30, 2014 10:24 AM