Free Support Forum -

Wrong page numbers in DOCX when using unlinkFields

Dear Aspose
We’re using Aspose.Words for Java for merging fields in word documents. In the result document we want the fields unlinked therefore we’re calling unlinkFields() on Document. But this turned out to cause problems with page numbering. When this method is called every page has number 3.
Please see attached document and code snippet.
test document with (10.6 KB)

Code snippet:

    FileInputStream fileInputStream = new FileInputStream("test document with numbers.docx");
    Document doc = new Document(fileInputStream);

    doc.getMailMerge().execute(new String[0], new Object[0]);

    FileOutputStream outputStream = new FileOutputStream("output.docx");, SaveFormat.DOCX);

Aspose.Words version used: 18.5

Result document: (10.4 KB)

Please advise what can we do to fix this?



Thanks for your inquiry. You are facing the expected behavior of Aspose.Words. Please note that Document.UnlinkFields method replaces all the fields in the whole document with their most recent results. The Page field is in the footer of document. The most recent result is 3. This is the reason you are getting 3 on all pages. To check this behavior, you can remove the page field from the document using MS Word and replace it with any number. You will see that number on all pages.

Thanks for you answer.
I’ve manged to workaround this with this code:

 FieldCollection fields = doc.getRange().getFields();
 for (Field field : fields) {
     if (field.getType() != FieldType.FIELD_PAGE) {



Thanks for your feedback. It is nice to hear from you that you have found the workaround of your issue. Document.getRange().getFields() returns the fields from the whole document including header and footer. In your case, we suggest you please use Body.getRange().getFields() method as shown below. Hope this helps you.

Document doc = new Document(MyDir + "test document with numbers.docx");
for(Section section : doc.getSections())
    FieldCollection fields = section.getBody().getRange().getFields();
    for (Field field : fields) {
} + "18.7.docx");

Thanks for the tip and thanks for your help.