How to create automatically for every page footer in docx using C#

EmaLac 1 Reputation point
2021-05-20T10:52:26.687+00:00

I am creating a docx and I need a footer (for each page of a document) with timestamp and page (in this format: [present page] of [total pages].
Every post/code I've read online seems to indicate that I must create a footer manually for every page and write the page information manually: is it true? Is it not possible to write code in a way that, appended a footer to the main document, the docx automatically create itself every footer populating it with the right information?

Any advice?

Developer technologies C#
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-05-20T14:32:43+00:00

    From what I've seen in the documentation pages you need to add the footer to each page. This code project article has a decent code sample using OpenXML for Word. To get a understanding of footers see these docs.

    A basic code sample

    private static Footer GeneratePageFooterPart(string FooterText)  
    {  
        var element =  
            new Footer(  
                new Paragraph(  
                    new ParagraphProperties(  
                        new ParagraphStyleId() { Val = "Footer" }),  
                    new Run(  
                        new Text(FooterText),  
                        // *** Adaptation: This will output the page number dynamically ***  
                        new SimpleField() { Instruction = "PAGE" })  
                ));  
      
        return element;  
    }  
    

    And if you are not currently working with OpenXML see my Microsoft article Office Word Basic operations: Open XML SDK 2.5 Office Word documents were there is a validator method to check if code written is valid markup for a word document..

    Why use OpenXml? Performance, more control over generating files while the disadvantage is generally more code and not always the best documentation.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.