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

2

5

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...

Conatus answered 18/7, 2016 at 7:17 Comment(0)
F
10

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" })
Fatherly answered 18/7, 2016 at 16:53 Comment(2)
What would the instruction be for something like "Page X of Y"? =)Ankylostomiasis
Glad my answer helped you @Ankylostomiasis - have you got it working as you want?Fatherly
O
1

Try this:

   private static void GenerateFooterPartContent(WordprocessingDocument package, string text = null)
    {
        FooterPart footerPart1 = package.MainDocumentPart.FooterParts.FirstOrDefault();
        if (footerPart1 == null)
        {
            footerPart1 = package.MainDocumentPart.AddNewPart<FooterPart>();
        }

        var relationshipId = package.MainDocumentPart.GetIdOfPart(footerPart1);
        // Get SectionProperties and set HeaderReference and FooterRefernce with new Id
        SectionProperties sectionProperties1 = new SectionProperties();
        FooterReference footerReference2 = new FooterReference() { Type = HeaderFooterValues.Default, Id = relationshipId };
        sectionProperties1.Append(footerReference2);
        package.MainDocumentPart.Document.Body.Append(sectionProperties1);


        Footer footer1 = new Footer();


        Paragraph paragraph2 = CreateParagraph(package, string.Empty, "Footer");
        Run r = new Run(new SimpleField() { Instruction = "DATE" });          

        paragraph2.Append(r);

        if (!string.IsNullOrWhiteSpace(text))
        {
            r = new Run();
            PositionalTab positionalTab1 = new PositionalTab() { Alignment = AbsolutePositionTabAlignmentValues.Center, 
                RelativeTo = AbsolutePositionTabPositioningBaseValues.Margin, 
                Leader = AbsolutePositionTabLeaderCharValues.None };

            r.Append(positionalTab1);
            paragraph2.Append(r);
            r = new Run(new Text(text) { Space = SpaceProcessingModeValues.Preserve });
            paragraph2.Append(r);
        }

        r = new Run();
        PositionalTab positionalTab2 = new PositionalTab() { Alignment = AbsolutePositionTabAlignmentValues.Right, 
            RelativeTo = AbsolutePositionTabPositioningBaseValues.Margin, 
            Leader = AbsolutePositionTabLeaderCharValues.None };

        r.Append(positionalTab2);
        paragraph2.Append(r);

        r = new Run(new Text("Page: ") { Space = SpaceProcessingModeValues.Preserve },
              // *** Adaptation: This will output the page number dynamically ***
              new SimpleField() { Instruction = "PAGE" },
              new Text(" of ") { Space = SpaceProcessingModeValues.Preserve },
              // *** Adaptation: This will output the number of pages dynamically ***
              new SimpleField() { Instruction = "NUMPAGES" });
        paragraph2.Append(r);

        footer1.Append(paragraph2);

        footerPart1.Footer = footer1;
    }

Refer to the following link for more instructions.

Otter answered 28/5, 2020 at 9:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.