com.aspose.words

Class FieldSeq

  • java.lang.Object
    • Field
      • com.aspose.words.FieldSeq
public class FieldSeq 
extends Field

Implements the SEQ field.
Sequentially numbers chapters, tables, figures, and other user-defined lists of items in a document.

Example:

Shows create numbering using SEQ fields.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// SEQ fields display a count that increments at each SEQ field.
// These fields also maintain separate counts for each unique named sequence
// identified by the SEQ field's "SequenceIdentifier" attribute.
// Insert a SEQ field that will display the current count value of "MySequence",
// after using the "ResetNumber" attribute to set it to 100.
builder.write("#");
FieldSeq fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
fieldSeq.setSequenceIdentifier("MySequence");
fieldSeq.setResetNumber("100");
fieldSeq.update();

Assert.assertEquals(" SEQ  MySequence \\r 100", fieldSeq.getFieldCode());
Assert.assertEquals("100", fieldSeq.getResult());

// Display the next number in this sequence with another SEQ field.
builder.write(", #");
fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
fieldSeq.setSequenceIdentifier("MySequence");
fieldSeq.update();

Assert.assertEquals("101", fieldSeq.getResult());

// Insert a level 1 heading.
builder.insertBreak(BreakType.PARAGRAPH_BREAK);
builder.getParagraphFormat().setStyle(doc.getStyles().get("Heading 1"));
builder.writeln("This level 1 heading will reset MySequence to 1");
builder.getParagraphFormat().setStyle(doc.getStyles().get("Normal"));

// Insert another SEQ field from the same sequence, and configure it to reset the count at every heading with 1.
builder.write("\n#");
fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
fieldSeq.setSequenceIdentifier("MySequence");
fieldSeq.setResetHeadingLevel("1");
fieldSeq.update();

// The above heading is a level 1 heading, so the count for this sequence is reset to 1.
Assert.assertEquals(" SEQ  MySequence \\s 1", fieldSeq.getFieldCode());
Assert.assertEquals("1", fieldSeq.getResult());

// Move to the next number of this sequence.
builder.write(", #");
fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
fieldSeq.setSequenceIdentifier("MySequence");
fieldSeq.setInsertNextNumber(true);
fieldSeq.update();

Assert.assertEquals(" SEQ  MySequence \\n", fieldSeq.getFieldCode());
Assert.assertEquals("2", fieldSeq.getResult());

doc.updateFields();
doc.save(getArtifactsDir() + "Field.SEQ.ResetNumbering.docx");

Example:

Shows how to combine table of contents and sequence fields.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// A TOC field can create an entry in its table of contents for each SEQ field found in the document.
// Each entry contains the paragraph that contains the SEQ field,
// and the number of the page that the field appears on.
FieldToc fieldToc = (FieldToc)builder.insertField(FieldType.FIELD_TOC, true);

// Configure this TOC field to only pick up SEQ fields that are within the bounds of a bookmark
// named "TOCBookmark", and also have a SequenceIdentifier attribute with a value of "MySequence".
fieldToc.setTableOfFiguresLabel("MySequence");
fieldToc.setBookmarkName("TOCBookmark");
builder.insertBreak(BreakType.PAGE_BREAK);

Assert.assertEquals(" TOC  \\c MySequence \\b TOCBookmark", fieldToc.getFieldCode());

// SEQ fields display a count that increments at each SEQ field.
// These fields also maintain separate counts for each unique named sequence
// identified by the SEQ field's "SequenceIdentifier" attribute.
// Insert a SEQ field that has a sequence identifier that matches the TOC's
// TableOfFiguresLabel attribute. This field will not create an entry in the TOC since it is outside
// the bookmark's bounds designated by "BookmarkName".
builder.write("MySequence #");
FieldSeq fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
fieldSeq.setSequenceIdentifier("MySequence");
builder.writeln(", will not show up in the TOC because it is outside of the bookmark.");

builder.startBookmark("TOCBookmark");

// This SEQ field's sequence matches the TOC's "TableOfFiguresLabel" attribute and is within the bookmark's bounds.
// The paragraph that contains this field will show up in the TOC as an entry.
builder.write("MySequence #");
fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
fieldSeq.setSequenceIdentifier("MySequence");
builder.writeln(", will show up in the TOC next to the entry for the above caption.");

// This SEQ field's sequence does not match the TOC's "TableOfFiguresLabel" attribute,
// and is within the bounds of the bookmark. Its paragraph will not show up in the TOC as an entry.
builder.write("MySequence #");
fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
fieldSeq.setSequenceIdentifier("OtherSequence");
builder.writeln(", will not show up in the TOC because it's from a different sequence identifier.");

// This SEQ field's sequence matches the TOC's "TableOfFiguresLabel" attribute, and is within the bounds of the bookmark.
// This field also references another bookmark. The contents of that bookmark will appear in the TOC entry for this SEQ field.
// The SEQ field itself will not display the contents of that bookmark.
fieldSeq = (FieldSeq)builder.insertField(FieldType.FIELD_SEQUENCE, true);
fieldSeq.setSequenceIdentifier("MySequence");
fieldSeq.setBookmarkName("SEQBookmark");
Assert.assertEquals(" SEQ  MySequence SEQBookmark", fieldSeq.getFieldCode());

// Create a bookmark with contents that will show up in the TOC entry due to the above SEQ field referencing it.
builder.insertBreak(BreakType.PAGE_BREAK);
builder.startBookmark("SEQBookmark");
builder.write("MySequence #");
fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
fieldSeq.setSequenceIdentifier("MySequence");
builder.writeln(", text from inside SEQBookmark.");
builder.endBookmark("SEQBookmark");

builder.endBookmark("TOCBookmark");

doc.updateFields();
doc.save(getArtifactsDir() + "Field.SEQ.Bookmark.docx");

Example:

Shows how to populate a TOC field with entries using SEQ fields.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// A TOC field can create an entry in its table of contents for each SEQ field found in the document.
// Each entry contains the paragraph that includes the SEQ field and the page's number that the field appears on.
FieldToc fieldToc = (FieldToc)builder.insertField(FieldType.FIELD_TOC, true);

// SEQ fields display a count that increments at each SEQ field.
// These fields also maintain separate counts for each unique named sequence
// identified by the SEQ field's "SequenceIdentifier" attribute.
// Use the "TableOfFiguresLabel" attribute to name a main sequence for the TOC.
// Now, this TOC will only create entries out of SEQ fields with their "SequenceIdentifier" set to "MySequence".
fieldToc.setTableOfFiguresLabel("MySequence");

// We can name another SEQ field sequence in the "PrefixedSequenceIdentifier" attribute.
// SEQ fields from this prefix sequence will not create TOC entries. 
// Every TOC entry created from a main sequence SEQ field will now also display the count that
// the prefix sequence is currently on at the primary sequence SEQ field that made the entry.
fieldToc.setPrefixedSequenceIdentifier("PrefixSequence");

// Each TOC entry will display the prefix sequence count immediately to the left
// of the page number that the main sequence SEQ field appears on.
// We can specify a custom separator that will appear between these two numbers.
fieldToc.setSequenceSeparator(">");

Assert.assertEquals(" TOC  \\c MySequence \\s PrefixSequence \\d >", fieldToc.getFieldCode());

builder.insertBreak(BreakType.PAGE_BREAK);

// There are two ways of using SEQ fields to populate this TOC.
// 1 -  Inserting a SEQ field that belongs to the TOC's prefix sequence:
// This field will increment the SEQ sequence count for the "PrefixSequence" by 1.
// Since this field does not belong to the main sequence identified
// by the "TableOfFiguresLabel" attribute of the TOC, it will not appear as an entry.
FieldSeq fieldSeq = (FieldSeq)builder.insertField(FieldType.FIELD_SEQUENCE, true);
fieldSeq.setSequenceIdentifier("PrefixSequence");
builder.insertParagraph();

Assert.assertEquals(" SEQ  PrefixSequence", fieldSeq.getFieldCode());

// 2 -  Inserting a SEQ field that belongs to the TOC's main sequence:
// This SEQ field will create an entry in the TOC.
// The TOC entry will contain the paragraph that the SEQ field is in and the number of the page that it appears on.
// This entry will also display the count that the prefix sequence is currently at,
// separated from the page number by the value in the TOC's SeqenceSeparator attribute.
// The "PrefixSequence" count is at 1, this main sequence SEQ field is on page 2,
// and the separator is ">", so entry will display "1>2".
builder.write("First TOC entry, MySequence #");
fieldSeq = (FieldSeq)builder.insertField(FieldType.FIELD_SEQUENCE, true);
fieldSeq.setSequenceIdentifier("MySequence");

Assert.assertEquals(" SEQ  MySequence", fieldSeq.getFieldCode());

// Insert a page, advance the prefix sequence by 2, and insert a SEQ field to create a TOC entry afterwards.
// The prefix sequence is now at 2, and the main sequence SEQ field is on page 3,
// so the TOC entry will display "2>3" at its page count.
builder.insertBreak(BreakType.PAGE_BREAK);
fieldSeq = (FieldSeq)builder.insertField(FieldType.FIELD_SEQUENCE, true);
fieldSeq.setSequenceIdentifier("PrefixSequence");
builder.insertParagraph();
fieldSeq = (FieldSeq)builder.insertField(FieldType.FIELD_SEQUENCE, true);
builder.write("Second TOC entry, MySequence #");
fieldSeq.setSequenceIdentifier("MySequence");

doc.updateFields();
doc.save(getArtifactsDir() + "Field.TOC.SEQ.docx");

Constructor Summary
 
Property Getters/Setters Summary
java.lang.StringgetBookmarkName()
void
setBookmarkName(java.lang.Stringvalue)
           Gets or sets a bookmark name that refers to an item elsewhere in the document rather than in the current location.
java.lang.StringgetDisplayResult()
Gets the text that represents the displayed field result.
FieldEndgetEnd()
Gets the node that represents the field end.
FieldFormatgetFormat()
Gets a FieldFormat object that provides typed access to field's formatting.
booleangetInsertNextNumber()
void
setInsertNextNumber(booleanvalue)
           Gets or sets whether to insert the next sequence number for the specified item.
booleanisDirty()
void
isDirty(booleanvalue)
           Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
booleanisLocked()
void
isLocked(booleanvalue)
           Gets or sets whether the field is locked (should not recalculate its result).
intgetLocaleId()
void
setLocaleId(intvalue)
           Gets or sets the LCID of the field.
java.lang.StringgetResetHeadingLevel()
void
setResetHeadingLevel(java.lang.Stringvalue)
           Gets or sets an integer number representing a heading level to reset the sequence number to. Returns -1 if the number is absent.
java.lang.StringgetResetNumber()
void
setResetNumber(java.lang.Stringvalue)
           Gets or sets an integer number to reset the sequence number to. Returns -1 if the number is absent.
java.lang.StringgetResult()
void
setResult(java.lang.Stringvalue)
           Gets or sets text that is between the field separator and field end.
FieldSeparatorgetSeparator()
Gets the node that represents the field separator. Can be null.
java.lang.StringgetSequenceIdentifier()
void
setSequenceIdentifier(java.lang.Stringvalue)
           Gets or sets the name assigned to the series of items that are to be numbered.
FieldStartgetStart()
Gets the node that represents the start of the field.
intgetType()
Gets the Microsoft Word field type. The value of the property is FieldType integer constant.
 
