'Omit last page on NUMPAGES Aspose .net

I'm looking for a solution in ASPOSE .Net to decrement the NUMPAGES. Reason is that I don't want to count the last page of the document. Here is what I tried so far:

builder.Write("Page ");
builder.InsertField("Page", "");
builder.Write(" of ");
builder.InsertField("NUMPAGES", $"{(doc.PageCount - 1)}");

// Another try in separate build
builder.InsertField("NUMPAGES - 1", "");

// Another try in separate build
builder.InsertField("NUMPAGES", "NUMPAGES - 1");

Document either doesn't display anything or count the last page as well.



Solution 1:[1]

You should use formula and nested NUMPAGES field to get the desired output. Field code in your MS Word document should look like this: {={NUMPAGES}-1}. To insert such field using Aspose.Words you can use code like this:

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert formula field
Field formula = builder.InsertField("=", "");
// Move document builder inside field code of the inserted field
// And put NUMPAGES field in it.
builder.MoveTo(formula.Separator);
builder.InsertField("NUMPAGES");
builder.Write("-1");

doc.UpdateFields();
doc.Save(@"C:\Temp\out.docx");

Please see Aspose.Words documentation to learn how to work with fields.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alexey Noskov