Home » c# » asp.net mvc – C# Openxml word document add page number to existing footer

asp.net mvc – C# Openxml word document add page number to existing footer

Posted by: admin February 21, 2020 Leave a comment

Questions:

I’m trying to add page numbers/pagination really to the footers of a word document programatically and so far I’ve got the numbers to show up but the footer seems to have created a big margin vertically when it should be smaller thus pushing some of my content to a new page when it should all fit in one single page.

enter image description here

The red box indicates a picture, I can’t show that for obvious reasons but as you can see there’s a huge gap in the footer which pushes some of my table contents to a new page. Is anyone able to pinpoint the issue in my code that’s causing this? as well as if it’s possible to have my number format be like Page 1 of XX instead of just the page number.

var stream = new MemoryStream();
stream.Write(wordDocBytes, 0, wordDocbytes.Length);
using(WordprocessingDocument doc = WordprocessingDocument.Open(stream, true)) 
{
    foreach(var footer in doc.MainDocumentPart.FooterParts) 
    {
        var simpleField = new SimpleField() { Instruction = "PAGE" };
        footer.Footer.Append(simpleField);
    }

    doc.MainDocumentPart.Document.Save();
}

stream.Seek(0, SeekOrigin.Begin);
return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "test.docx");

Thanks

How to&Answers: