question

emalac avatar image
0 Votes"
emalac asked karenpayneoregon answered

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

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?

dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered

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.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.