You need to create a complex field. A complex field allows you to create a formula using other fieldcodes such as the NUMPAGES
field code. A complex field consists of multiples parts on the run level. A complex field is created using the FieldChar
class (microsoft docs). I have shorty described the purpose of each part of the complex field in the code comments below:
static void Main(string[] args)
{
using(WordprocessingDocument document = WordprocessingDocument.Open(@"C:\Users\test\document.docx", true))
{
// get the first paragrahp of document
Paragraph paragraph = document.MainDocumentPart.Document.Descendants<Paragraph>().First();
// clean the paragraph
paragraph.Descendants<Run>().ToList().ForEach(r => r.Remove());
// construct a complex field
// the start field char signals the start of a complex field
Run fieldStartRun = new Run(new FieldChar() { FieldCharType = FieldCharValues.Begin });
// the field code singals the field consists of a formula -> =
Run fieldFormulaCode = new Run(new FieldCode() { Space = SpaceProcessingModeValues.Preserve, Text = " = " });
// the simple field singals we want to work with the NUMPAGES field code
SimpleField pageNumberField = new SimpleField() { Instruction = "NUMPAGES" };
// The addition field code signals we want to add 2 to the NUMPAGES field
Run fieldFormulaAdditionCode = new Run(new FieldCode() { Space = SpaceProcessingModeValues.Preserve, Text = " + 2 " });
// Then end fieldchar signals the end of the complex field
Run fieldEndRun = new Run(new FieldChar() { FieldCharType = FieldCharValues.End });
// append to the paragraph
paragraph.Append(fieldStartRun, fieldFormulaCode, pageNumberField, fieldFormulaAdditionCode, fieldEndRun);
}
}
If you do not have it already you can always download the openxml SDK tool which can guide in you in how to build your WordprocessingML. You can find it here: Microsoft download center.