1

I'm trying to generate a word document in .Net with Open XML. The problem is with the footer, simple text added. Could I add a formula where the Instruction (NUMPAGES) will be reduced by 1?

Example

run_page = new Run(new Text("Página ") { Space = SpaceProcessingModeValues.Preserve },               
           new SimpleField() { Instruction = "PAGE"},
           new Text(" de ") { Space = SpaceProcessingModeValues.Preserve },
           new SimpleField() { Instruction = "NUMPAGES - 1"});

Do I need to nest SimpleFields to make it? How to nest?

Thanks!

ihimv
  • 1,308
  • 12
  • 25

1 Answers1

0

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

Discobarry
  • 64
  • 3