Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically add a page number in footer in Microsoft OXML c#

I'm creating a word document using OXML in Visual Studio. I don't know how long it is going to be and I need to add a simple page number in the footer of the document.

To generate headers and footers I used this: https://msdn.microsoft.com/en-us/library/ee355228(v=office.12).aspx

As I understand, this presets the default headers/footers before I even write anything in the document. So I'm not quite sure if I can add page numbering to this? I'd really appreciate the help, because I've been stuck on this for a whole day...

like image 370
Dueldogg Avatar asked Jul 18 '16 07:07

Dueldogg


1 Answers

You can add dynamic page numbers by adding a SimpleField with an Instruction of "PAGE". Word will automatically update any such field with the correct page number.

In order to code that you can adapt the GeneratePageFooterPart in the link you provided to include a SimpleField in the Run that gets added to the Footer:

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;
}

Note that you can change the format of the page number by postfixing the PAGE text. From the Ecma Office Open XML Part 1 - Fundamentals And Markup Language Reference.pdf:

When the current page number is 19 and the following fields are updated:

PAGE
PAGE \* ArabicDash
PAGE \* ALPHABETIC
PAGE \* roman

the results are:

19
- 19 -
S
xix

So to get roman numerals for example you would need to change the SimpleField line of code above to:

new SimpleField() { Instruction = "PAGE \\* roman" })

or (if you prefer)

new SimpleField() { Instruction = @"PAGE \* roman" })
like image 67
petelids Avatar answered Nov 09 '22 20:11

petelids