Bug with PAGE fields (Word for JAVA)

1) problem:
it is not possible to insert few PAGE fields to same document

2) source code that does not work as expected:

....
String fileName = "test-page-fields.docx";
Document doc = new Document();
DocumentBuilder documentBuilder = new DocumentBuilder(doc);
documentBuilder.write("p");
documentBuilder.insertField("PAGE");
documentBuilder.insertBreak(BreakType.PAGE_BREAK);
doc.updateFields();

// doc.save(fileName);
// doc = new Document(fileName);
// documentBuilder = new DocumentBuilder(doc);
// documentBuilder.moveToDocumentEnd();

documentBuilder.write("p");
documentBuilder.insertField("PAGE");
doc.updateFields();
doc.save(fileName);
....

it produce Word file with one PAGE field only but expected result is to have 2 bookmarks.

see: 1-no-second-field.png
see: 1-no-second-field.docx

3) source code with workaround:

....
String fileName = "test-page-fields.docx";
Document doc = new Document();
DocumentBuilder documentBuilder = new DocumentBuilder(doc);
documentBuilder.write("p");
documentBuilder.insertField("PAGE");
documentBuilder.insertBreak(BreakType.PAGE_BREAK);
doc.updateFields();

doc.save(fileName);
doc = new Document(fileName);
documentBuilder = new DocumentBuilder(doc);
documentBuilder.moveToDocumentEnd();

documentBuilder.write("p");
documentBuilder.insertField("PAGE");
doc.updateFields();
doc.save(fileName);
....

it produce Word file with 2 PAGE fields as expected.

see: 2-second-field-exists.png
see: 2-second-field-exists.docx

4) question:
is there another way to insert few PAGE fields other then found as workaround?

Hi there,

Thanks for your inquiry. Please use DocumentBuilder.InsertField method (String, String) to insert a page field in the document. This will fix the issue which you are facing. Please let us know if you have any more queries.


Document doc = new Document();

DocumentBuilder documentBuilder = new DocumentBuilder(doc);

documentBuilder.write("p");

documentBuilder.insertField("PAGE", "");

documentBuilder.insertBreak(BreakType.PAGE_BREAK);

documentBuilder.write("p");

documentBuilder.insertField("PAGE", "");

doc.updateFields();

doc.save(MyDir + "Out.docx");