Method Summary
java.lang.StringgetFieldCode()
Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
java.lang.StringgetFieldCode(boolean includeChildFieldCodes)
Returns text between field start and field separator (or field end if there is no separator).
Noderemove()
Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
booleanunlink()
Performs the field unlink.
voidupdate()
Performs the field update. Throws if the field is being updated already.
voidupdate(boolean ignoreMergeFormat)
Performs a field update. Throws if the field is being updated already.
 

    • Constructor Detail

      • FieldSeq

        public FieldSeq()
    • Property Getters/Setters Detail

      • getBookmarkName/setBookmarkName

        public java.lang.String getBookmarkName() / public void setBookmarkName(java.lang.String value)
        
        Gets or sets a bookmark name that refers to an item elsewhere in the document rather than in the current location.

        Example:

        Shows how to combine table of contents and sequence fields.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // A TOC field can create an entry in its table of contents for each SEQ field found in the document.
        // Each entry contains the paragraph that contains the SEQ field,
        // and the number of the page that the field appears on.
        FieldToc fieldToc = (FieldToc)builder.insertField(FieldType.FIELD_TOC, true);
        
        // Configure this TOC field to only pick up SEQ fields that are within the bounds of a bookmark
        // named "TOCBookmark", and also have a SequenceIdentifier attribute with a value of "MySequence".
        fieldToc.setTableOfFiguresLabel("MySequence");
        fieldToc.setBookmarkName("TOCBookmark");
        builder.insertBreak(BreakType.PAGE_BREAK);
        
        Assert.assertEquals(" TOC  \\c MySequence \\b TOCBookmark", fieldToc.getFieldCode());
        
        // SEQ fields display a count that increments at each SEQ field.
        // These fields also maintain separate counts for each unique named sequence
        // identified by the SEQ field's "SequenceIdentifier" attribute.
        // Insert a SEQ field that has a sequence identifier that matches the TOC's
        // TableOfFiguresLabel attribute. This field will not create an entry in the TOC since it is outside
        // the bookmark's bounds designated by "BookmarkName".
        builder.write("MySequence #");
        FieldSeq fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("MySequence");
        builder.writeln(", will not show up in the TOC because it is outside of the bookmark.");
        
        builder.startBookmark("TOCBookmark");
        
        // This SEQ field's sequence matches the TOC's "TableOfFiguresLabel" attribute and is within the bookmark's bounds.
        // The paragraph that contains this field will show up in the TOC as an entry.
        builder.write("MySequence #");
        fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("MySequence");
        builder.writeln(", will show up in the TOC next to the entry for the above caption.");
        
        // This SEQ field's sequence does not match the TOC's "TableOfFiguresLabel" attribute,
        // and is within the bounds of the bookmark. Its paragraph will not show up in the TOC as an entry.
        builder.write("MySequence #");
        fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("OtherSequence");
        builder.writeln(", will not show up in the TOC because it's from a different sequence identifier.");
        
        // This SEQ field's sequence matches the TOC's "TableOfFiguresLabel" attribute, and is within the bounds of the bookmark.
        // This field also references another bookmark. The contents of that bookmark will appear in the TOC entry for this SEQ field.
        // The SEQ field itself will not display the contents of that bookmark.
        fieldSeq = (FieldSeq)builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("MySequence");
        fieldSeq.setBookmarkName("SEQBookmark");
        Assert.assertEquals(" SEQ  MySequence SEQBookmark", fieldSeq.getFieldCode());
        
        // Create a bookmark with contents that will show up in the TOC entry due to the above SEQ field referencing it.
        builder.insertBreak(BreakType.PAGE_BREAK);
        builder.startBookmark("SEQBookmark");
        builder.write("MySequence #");
        fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("MySequence");
        builder.writeln(", text from inside SEQBookmark.");
        builder.endBookmark("SEQBookmark");
        
        builder.endBookmark("TOCBookmark");
        
        doc.updateFields();
        doc.save(getArtifactsDir() + "Field.SEQ.Bookmark.docx");
      • getDisplayResult

        public java.lang.String getDisplayResult()
        
        Gets the text that represents the displayed field result. The Document.updateListLabels() method must be called to obtain correct value for the FieldListNum, FieldAutoNum, FieldAutoNumOut and FieldAutoNumLgl fields.

        Example:

        Shows how to get the real text that a field displays in the document.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        builder.write("This document was written by ");
        FieldAuthor fieldAuthor = (FieldAuthor)builder.insertField(FieldType.FIELD_AUTHOR, true);
        fieldAuthor.setAuthorName("John Doe");
        
        // We can use the DisplayResult attribute to verify what exact text
        // a field would display in its place in the document.
        Assert.assertEquals("", fieldAuthor.getDisplayResult());
        
        // Fields do not maintain accurate result values in real-time. 
        // To make sure our fields display accurate results at any given time,
        // such as right before a save operation, we need to update them manually.
        fieldAuthor.update();
        
        Assert.assertEquals("John Doe", fieldAuthor.getDisplayResult());
        
        doc.save(getArtifactsDir() + "Field.DisplayResult.docx");
      • getEnd

        public FieldEnd getEnd()
        
        Gets the node that represents the field end.

        Example:

        Shows how to work with a collection of fields.
        public void fieldCollection() throws Exception
        {
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
        
            builder.insertField(" DATE \\@ \"dddd, d MMMM yyyy\" ");
            builder.insertField(" TIME ");
            builder.insertField(" REVNUM ");
            builder.insertField(" AUTHOR  \"John Doe\" ");
            builder.insertField(" SUBJECT \"My Subject\" ");
            builder.insertField(" QUOTE \"Hello world!\" ");
            doc.updateFields();
        
            // This collection stores all of a document's fields.
            FieldCollection fields = doc.getRange().getFields();
        
            Assert.assertEquals(6, fields.getCount());
        
            // Iterate over the field collection, and print contents and type
            // of every field using a custom visitor implementation.
            FieldVisitor fieldVisitor = new FieldVisitor();
        
            Iterator<Field> fieldEnumerator = fields.iterator();
        
            while (fieldEnumerator.hasNext()) {
                if (fieldEnumerator.next() != null) {
                    Field currentField = fieldEnumerator.next();
        
                    currentField.getStart().accept(fieldVisitor);
                    if (currentField.getSeparator() != null) {
                        currentField.getSeparator().accept(fieldVisitor);
                    }
                    currentField.getEnd().accept(fieldVisitor);
                } else {
                    System.out.println("There are no fields in the document.");
                }
            }
        
            System.out.println(fieldVisitor.getText());
        }
        
        /// <summary>
        /// Document visitor implementation that prints field info.
        /// </summary>
        public static class FieldVisitor extends DocumentVisitor {
            public FieldVisitor() {
                mBuilder = new StringBuilder();
            }
        
            /// <summary>
            /// Gets the plain text of the document that was accumulated by the visitor.
            /// </summary>
            public String getText() {
                return mBuilder.toString();
            }
        
            /// <summary>
            /// Called when a FieldStart node is encountered in the document.
            /// </summary>
            public int visitFieldStart(final FieldStart fieldStart) {
                mBuilder.append("Found field: " + fieldStart.getFieldType() + "\r\n");
                mBuilder.append("\tField code: " + fieldStart.getField().getFieldCode() + "\r\n");
                mBuilder.append("\tDisplayed as: " + fieldStart.getField().getResult() + "\r\n");
        
                return VisitorAction.CONTINUE;
            }
        
            /// <summary>
            /// Called when a FieldSeparator node is encountered in the document.
            /// </summary>
            public int visitFieldSeparator(final FieldSeparator fieldSeparator) {
                mBuilder.append("\tFound separator: " + fieldSeparator.getText() + "\r\n");
        
                return VisitorAction.CONTINUE;
            }
        
            /// <summary>
            /// Called when a FieldEnd node is encountered in the document.
            /// </summary>
            public int visitFieldEnd(final FieldEnd fieldEnd) {
                mBuilder.append("End of field: " + fieldEnd.getFieldType() + "\r\n");
        
                return VisitorAction.CONTINUE;
            }
        
            private /*final*/ StringBuilder mBuilder;
        }
      • getFormat

        public FieldFormat getFormat()
        
        Gets a FieldFormat object that provides typed access to field's formatting.

        Example:

        Shows how to format field results.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // Use a document builder to insert a field that displays a result with no format applied.
        Field field = builder.insertField("= 2 + 3");
        
        Assert.assertEquals("= 2 + 3", field.getFieldCode());
        Assert.assertEquals("5", field.getResult());
        
        // We can apply a format to a field's result using the field's attributes.
        // Below are three types of formats that we can apply to a field's result.
        // 1 -  Numeric format:
        FieldFormat format = field.getFormat();
        format.setNumericFormat("$###.00");
        field.update();
        
        Assert.assertEquals("= 2 + 3 \\# $###.00", field.getFieldCode());
        Assert.assertEquals("$  5.00", field.getResult());
        
        // 2 -  Date/time format:
        field = builder.insertField("DATE");
        format = field.getFormat();
        format.setDateTimeFormat("dddd, MMMM dd, yyyy");
        field.update();
        
        Assert.assertEquals("DATE \\@ \"dddd, MMMM dd, yyyy\"", field.getFieldCode());
        System.out.println("Today's date, in {format.DateTimeFormat} format:\n\t{field.Result}");
        
        // 3 -  General format:
        field = builder.insertField("= 25 + 33");
        format = field.getFormat();
        format.getGeneralFormats().add(GeneralFormat.LOWERCASE_ROMAN);
        format.getGeneralFormats().add(GeneralFormat.UPPER);
        field.update();
        
        int index = 0;
        Iterator<Integer> generalFormatEnumerator = format.getGeneralFormats().iterator();
        while (generalFormatEnumerator.hasNext()) {
            int value = generalFormatEnumerator.next();
            System.out.println(MessageFormat.format("General format index {0}: {1}", index++, value));
        }
        
        Assert.assertEquals("= 25 + 33 \\* roman \\* Upper", field.getFieldCode());
        Assert.assertEquals("LVIII", field.getResult());
        Assert.assertEquals(2, format.getGeneralFormats().getCount());
        Assert.assertEquals(GeneralFormat.LOWERCASE_ROMAN, format.getGeneralFormats().get(0));
        
        // We can remove our formats to revert the field's result to its original form.
        format.getGeneralFormats().remove(GeneralFormat.LOWERCASE_ROMAN);
        format.getGeneralFormats().removeAt(0);
        Assert.assertEquals(0, format.getGeneralFormats().getCount());
        field.update();
        
        Assert.assertEquals("= 25 + 33  ", field.getFieldCode());
        Assert.assertEquals("58", field.getResult());
        Assert.assertEquals(0, format.getGeneralFormats().getCount());
      • getInsertNextNumber/setInsertNextNumber

        public boolean getInsertNextNumber() / public void setInsertNextNumber(boolean value)
        
        Gets or sets whether to insert the next sequence number for the specified item.

        Example:

        Shows create numbering using SEQ fields.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // SEQ fields display a count that increments at each SEQ field.
        // These fields also maintain separate counts for each unique named sequence
        // identified by the SEQ field's "SequenceIdentifier" attribute.
        // Insert a SEQ field that will display the current count value of "MySequence",
        // after using the "ResetNumber" attribute to set it to 100.
        builder.write("#");
        FieldSeq fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("MySequence");
        fieldSeq.setResetNumber("100");
        fieldSeq.update();
        
        Assert.assertEquals(" SEQ  MySequence \\r 100", fieldSeq.getFieldCode());
        Assert.assertEquals("100", fieldSeq.getResult());
        
        // Display the next number in this sequence with another SEQ field.
        builder.write(", #");
        fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("MySequence");
        fieldSeq.update();
        
        Assert.assertEquals("101", fieldSeq.getResult());
        
        // Insert a level 1 heading.
        builder.insertBreak(BreakType.PARAGRAPH_BREAK);
        builder.getParagraphFormat().setStyle(doc.getStyles().get("Heading 1"));
        builder.writeln("This level 1 heading will reset MySequence to 1");
        builder.getParagraphFormat().setStyle(doc.getStyles().get("Normal"));
        
        // Insert another SEQ field from the same sequence, and configure it to reset the count at every heading with 1.
        builder.write("\n#");
        fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("MySequence");
        fieldSeq.setResetHeadingLevel("1");
        fieldSeq.update();
        
        // The above heading is a level 1 heading, so the count for this sequence is reset to 1.
        Assert.assertEquals(" SEQ  MySequence \\s 1", fieldSeq.getFieldCode());
        Assert.assertEquals("1", fieldSeq.getResult());
        
        // Move to the next number of this sequence.
        builder.write(", #");
        fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("MySequence");
        fieldSeq.setInsertNextNumber(true);
        fieldSeq.update();
        
        Assert.assertEquals(" SEQ  MySequence \\n", fieldSeq.getFieldCode());
        Assert.assertEquals("2", fieldSeq.getResult());
        
        doc.updateFields();
        doc.save(getArtifactsDir() + "Field.SEQ.ResetNumbering.docx");
      • isDirty/isDirty

        public boolean isDirty() / public void isDirty(boolean value)
        
        Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.

        Example:

        Shows how to use special property for updating field result.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // Give the document's built-in "Author" property value, and then display it with a field.
        doc.getBuiltInDocumentProperties().setAuthor("John Doe");
        FieldAuthor field = (FieldAuthor)builder.insertField(FieldType.FIELD_AUTHOR, true);
        
        Assert.assertFalse(field.isDirty());
        Assert.assertEquals("John Doe", field.getResult());
        
        // Update the property. The field still displays the old value.
        doc.getBuiltInDocumentProperties().setAuthor("John & Jane Doe");
        
        Assert.assertEquals("John Doe", field.getResult());
        
        // Since the field's value is out of date, we can mark it as "dirty".
        // This value will stay out of date until we update the field manually with the Field.Update() method.
        field.isDirty(true);
        
        OutputStream docStream = new FileOutputStream(getArtifactsDir() + "Filed.UpdateDirtyFields.docx");
        try {
            // If we save without calling an update method,
            // the field will keep displaying the out of date value in the output document.
            doc.save(docStream, SaveFormat.DOCX);
        
            // The LoadOptions object has an option to update all fields
            // marked as "dirty" when loading the document.
            LoadOptions options = new LoadOptions();
            options.setUpdateDirtyFields(updateDirtyFields);
        
            doc = new Document(String.valueOf(docStream), options);
        
            Assert.assertEquals("John & Jane Doe", doc.getBuiltInDocumentProperties().getAuthor());
        
            field = (FieldAuthor) doc.getRange().getFields().get(0);
        
            // Updating dirty fields like this automatically set their "IsDirty" flag to false.
            if (updateDirtyFields)
            {
                Assert.assertEquals("John & Jane Doe", field.getResult());
                Assert.assertFalse(field.isDirty());
            } else {
                Assert.assertEquals("John Doe", field.getResult());
                Assert.assertTrue(field.isDirty());
            }
        } finally {
            if (docStream != null) docStream.close();
        }
      • isLocked/isLocked

        public boolean isLocked() / public void isLocked(boolean value)
        
        Gets or sets whether the field is locked (should not recalculate its result).

        Example:

        Shows how to work with a FieldStart node.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        FieldDate field = (FieldDate) builder.insertField(FieldType.FIELD_DATE, true);
        field.getFormat().setDateTimeFormat("dddd, MMMM dd, yyyy");
        field.update();
        
        FieldChar fieldStart = field.getStart();
        
        Assert.assertEquals(FieldType.FIELD_DATE, fieldStart.getFieldType());
        Assert.assertEquals(false, fieldStart.isDirty());
        Assert.assertEquals(false, fieldStart.isLocked());
        
        // Retrieve the facade object which represents the field in the document.
        field = (FieldDate)fieldStart.getField();
        
        Assert.assertEquals(false, field.isLocked());
        Assert.assertEquals(" DATE  \\@ \"dddd, MMMM dd, yyyy\"", field.getFieldCode());
        
        // Update the field to show the current date.
        field.update();
      • getLocaleId/setLocaleId

        public int getLocaleId() / public void setLocaleId(int value)
        
        Gets or sets the LCID of the field.

        Example:

        Shows how to insert a field and work with its locale.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // Insert a DATE field, and then print the date it will display.
        // Your thread's current culture determines the formatting of the date.
        Field field = builder.insertField("DATE");
        System.out.println("Today's date, as displayed in the \"{CultureInfo.CurrentCulture.EnglishName}\" culture: {field.Result}");
        
        Assert.assertEquals(1033, field.getLocaleId());
        
        // Changing the culture of our thread will impact the result of the DATE field.
        // Another way to get the DATE field to display a date in a different culture is to use its LocaleId attribute.
        // This way allows us to avoid changing the thread's culture to get this effect.
        doc.getFieldOptions().setFieldUpdateCultureSource(FieldUpdateCultureSource.FIELD_CODE);
        CultureInfo de = new CultureInfo("de-DE");
        field.setLocaleId(1031);
        field.update();
        
        System.out.println("Today's date, as displayed according to the \"{CultureInfo.GetCultureInfo(field.LocaleId).EnglishName}\" culture: {field.Result}");
        See Also:
        FieldUpdateCultureSource.FIELD_CODE
      • getResetHeadingLevel/setResetHeadingLevel

        public java.lang.String getResetHeadingLevel() / public void setResetHeadingLevel(java.lang.String value)
        
        Gets or sets an integer number representing a heading level to reset the sequence number to. Returns -1 if the number is absent.

        Example:

        Shows create numbering using SEQ fields.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // SEQ fields display a count that increments at each SEQ field.
        // These fields also maintain separate counts for each unique named sequence
        // identified by the SEQ field's "SequenceIdentifier" attribute.
        // Insert a SEQ field that will display the current count value of "MySequence",
        // after using the "ResetNumber" attribute to set it to 100.
        builder.write("#");
        FieldSeq fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("MySequence");
        fieldSeq.setResetNumber("100");
        fieldSeq.update();
        
        Assert.assertEquals(" SEQ  MySequence \\r 100", fieldSeq.getFieldCode());
        Assert.assertEquals("100", fieldSeq.getResult());
        
        // Display the next number in this sequence with another SEQ field.
        builder.write(", #");
        fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("MySequence");
        fieldSeq.update();
        
        Assert.assertEquals("101", fieldSeq.getResult());
        
        // Insert a level 1 heading.
        builder.insertBreak(BreakType.PARAGRAPH_BREAK);
        builder.getParagraphFormat().setStyle(doc.getStyles().get("Heading 1"));
        builder.writeln("This level 1 heading will reset MySequence to 1");
        builder.getParagraphFormat().setStyle(doc.getStyles().get("Normal"));
        
        // Insert another SEQ field from the same sequence, and configure it to reset the count at every heading with 1.
        builder.write("\n#");
        fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("MySequence");
        fieldSeq.setResetHeadingLevel("1");
        fieldSeq.update();
        
        // The above heading is a level 1 heading, so the count for this sequence is reset to 1.
        Assert.assertEquals(" SEQ  MySequence \\s 1", fieldSeq.getFieldCode());
        Assert.assertEquals("1", fieldSeq.getResult());
        
        // Move to the next number of this sequence.
        builder.write(", #");
        fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("MySequence");
        fieldSeq.setInsertNextNumber(true);
        fieldSeq.update();
        
        Assert.assertEquals(" SEQ  MySequence \\n", fieldSeq.getFieldCode());
        Assert.assertEquals("2", fieldSeq.getResult());
        
        doc.updateFields();
        doc.save(getArtifactsDir() + "Field.SEQ.ResetNumbering.docx");
      • getResetNumber/setResetNumber

        public java.lang.String getResetNumber() / public void setResetNumber(java.lang.String value)
        
        Gets or sets an integer number to reset the sequence number to. Returns -1 if the number is absent.

        Example:

        Shows create numbering using SEQ fields.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // SEQ fields display a count that increments at each SEQ field.
        // These fields also maintain separate counts for each unique named sequence
        // identified by the SEQ field's "SequenceIdentifier" attribute.
        // Insert a SEQ field that will display the current count value of "MySequence",
        // after using the "ResetNumber" attribute to set it to 100.
        builder.write("#");
        FieldSeq fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("MySequence");
        fieldSeq.setResetNumber("100");
        fieldSeq.update();
        
        Assert.assertEquals(" SEQ  MySequence \\r 100", fieldSeq.getFieldCode());
        Assert.assertEquals("100", fieldSeq.getResult());
        
        // Display the next number in this sequence with another SEQ field.
        builder.write(", #");
        fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("MySequence");
        fieldSeq.update();
        
        Assert.assertEquals("101", fieldSeq.getResult());
        
        // Insert a level 1 heading.
        builder.insertBreak(BreakType.PARAGRAPH_BREAK);
        builder.getParagraphFormat().setStyle(doc.getStyles().get("Heading 1"));
        builder.writeln("This level 1 heading will reset MySequence to 1");
        builder.getParagraphFormat().setStyle(doc.getStyles().get("Normal"));
        
        // Insert another SEQ field from the same sequence, and configure it to reset the count at every heading with 1.
        builder.write("\n#");
        fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("MySequence");
        fieldSeq.setResetHeadingLevel("1");
        fieldSeq.update();
        
        // The above heading is a level 1 heading, so the count for this sequence is reset to 1.
        Assert.assertEquals(" SEQ  MySequence \\s 1", fieldSeq.getFieldCode());
        Assert.assertEquals("1", fieldSeq.getResult());
        
        // Move to the next number of this sequence.
        builder.write(", #");
        fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("MySequence");
        fieldSeq.setInsertNextNumber(true);
        fieldSeq.update();
        
        Assert.assertEquals(" SEQ  MySequence \\n", fieldSeq.getFieldCode());
        Assert.assertEquals("2", fieldSeq.getResult());
        
        doc.updateFields();
        doc.save(getArtifactsDir() + "Field.SEQ.ResetNumbering.docx");
      • getResult/setResult

        public java.lang.String getResult() / public void setResult(java.lang.String value)
        
        Gets or sets text that is between the field separator and field end.

        Example:

        Shows how to insert a field into a document using a field code.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        Field dateField = builder.insertField("DATE \\* MERGEFORMAT");
        
        Assert.assertEquals(FieldType.FIELD_DATE, dateField.getType());
        Assert.assertEquals("DATE \\* MERGEFORMAT", dateField.getFieldCode());
      • getSeparator

        public FieldSeparator getSeparator()
        
        Gets the node that represents the field separator. Can be null.

        Example:

        Shows how to work with a collection of fields.
        public void fieldCollection() throws Exception
        {
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
        
            builder.insertField(" DATE \\@ \"dddd, d MMMM yyyy\" ");
            builder.insertField(" TIME ");
            builder.insertField(" REVNUM ");
            builder.insertField(" AUTHOR  \"John Doe\" ");
            builder.insertField(" SUBJECT \"My Subject\" ");
            builder.insertField(" QUOTE \"Hello world!\" ");
            doc.updateFields();
        
            // This collection stores all of a document's fields.
            FieldCollection fields = doc.getRange().getFields();
        
            Assert.assertEquals(6, fields.getCount());
        
            // Iterate over the field collection, and print contents and type
            // of every field using a custom visitor implementation.
            FieldVisitor fieldVisitor = new FieldVisitor();
        
            Iterator<Field> fieldEnumerator = fields.iterator();
        
            while (fieldEnumerator.hasNext()) {
                if (fieldEnumerator.next() != null) {
                    Field currentField = fieldEnumerator.next();
        
                    currentField.getStart().accept(fieldVisitor);
                    if (currentField.getSeparator() != null) {
                        currentField.getSeparator().accept(fieldVisitor);
                    }
                    currentField.getEnd().accept(fieldVisitor);
                } else {
                    System.out.println("There are no fields in the document.");
                }
            }
        
            System.out.println(fieldVisitor.getText());
        }
        
        /// <summary>
        /// Document visitor implementation that prints field info.
        /// </summary>
        public static class FieldVisitor extends DocumentVisitor {
            public FieldVisitor() {
                mBuilder = new StringBuilder();
            }
        
            /// <summary>
            /// Gets the plain text of the document that was accumulated by the visitor.
            /// </summary>
            public String getText() {
                return mBuilder.toString();
            }
        
            /// <summary>
            /// Called when a FieldStart node is encountered in the document.
            /// </summary>
            public int visitFieldStart(final FieldStart fieldStart) {
                mBuilder.append("Found field: " + fieldStart.getFieldType() + "\r\n");
                mBuilder.append("\tField code: " + fieldStart.getField().getFieldCode() + "\r\n");
                mBuilder.append("\tDisplayed as: " + fieldStart.getField().getResult() + "\r\n");
        
                return VisitorAction.CONTINUE;
            }
        
            /// <summary>
            /// Called when a FieldSeparator node is encountered in the document.
            /// </summary>
            public int visitFieldSeparator(final FieldSeparator fieldSeparator) {
                mBuilder.append("\tFound separator: " + fieldSeparator.getText() + "\r\n");
        
                return VisitorAction.CONTINUE;
            }
        
            /// <summary>
            /// Called when a FieldEnd node is encountered in the document.
            /// </summary>
            public int visitFieldEnd(final FieldEnd fieldEnd) {
                mBuilder.append("End of field: " + fieldEnd.getFieldType() + "\r\n");
        
                return VisitorAction.CONTINUE;
            }
        
            private /*final*/ StringBuilder mBuilder;
        }
      • getSequenceIdentifier/setSequenceIdentifier

        public java.lang.String getSequenceIdentifier() / public void setSequenceIdentifier(java.lang.String value)
        
        Gets or sets the name assigned to the series of items that are to be numbered.

        Example:

        Shows create numbering using SEQ fields.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // SEQ fields display a count that increments at each SEQ field.
        // These fields also maintain separate counts for each unique named sequence
        // identified by the SEQ field's "SequenceIdentifier" attribute.
        // Insert a SEQ field that will display the current count value of "MySequence",
        // after using the "ResetNumber" attribute to set it to 100.
        builder.write("#");
        FieldSeq fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("MySequence");
        fieldSeq.setResetNumber("100");
        fieldSeq.update();
        
        Assert.assertEquals(" SEQ  MySequence \\r 100", fieldSeq.getFieldCode());
        Assert.assertEquals("100", fieldSeq.getResult());
        
        // Display the next number in this sequence with another SEQ field.
        builder.write(", #");
        fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("MySequence");
        fieldSeq.update();
        
        Assert.assertEquals("101", fieldSeq.getResult());
        
        // Insert a level 1 heading.
        builder.insertBreak(BreakType.PARAGRAPH_BREAK);
        builder.getParagraphFormat().setStyle(doc.getStyles().get("Heading 1"));
        builder.writeln("This level 1 heading will reset MySequence to 1");
        builder.getParagraphFormat().setStyle(doc.getStyles().get("Normal"));
        
        // Insert another SEQ field from the same sequence, and configure it to reset the count at every heading with 1.
        builder.write("\n#");
        fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("MySequence");
        fieldSeq.setResetHeadingLevel("1");
        fieldSeq.update();
        
        // The above heading is a level 1 heading, so the count for this sequence is reset to 1.
        Assert.assertEquals(" SEQ  MySequence \\s 1", fieldSeq.getFieldCode());
        Assert.assertEquals("1", fieldSeq.getResult());
        
        // Move to the next number of this sequence.
        builder.write(", #");
        fieldSeq = (FieldSeq) builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("MySequence");
        fieldSeq.setInsertNextNumber(true);
        fieldSeq.update();
        
        Assert.assertEquals(" SEQ  MySequence \\n", fieldSeq.getFieldCode());
        Assert.assertEquals("2", fieldSeq.getResult());
        
        doc.updateFields();
        doc.save(getArtifactsDir() + "Field.SEQ.ResetNumbering.docx");

        Example:

        Shows how to populate a TOC field with entries using SEQ fields.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // A TOC field can create an entry in its table of contents for each SEQ field found in the document.
        // Each entry contains the paragraph that includes the SEQ field and the page's number that the field appears on.
        FieldToc fieldToc = (FieldToc)builder.insertField(FieldType.FIELD_TOC, true);
        
        // SEQ fields display a count that increments at each SEQ field.
        // These fields also maintain separate counts for each unique named sequence
        // identified by the SEQ field's "SequenceIdentifier" attribute.
        // Use the "TableOfFiguresLabel" attribute to name a main sequence for the TOC.
        // Now, this TOC will only create entries out of SEQ fields with their "SequenceIdentifier" set to "MySequence".
        fieldToc.setTableOfFiguresLabel("MySequence");
        
        // We can name another SEQ field sequence in the "PrefixedSequenceIdentifier" attribute.
        // SEQ fields from this prefix sequence will not create TOC entries. 
        // Every TOC entry created from a main sequence SEQ field will now also display the count that
        // the prefix sequence is currently on at the primary sequence SEQ field that made the entry.
        fieldToc.setPrefixedSequenceIdentifier("PrefixSequence");
        
        // Each TOC entry will display the prefix sequence count immediately to the left
        // of the page number that the main sequence SEQ field appears on.
        // We can specify a custom separator that will appear between these two numbers.
        fieldToc.setSequenceSeparator(">");
        
        Assert.assertEquals(" TOC  \\c MySequence \\s PrefixSequence \\d >", fieldToc.getFieldCode());
        
        builder.insertBreak(BreakType.PAGE_BREAK);
        
        // There are two ways of using SEQ fields to populate this TOC.
        // 1 -  Inserting a SEQ field that belongs to the TOC's prefix sequence:
        // This field will increment the SEQ sequence count for the "PrefixSequence" by 1.
        // Since this field does not belong to the main sequence identified
        // by the "TableOfFiguresLabel" attribute of the TOC, it will not appear as an entry.
        FieldSeq fieldSeq = (FieldSeq)builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("PrefixSequence");
        builder.insertParagraph();
        
        Assert.assertEquals(" SEQ  PrefixSequence", fieldSeq.getFieldCode());
        
        // 2 -  Inserting a SEQ field that belongs to the TOC's main sequence:
        // This SEQ field will create an entry in the TOC.
        // The TOC entry will contain the paragraph that the SEQ field is in and the number of the page that it appears on.
        // This entry will also display the count that the prefix sequence is currently at,
        // separated from the page number by the value in the TOC's SeqenceSeparator attribute.
        // The "PrefixSequence" count is at 1, this main sequence SEQ field is on page 2,
        // and the separator is ">", so entry will display "1>2".
        builder.write("First TOC entry, MySequence #");
        fieldSeq = (FieldSeq)builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("MySequence");
        
        Assert.assertEquals(" SEQ  MySequence", fieldSeq.getFieldCode());
        
        // Insert a page, advance the prefix sequence by 2, and insert a SEQ field to create a TOC entry afterwards.
        // The prefix sequence is now at 2, and the main sequence SEQ field is on page 3,
        // so the TOC entry will display "2>3" at its page count.
        builder.insertBreak(BreakType.PAGE_BREAK);
        fieldSeq = (FieldSeq)builder.insertField(FieldType.FIELD_SEQUENCE, true);
        fieldSeq.setSequenceIdentifier("PrefixSequence");
        builder.insertParagraph();
        fieldSeq = (FieldSeq)builder.insertField(FieldType.FIELD_SEQUENCE, true);
        builder.write("Second TOC entry, MySequence #");
        fieldSeq.setSequenceIdentifier("MySequence");
        
        doc.updateFields();
        doc.save(getArtifactsDir() + "Field.TOC.SEQ.docx");
      • getStart

        public FieldStart getStart()
        
        Gets the node that represents the start of the field.

        Example:

        Shows how to work with a collection of fields.
        public void fieldCollection() throws Exception
        {
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
        
            builder.insertField(" DATE \\@ \"dddd, d MMMM yyyy\" ");
            builder.insertField(" TIME ");
            builder.insertField(" REVNUM ");
            builder.insertField(" AUTHOR  \"John Doe\" ");
            builder.insertField(" SUBJECT \"My Subject\" ");
            builder.insertField(" QUOTE \"Hello world!\" ");
            doc.updateFields();
        
            // This collection stores all of a document's fields.
            FieldCollection fields = doc.getRange().getFields();
        
            Assert.assertEquals(6, fields.getCount());
        
            // Iterate over the field collection, and print contents and type
            // of every field using a custom visitor implementation.
            FieldVisitor fieldVisitor = new FieldVisitor();
        
            Iterator<Field> fieldEnumerator = fields.iterator();
        
            while (fieldEnumerator.hasNext()) {
                if (fieldEnumerator.next() != null) {
                    Field currentField = fieldEnumerator.next();
        
                    currentField.getStart().accept(fieldVisitor);
                    if (currentField.getSeparator() != null) {
                        currentField.getSeparator().accept(fieldVisitor);
                    }
                    currentField.getEnd().accept(fieldVisitor);
                } else {
                    System.out.println("There are no fields in the document.");
                }
            }
        
            System.out.println(fieldVisitor.getText());
        }
        
        /// <summary>
        /// Document visitor implementation that prints field info.
        /// </summary>
        public static class FieldVisitor extends DocumentVisitor {
            public FieldVisitor() {
                mBuilder = new StringBuilder();
            }
        
            /// <summary>
            /// Gets the plain text of the document that was accumulated by the visitor.
            /// </summary>
            public String getText() {
                return mBuilder.toString();
            }
        
            /// <summary>
            /// Called when a FieldStart node is encountered in the document.
            /// </summary>
            public int visitFieldStart(final FieldStart fieldStart) {
                mBuilder.append("Found field: " + fieldStart.getFieldType() + "\r\n");
                mBuilder.append("\tField code: " + fieldStart.getField().getFieldCode() + "\r\n");
                mBuilder.append("\tDisplayed as: " + fieldStart.getField().getResult() + "\r\n");
        
                return VisitorAction.CONTINUE;
            }
        
            /// <summary>
            /// Called when a FieldSeparator node is encountered in the document.
            /// </summary>
            public int visitFieldSeparator(final FieldSeparator fieldSeparator) {
                mBuilder.append("\tFound separator: " + fieldSeparator.getText() + "\r\n");
        
                return VisitorAction.CONTINUE;
            }
        
            /// <summary>
            /// Called when a FieldEnd node is encountered in the document.
            /// </summary>
            public int visitFieldEnd(final FieldEnd fieldEnd) {
                mBuilder.append("End of field: " + fieldEnd.getFieldType() + "\r\n");
        
                return VisitorAction.CONTINUE;
            }
        
            private /*final*/ StringBuilder mBuilder;
        }
      • getType

        public int getType()
        
        Gets the Microsoft Word field type. The value of the property is FieldType integer constant.

        Example:

        Shows how to insert a field into a document using a field code.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        Field dateField = builder.insertField("DATE \\* MERGEFORMAT");
        
        Assert.assertEquals(FieldType.FIELD_DATE, dateField.getType());
        Assert.assertEquals("DATE \\* MERGEFORMAT", dateField.getFieldCode());
    • Method Detail

      • getFieldCode

        public java.lang.String getFieldCode()
        Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.

        Example:

        Shows how to get a field's field code.
        // Open a document which contains a MERGEFIELD inside an IF field.
        Document doc = new Document(getMyDir() + "Nested fields.docx");
        FieldIf fieldIf = (FieldIf)doc.getRange().getFields().get(0);
        
        // There are two ways of getting a field's field code:
        // 1 -  Omit its inner fields:
        Assert.assertEquals(" IF  > 0 \" (surplus of ) \" \"\" ", fieldIf.getFieldCode(false));
        
        // 2 -  Include its inner fields:
        Assert.assertEquals(" IF \u0013 MERGEFIELD NetIncome \u0014\u0015 > 0 \" (surplus of \u0013 MERGEFIELD  NetIncome \\f $ \u0014\u0015) \" \"\" ",
            fieldIf.getFieldCode(true));
        
        // By default, the GetFieldCode method displays inner fields.
        Assert.assertEquals(fieldIf.getFieldCode(), fieldIf.getFieldCode(true));

        Example:

        Shows how to insert a field into a document using a field code.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        Field dateField = builder.insertField("DATE \\* MERGEFORMAT");
        
        Assert.assertEquals(FieldType.FIELD_DATE, dateField.getType());
        Assert.assertEquals("DATE \\* MERGEFORMAT", dateField.getFieldCode());
      • getFieldCode

        public java.lang.String getFieldCode(boolean includeChildFieldCodes)
        Returns text between field start and field separator (or field end if there is no separator).
        Parameters:
        includeChildFieldCodes - True if child field codes should be included.

        Example:

        Shows how to get a field's field code.
        // Open a document which contains a MERGEFIELD inside an IF field.
        Document doc = new Document(getMyDir() + "Nested fields.docx");
        FieldIf fieldIf = (FieldIf)doc.getRange().getFields().get(0);
        
        // There are two ways of getting a field's field code:
        // 1 -  Omit its inner fields:
        Assert.assertEquals(" IF  > 0 \" (surplus of ) \" \"\" ", fieldIf.getFieldCode(false));
        
        // 2 -  Include its inner fields:
        Assert.assertEquals(" IF \u0013 MERGEFIELD NetIncome \u0014\u0015 > 0 \" (surplus of \u0013 MERGEFIELD  NetIncome \\f $ \u0014\u0015) \" \"\" ",
            fieldIf.getFieldCode(true));
        
        // By default, the GetFieldCode method displays inner fields.
        Assert.assertEquals(fieldIf.getFieldCode(), fieldIf.getFieldCode(true));
      • remove

        public Node remove()
                   throws java.lang.Exception
        Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.

        Example:

        Shows how to process PRIVATE fields.
        public void fieldPrivate() throws Exception
        {
            // Open a Corel WordPerfect document which we have converted to .docx format.
            Document doc = new Document(getMyDir() + "Field sample - PRIVATE.docx");
        
            // WordPerfect 5.x/6.x documents like the one we have loaded may contain PRIVATE fields.
            // Microsoft Word preserves PRIVATE fields during load/save operations,
            // but provides no functionality for them.
            FieldPrivate field = (FieldPrivate)doc.getRange().getFields().get(0);
        
            Assert.assertEquals(" PRIVATE \"My value\" ", field.getFieldCode());
            Assert.assertEquals(FieldType.FIELD_PRIVATE, field.getType());
        
            // We can also insert PRIVATE fields using a document builder.
            DocumentBuilder builder = new DocumentBuilder(doc);
            builder.insertField(FieldType.FIELD_PRIVATE, true);
        
            // These fields are not a viable way of protecting sensitive information.
            // Unless backward compatibility with older versions of WordPerfect is essential,
            // we can safely remove these fields. We can do this using a DocumentVisiitor implementation.
            Assert.assertEquals(2, doc.getRange().getFields().getCount());
        
            FieldPrivateRemover remover = new FieldPrivateRemover();
            doc.accept(remover);
        
            Assert.assertEquals(remover.getFieldsRemovedCount(), 2);
            Assert.assertEquals(doc.getRange().getFields().getCount(), 0);
        }
        
        /// <summary>
        /// Removes all encountered PRIVATE fields.
        /// </summary>
        public static class FieldPrivateRemover extends DocumentVisitor {
            public FieldPrivateRemover() {
                mFieldsRemovedCount = 0;
            }
        
            public int getFieldsRemovedCount() {
                return mFieldsRemovedCount;
            }
        
            /// <summary>
            /// Called when a FieldEnd node is encountered in the document.
            /// If the node belongs to a PRIVATE field, the entire field is removed.
            /// </summary>
            public int visitFieldEnd(final FieldEnd fieldEnd) throws Exception {
                if (fieldEnd.getFieldType() == FieldType.FIELD_PRIVATE) {
                    fieldEnd.getField().remove();
                    mFieldsRemovedCount++;
                }
        
                return VisitorAction.CONTINUE;
            }
        
            private int mFieldsRemovedCount;
        }

        Example:

        Shows how to remove fields from a field collection.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        builder.insertField(" DATE \\@ \"dddd, d MMMM yyyy\" ");
        builder.insertField(" TIME ");
        builder.insertField(" REVNUM ");
        builder.insertField(" AUTHOR  \"John Doe\" ");
        builder.insertField(" SUBJECT \"My Subject\" ");
        builder.insertField(" QUOTE \"Hello world!\" ");
        doc.updateFields();
        
        // This collection stores all of a document's fields.
        FieldCollection fields = doc.getRange().getFields();
        
        Assert.assertEquals(6, fields.getCount());
        
        // Below are four ways of removing fields from a field collection.
        // 1 -  Get a field to remove itself:
        fields.get(0).remove();
        Assert.assertEquals(5, fields.getCount());
        
        // 2 -  Get the collection to remove a field that we pass to its removal method:
        Field lastField = fields.get(3);
        fields.remove(lastField);
        Assert.assertEquals(4, fields.getCount());
        
        // 3 -  Remove a field from a collection at an index:
        fields.removeAt(2);
        Assert.assertEquals(3, fields.getCount());
        
        // 4 -  Remove all the fields from the collection at once:
        fields.clear();
        Assert.assertEquals(0, fields.getCount());
      • unlink

        public boolean unlink()
                      throws java.lang.Exception
        Performs the field unlink.

        Replaces the field with its most recent result.

        Some fields, such as XE (Index Entry) fields and SEQ (Sequence) fields, cannot be unlinked.

        Returns:
        True if the field has been unlinked, otherwise false.

        Example:

        Shows how to unlink a field.
        Document doc = new Document(getMyDir() + "Linked fields.docx");
        doc.getRange().getFields().get(1).unlink();
      • update

        public void update()
                   throws java.lang.Exception
        Performs the field update. Throws if the field is being updated already.

        Example:

        Shows how to format field results.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // Use a document builder to insert a field that displays a result with no format applied.
        Field field = builder.insertField("= 2 + 3");
        
        Assert.assertEquals("= 2 + 3", field.getFieldCode());
        Assert.assertEquals("5", field.getResult());
        
        // We can apply a format to a field's result using the field's attributes.
        // Below are three types of formats that we can apply to a field's result.
        // 1 -  Numeric format:
        FieldFormat format = field.getFormat();
        format.setNumericFormat("$###.00");
        field.update();
        
        Assert.assertEquals("= 2 + 3 \\# $###.00", field.getFieldCode());
        Assert.assertEquals("$  5.00", field.getResult());
        
        // 2 -  Date/time format:
        field = builder.insertField("DATE");
        format = field.getFormat();
        format.setDateTimeFormat("dddd, MMMM dd, yyyy");
        field.update();
        
        Assert.assertEquals("DATE \\@ \"dddd, MMMM dd, yyyy\"", field.getFieldCode());
        System.out.println("Today's date, in {format.DateTimeFormat} format:\n\t{field.Result}");
        
        // 3 -  General format:
        field = builder.insertField("= 25 + 33");
        format = field.getFormat();
        format.getGeneralFormats().add(GeneralFormat.LOWERCASE_ROMAN);
        format.getGeneralFormats().add(GeneralFormat.UPPER);
        field.update();
        
        int index = 0;
        Iterator<Integer> generalFormatEnumerator = format.getGeneralFormats().iterator();
        while (generalFormatEnumerator.hasNext()) {
            int value = generalFormatEnumerator.next();
            System.out.println(MessageFormat.format("General format index {0}: {1}", index++, value));
        }
        
        Assert.assertEquals("= 25 + 33 \\* roman \\* Upper", field.getFieldCode());
        Assert.assertEquals("LVIII", field.getResult());
        Assert.assertEquals(2, format.getGeneralFormats().getCount());
        Assert.assertEquals(GeneralFormat.LOWERCASE_ROMAN, format.getGeneralFormats().get(0));
        
        // We can remove our formats to revert the field's result to its original form.
        format.getGeneralFormats().remove(GeneralFormat.LOWERCASE_ROMAN);
        format.getGeneralFormats().removeAt(0);
        Assert.assertEquals(0, format.getGeneralFormats().getCount());
        field.update();
        
        Assert.assertEquals("= 25 + 33  ", field.getFieldCode());
        Assert.assertEquals("58", field.getResult());
        Assert.assertEquals(0, format.getGeneralFormats().getCount());

        Example:

        Shows how to insert a field into a document using FieldType.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // Insert two fields while passing a flag which determines whether to update them as the builder inserts them.
        // In some cases, updating fields could be computationally expensive, and it may be a good idea to defer the update.
        // Not all field types require updating, exceptions include BARCODE and MERGEFIELD.
        doc.getBuiltInDocumentProperties().setAuthor("John Doe");
        builder.write("This document was written by ");
        builder.insertField(FieldType.FIELD_AUTHOR, updateInsertedFieldsImmediately);
        
        builder.insertParagraph();
        builder.write("\nThis is page ");
        builder.insertField(FieldType.FIELD_PAGE, updateInsertedFieldsImmediately);
        
        Assert.assertEquals(" AUTHOR ", doc.getRange().getFields().get(0).getFieldCode());
        Assert.assertEquals(" PAGE ", doc.getRange().getFields().get(1).getFieldCode());
        
        if (updateInsertedFieldsImmediately)
        {
            Assert.assertEquals("John Doe", doc.getRange().getFields().get(0).getResult());
            Assert.assertEquals("1", doc.getRange().getFields().get(1).getResult());
        }
        else
        {
            Assert.assertEquals("", doc.getRange().getFields().get(0).getResult());
            Assert.assertEquals("", doc.getRange().getFields().get(1).getResult());
        
            // We will need to update these fields using the update methods manually.
            doc.getRange().getFields().get(0).update();
        
            Assert.assertEquals("John Doe", doc.getRange().getFields().get(0).getResult());
        
        doc.updateFields();
        
        Assert.assertEquals("1", doc.getRange().getFields().get(1).getResult());
        }
      • update

        public void update(boolean ignoreMergeFormat)
                   throws java.lang.Exception
        Performs a field update. Throws if the field is being updated already.
        Parameters:
        ignoreMergeFormat - If true then direct field result formatting is abandoned, regardless of the MERGEFORMAT switch, otherwise normal update is performed.