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" })