com.aspose.words
Class FieldMergeField

java.lang.Object
  extended by Field
      extended by com.aspose.words.FieldMergeField

public class FieldMergeField 
extends Field

Implements the MERGEFIELD field. Retrieves the name of a data field within the merge characters in a mail merge main document. When the main document is merged with the selected data source, information from the specified data field is inserted in place of the merge field.

Example:

Shows how to use MERGEFIELD fields to perform a mail merge.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create data source for our merge fields
DataTable table = new DataTable("Employees");
table.getColumns().add("Courtesy Title");
table.getColumns().add("First Name");
table.getColumns().add("Last Name");
table.getRows().add("Mr.", "John", "Doe");
table.getRows().add("Mrs.", "Jane", "Cardholder");

// Insert a merge field that corresponds to one of our columns and put text before and after it
FieldMergeField fieldMergeField = (FieldMergeField) builder.insertField(FieldType.FIELD_MERGE_FIELD, true);
fieldMergeField.setFieldName("Courtesy Title");
fieldMergeField.isMapped(true);
fieldMergeField.isVerticalFormatting(false);
fieldMergeField.setTextBefore("Dear ");
fieldMergeField.setTextAfter(" ");

Assert.assertEquals(" MERGEFIELD  \"Courtesy Title\" \\m \\b \"Dear \" \\f \" \"", fieldMergeField.getFieldCode());

// Insert another merge field for another column
// We don't need to use every column to perform a mail merge
fieldMergeField = (FieldMergeField) builder.insertField(FieldType.FIELD_MERGE_FIELD, true);
fieldMergeField.setFieldName("Last Name");
fieldMergeField.setTextAfter(":");

doc.updateFields();
doc.getMailMerge().execute(table);
doc.save(getArtifactsDir() + "Field.MERGEFIELD.docx");

Property Getters/Setters Summary
java.lang.StringgetDisplayResult()→ inherited from Field
           Gets the text that represents the displayed field result.
FieldEndgetEnd()→ inherited from Field
           Gets the node that represents the field end.
java.lang.StringgetFieldName()
voidsetFieldName(java.lang.String value)
           Gets or sets the name of a data field.
java.lang.StringgetFieldNameNoPrefix()
           Returns just the name of the data field. Any prefix is stripped to the prefix property.
FieldFormatgetFormat()→ inherited from Field
           Gets a FieldFormat object that provides typed access to field's formatting.
booleanisDirty()→ inherited from Field
voidisDirty(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.
booleanisLocked()→ inherited from Field
voidisLocked(boolean value)
           Gets or sets whether the field is locked (should not recalculate its result).
booleanisMapped()
voidisMapped(boolean value)
           Gets or sets whether this field is a mapped field.
booleanisVerticalFormatting()
voidisVerticalFormatting(boolean value)
           Gets or sets whether to enable character conversion for vertical formatting.
intgetLocaleId()→ inherited from Field
voidsetLocaleId(int value)
           Gets or sets the LCID of the field.
java.lang.StringgetResult()→ inherited from Field
voidsetResult(java.lang.String value)
           Gets or sets text that is between the field separator and field end.
FieldSeparatorgetSeparator()→ inherited from Field
           Gets the node that represents the field separator. Can be null.
FieldStartgetStart()→ inherited from Field
           Gets the node that represents the start of the field.
java.lang.StringgetTextAfter()
voidsetTextAfter(java.lang.String value)
           Gets or sets the text to be inserted after the field if the field is not blank.
java.lang.StringgetTextBefore()
voidsetTextBefore(java.lang.String value)
           Gets or sets the text to be inserted before the field if the field is not blank.
intgetType()
           Gets the Microsoft Word field type. The value of the property is FieldType integer constant.
 
Method Summary
java.lang.StringgetFieldCode()→ inherited from Field
           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)→ inherited from Field
           Returns text between field start and field separator (or field end if there is no separator).
Noderemove()→ inherited from Field
           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()→ inherited from Field
           Performs the field unlink.
voidupdate()→ inherited from Field
           Performs the field update. Throws if the field is being updated already.
voidupdate(boolean ignoreMergeFormat)→ inherited from Field
           Performs a field update. Throws if the field is being updated already.
 

Property Getters/Setters Detail

getDisplayResult

→ inherited from Field
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 text that represents the displayed field result.
Document document = new Document(getMyDir() + "Various fields.docx");

FieldCollection fields = document.getRange().getFields();

Assert.assertEquals(fields.get(0).getDisplayResult(), "111");
Assert.assertEquals(fields.get(1).getDisplayResult(), "222");
Assert.assertEquals(fields.get(2).getDisplayResult(), "Multi\rLine\rText");
Assert.assertEquals(fields.get(3).getDisplayResult(), "%");
Assert.assertEquals(fields.get(4).getDisplayResult(), "Macro Button Text");
Assert.assertEquals(fields.get(5).getDisplayResult(), "");

// Method must be called to obtain correct value for the "FieldListNum", "FieldAutoNum",
// "FieldAutoNumOut" and "FieldAutoNumLgl" fields
document.updateListLabels();

Assert.assertEquals(fields.get(5).getDisplayResult(), "1)");

getEnd

→ inherited from Field
public FieldEnd getEnd()
Gets the node that represents the field end.

Example:

Shows how to work with a document's field collection.
public void fieldCollection() throws Exception {
    // Create a new document and insert some fields
    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();

    // Get the collection that contains all the fields in a document
    FieldCollection fields = doc.getRange().getFields();
    Assert.assertEquals(fields.getCount(), 6);

    // 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());

    // Get a field to remove itself
    fields.get(0).remove();
    Assert.assertEquals(fields.getCount(), 5);

    // Remove a field by reference
    Field lastField = fields.get(3);
    fields.remove(lastField);
    Assert.assertEquals(fields.getCount(), 4);

    // Remove a field by index
    fields.removeAt(2);
    Assert.assertEquals(fields.getCount(), 3);

    // Remove all fields from the document
    fields.clear();
    Assert.assertEquals(fields.getCount(), 0);
}

/// <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 StringBuilder mBuilder;
}

getFieldName/setFieldName

public java.lang.String getFieldName() / public void setFieldName(java.lang.String value)
Gets or sets the name of a data field.

Example:

Shows how to use MERGEFIELD fields to perform a mail merge.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create data source for our merge fields
DataTable table = new DataTable("Employees");
table.getColumns().add("Courtesy Title");
table.getColumns().add("First Name");
table.getColumns().add("Last Name");
table.getRows().add("Mr.", "John", "Doe");
table.getRows().add("Mrs.", "Jane", "Cardholder");

// Insert a merge field that corresponds to one of our columns and put text before and after it
FieldMergeField fieldMergeField = (FieldMergeField) builder.insertField(FieldType.FIELD_MERGE_FIELD, true);
fieldMergeField.setFieldName("Courtesy Title");
fieldMergeField.isMapped(true);
fieldMergeField.isVerticalFormatting(false);
fieldMergeField.setTextBefore("Dear ");
fieldMergeField.setTextAfter(" ");

Assert.assertEquals(" MERGEFIELD  \"Courtesy Title\" \\m \\b \"Dear \" \\f \" \"", fieldMergeField.getFieldCode());

// Insert another merge field for another column
// We don't need to use every column to perform a mail merge
fieldMergeField = (FieldMergeField) builder.insertField(FieldType.FIELD_MERGE_FIELD, true);
fieldMergeField.setFieldName("Last Name");
fieldMergeField.setTextAfter(":");

doc.updateFields();
doc.getMailMerge().execute(table);
doc.save(getArtifactsDir() + "Field.MERGEFIELD.docx");

getFieldNameNoPrefix

public java.lang.String getFieldNameNoPrefix()
Returns just the name of the data field. Any prefix is stripped to the prefix property.

Example:

Shows how to use MERGEFIELD fields to perform a mail merge.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create data source for our merge fields
DataTable table = new DataTable("Employees");
table.getColumns().add("Courtesy Title");
table.getColumns().add("First Name");
table.getColumns().add("Last Name");
table.getRows().add("Mr.", "John", "Doe");
table.getRows().add("Mrs.", "Jane", "Cardholder");

// Insert a merge field that corresponds to one of our columns and put text before and after it
FieldMergeField fieldMergeField = (FieldMergeField) builder.insertField(FieldType.FIELD_MERGE_FIELD, true);
fieldMergeField.setFieldName("Courtesy Title");
fieldMergeField.isMapped(true);
fieldMergeField.isVerticalFormatting(false);
fieldMergeField.setTextBefore("Dear ");
fieldMergeField.setTextAfter(" ");

Assert.assertEquals(" MERGEFIELD  \"Courtesy Title\" \\m \\b \"Dear \" \\f \" \"", fieldMergeField.getFieldCode());

// Insert another merge field for another column
// We don't need to use every column to perform a mail merge
fieldMergeField = (FieldMergeField) builder.insertField(FieldType.FIELD_MERGE_FIELD, true);
fieldMergeField.setFieldName("Last Name");
fieldMergeField.setTextAfter(":");

doc.updateFields();
doc.getMailMerge().execute(table);
doc.save(getArtifactsDir() + "Field.MERGEFIELD.docx");

getFormat

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

Example:

Shows how to format fields.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert field with no format
Field field = builder.insertField("= 2 + 3");

// We can format our field here instead of in the field code
FieldFormat format = field.getFormat();
format.setNumericFormat("$###.00");
field.update();

// Apply a date/time format
field = builder.insertField("DATE");
format = field.getFormat();
format.setDateTimeFormat("dddd, MMMM dd, yyyy");
field.update();

// Apply 2 general formats at the same time
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()) {
    System.out.println(MessageFormat.format("General format index {0}: {1}", index++, generalFormatEnumerator.toString()));
}

Assert.assertEquals("LVIII", field.getResult());
Assert.assertEquals(2, format.getGeneralFormats().getCount());
Assert.assertEquals(format.getGeneralFormats().get(0), GeneralFormat.LOWERCASE_ROMAN);

// Removing field formats
format.getGeneralFormats().remove(GeneralFormat.LOWERCASE_ROMAN);
format.getGeneralFormats().removeAt(0);
Assert.assertEquals(format.getGeneralFormats().getCount(), 0);
field.update();

// Our field has no general formats left and is back to default form
Assert.assertEquals(field.getResult(), "58");

isDirty/isDirty

→ inherited from Field
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);

Field fieldToc = builder.insertTableOfContents("\\o \"1-3\" \\h \\z \\u");
fieldToc.isDirty(true);

doc.save(getArtifactsDir() + "Field.insertAndUpdateDirtyField.docx");

Assert.assertTrue(doc.getRange().getFields().get(0).isDirty());

LoadOptions loadOptions = new LoadOptions();
loadOptions.setUpdateDirtyFields(false);

doc = new Document(getArtifactsDir() + "Field.insertAndUpdateDirtyField.docx", loadOptions);

isLocked/isLocked

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

Example:

Demonstrates how to retrieve the field class from an existing FieldStart node in the document.
Document doc = new Document(getMyDir() + "Table of contents.docx");

FieldChar fieldStart = (FieldChar) doc.getChild(NodeType.FIELD_START, 0, true);
Assert.assertEquals(fieldStart.getFieldType(), FieldType.FIELD_TOC);
Assert.assertEquals(fieldStart.isDirty(), false);
Assert.assertEquals(fieldStart.isLocked(), false);

// Retrieve the facade object which represents the field in the document
Field field = fieldStart.getField();

Assert.assertEquals(field.isLocked(), false);
Assert.assertEquals(field.getFieldCode(), " TOC \\o \"1-3\" \\h \\z \\u ");

// This updates only this field in the document
field.update();

isMapped/isMapped

public boolean isMapped() / public void isMapped(boolean value)
Gets or sets whether this field is a mapped field.

Example:

Shows how to use MERGEFIELD fields to perform a mail merge.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create data source for our merge fields
DataTable table = new DataTable("Employees");
table.getColumns().add("Courtesy Title");
table.getColumns().add("First Name");
table.getColumns().add("Last Name");
table.getRows().add("Mr.", "John", "Doe");
table.getRows().add("Mrs.", "Jane", "Cardholder");

// Insert a merge field that corresponds to one of our columns and put text before and after it
FieldMergeField fieldMergeField = (FieldMergeField) builder.insertField(FieldType.FIELD_MERGE_FIELD, true);
fieldMergeField.setFieldName("Courtesy Title");
fieldMergeField.isMapped(true);
fieldMergeField.isVerticalFormatting(false);
fieldMergeField.setTextBefore("Dear ");
fieldMergeField.setTextAfter(" ");

Assert.assertEquals(" MERGEFIELD  \"Courtesy Title\" \\m \\b \"Dear \" \\f \" \"", fieldMergeField.getFieldCode());

// Insert another merge field for another column
// We don't need to use every column to perform a mail merge
fieldMergeField = (FieldMergeField) builder.insertField(FieldType.FIELD_MERGE_FIELD, true);
fieldMergeField.setFieldName("Last Name");
fieldMergeField.setTextAfter(":");

doc.updateFields();
doc.getMailMerge().execute(table);
doc.save(getArtifactsDir() + "Field.MERGEFIELD.docx");

isVerticalFormatting/isVerticalFormatting

public boolean isVerticalFormatting() / public void isVerticalFormatting(boolean value)
Gets or sets whether to enable character conversion for vertical formatting.

Example:

Shows how to use MERGEFIELD fields to perform a mail merge.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create data source for our merge fields
DataTable table = new DataTable("Employees");
table.getColumns().add("Courtesy Title");
table.getColumns().add("First Name");
table.getColumns().add("Last Name");
table.getRows().add("Mr.", "John", "Doe");
table.getRows().add("Mrs.", "Jane", "Cardholder");

// Insert a merge field that corresponds to one of our columns and put text before and after it
FieldMergeField fieldMergeField = (FieldMergeField) builder.insertField(FieldType.FIELD_MERGE_FIELD, true);
fieldMergeField.setFieldName("Courtesy Title");
fieldMergeField.isMapped(true);
fieldMergeField.isVerticalFormatting(false);
fieldMergeField.setTextBefore("Dear ");
fieldMergeField.setTextAfter(" ");

Assert.assertEquals(" MERGEFIELD  \"Courtesy Title\" \\m \\b \"Dear \" \\f \" \"", fieldMergeField.getFieldCode());

// Insert another merge field for another column
// We don't need to use every column to perform a mail merge
fieldMergeField = (FieldMergeField) builder.insertField(FieldType.FIELD_MERGE_FIELD, true);
fieldMergeField.setFieldName("Last Name");
fieldMergeField.setTextAfter(":");

doc.updateFields();
doc.getMailMerge().execute(table);
doc.save(getArtifactsDir() + "Field.MERGEFIELD.docx");

getLocaleId/setLocaleId

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

Example:

Get or sets locale for fields.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Field field = builder.insertField("DATE \\* MERGEFORMAT");
field.setLocaleId(2064);

ByteArrayOutputStream dstStream = new ByteArrayOutputStream();
doc.save(dstStream, SaveFormat.DOCX);

Field newField = doc.getRange().getFields().get(0);
Assert.assertEquals(newField.getLocaleId(), 2064);
See Also:
FieldUpdateCultureSource.FIELD_CODE

getResult/setResult

→ inherited from Field
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:

Inserts a field into a document using DocumentBuilder and FieldCode.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a simple Date field into the document
// When we insert a field through the DocumentBuilder class we can get the
// special Field object which contains information about the field
Field dateField = builder.insertField("DATE \\* MERGEFORMAT");

// Update this particular field in the document so we can get the FieldResult
dateField.update();

// Display some information from this field
// The field result is where the last evaluated value is stored. This is what is displayed in the document
// When field codes are not showing
System.out.println(MessageFormat.format("FieldResult: {0}", dateField.getResult()));

// Display the field code which defines the behavior of the field. This can been seen in Microsoft Word by pressing ALT+F9
System.out.println(MessageFormat.format("FieldCode: {0}", dateField.getFieldCode()));

// The field type defines what type of field in the Document this is. In this case the type is "FieldDate"
System.out.println(MessageFormat.format("FieldType: {0}", dateField.getType()));

// Finally let's completely remove the field from the document. This can easily be done by invoking the Remove method on the object
dateField.remove();

getSeparator

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

Example:

Shows how to work with a document's field collection.
public void fieldCollection() throws Exception {
    // Create a new document and insert some fields
    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();

    // Get the collection that contains all the fields in a document
    FieldCollection fields = doc.getRange().getFields();
    Assert.assertEquals(fields.getCount(), 6);

    // 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());

    // Get a field to remove itself
    fields.get(0).remove();
    Assert.assertEquals(fields.getCount(), 5);

    // Remove a field by reference
    Field lastField = fields.get(3);
    fields.remove(lastField);
    Assert.assertEquals(fields.getCount(), 4);

    // Remove a field by index
    fields.removeAt(2);
    Assert.assertEquals(fields.getCount(), 3);

    // Remove all fields from the document
    fields.clear();
    Assert.assertEquals(fields.getCount(), 0);
}

/// <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 StringBuilder mBuilder;
}

getStart

→ inherited from Field
public FieldStart getStart()
Gets the node that represents the start of the field.

Example:

Shows how to work with a document's field collection.
public void fieldCollection() throws Exception {
    // Create a new document and insert some fields
    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();

    // Get the collection that contains all the fields in a document
    FieldCollection fields = doc.getRange().getFields();
    Assert.assertEquals(fields.getCount(), 6);

    // 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());

    // Get a field to remove itself
    fields.get(0).remove();
    Assert.assertEquals(fields.getCount(), 5);

    // Remove a field by reference
    Field lastField = fields.get(3);
    fields.remove(lastField);
    Assert.assertEquals(fields.getCount(), 4);

    // Remove a field by index
    fields.removeAt(2);
    Assert.assertEquals(fields.getCount(), 3);

    // Remove all fields from the document
    fields.clear();
    Assert.assertEquals(fields.getCount(), 0);
}

/// <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 StringBuilder mBuilder;
}

getTextAfter/setTextAfter

public java.lang.String getTextAfter() / public void setTextAfter(java.lang.String value)
Gets or sets the text to be inserted after the field if the field is not blank.

Example:

Shows how to use MERGEFIELD fields to perform a mail merge.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create data source for our merge fields
DataTable table = new DataTable("Employees");
table.getColumns().add("Courtesy Title");
table.getColumns().add("First Name");
table.getColumns().add("Last Name");
table.getRows().add("Mr.", "John", "Doe");
table.getRows().add("Mrs.", "Jane", "Cardholder");

// Insert a merge field that corresponds to one of our columns and put text before and after it
FieldMergeField fieldMergeField = (FieldMergeField) builder.insertField(FieldType.FIELD_MERGE_FIELD, true);
fieldMergeField.setFieldName("Courtesy Title");
fieldMergeField.isMapped(true);
fieldMergeField.isVerticalFormatting(false);
fieldMergeField.setTextBefore("Dear ");
fieldMergeField.setTextAfter(" ");

Assert.assertEquals(" MERGEFIELD  \"Courtesy Title\" \\m \\b \"Dear \" \\f \" \"", fieldMergeField.getFieldCode());

// Insert another merge field for another column
// We don't need to use every column to perform a mail merge
fieldMergeField = (FieldMergeField) builder.insertField(FieldType.FIELD_MERGE_FIELD, true);
fieldMergeField.setFieldName("Last Name");
fieldMergeField.setTextAfter(":");

doc.updateFields();
doc.getMailMerge().execute(table);
doc.save(getArtifactsDir() + "Field.MERGEFIELD.docx");

getTextBefore/setTextBefore

public java.lang.String getTextBefore() / public void setTextBefore(java.lang.String value)
Gets or sets the text to be inserted before the field if the field is not blank.

Example:

Shows how to mail merge HTML data into a document.
public void insertHtml() throws Exception
{
    Document doc = new Document(getMyDir() + "Field MERGEFIELD.docx");

    // Add a handler for the MergeField event
    doc.getMailMerge().setFieldMergingCallback(new HandleMergeFieldInsertHtml());

    // Load some Html from file
    StringBuilder htmlText = new StringBuilder();
    BufferedReader reader = new BufferedReader(new FileReader(getMyDir() + "MailMerge.HtmlData.html"));
    String line;
    while ((line = reader.readLine()) != null) {
        htmlText.append(line);
        htmlText.append("\r\n");
    }

    // Execute mail merge
    doc.getMailMerge().execute(new String[]{"htmlField1"}, new String[]{htmlText.toString()});

    // Save resulting document with a new name
    doc.save(getArtifactsDir() + "MailMergeEvent.InsertHtml.docx");
}

private class HandleMergeFieldInsertHtml implements IFieldMergingCallback {
    /**
     * This is called when merge field is actually merged with data in the document.
     */
    public void fieldMerging(final FieldMergingArgs args) throws Exception {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'
        if (args.getDocumentFieldName().startsWith("html") && args.getField().getFieldCode().contains("\\b"))
        {
            FieldMergeField field = args.getField();

            // Insert the text for this merge field as HTML data, using DocumentBuilder
            DocumentBuilder builder = new DocumentBuilder(args.getDocument());
            builder.moveToMergeField(args.getDocumentFieldName());
            builder.write(field.getTextBefore());
            builder.insertHtml((String) args.getFieldValue());

            // The HTML text itself should not be inserted
            // We have already inserted it as an HTML
            args.setText("");
        }
    }

    public void imageFieldMerging(final ImageFieldMergingArgs args) {
        // Do nothing
    }
}

getType

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

Method Detail

getFieldCode

→ inherited from Field
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:

Inserts a field into a document using DocumentBuilder and FieldCode.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a simple Date field into the document
// When we insert a field through the DocumentBuilder class we can get the
// special Field object which contains information about the field
Field dateField = builder.insertField("DATE \\* MERGEFORMAT");

// Update this particular field in the document so we can get the FieldResult
dateField.update();

// Display some information from this field
// The field result is where the last evaluated value is stored. This is what is displayed in the document
// When field codes are not showing
System.out.println(MessageFormat.format("FieldResult: {0}", dateField.getResult()));

// Display the field code which defines the behavior of the field. This can been seen in Microsoft Word by pressing ALT+F9
System.out.println(MessageFormat.format("FieldCode: {0}", dateField.getFieldCode()));

// The field type defines what type of field in the Document this is. In this case the type is "FieldDate"
System.out.println(MessageFormat.format("FieldType: {0}", dateField.getType()));

// Finally let's completely remove the field from the document. This can easily be done by invoking the Remove method on the object
dateField.remove();

Example:

Shows how to get text between field start and field separator (or field end if there is no separator).
Document doc = new Document(getMyDir() + "Nested fields.docx");

for (Field field : doc.getRange().getFields()) {
    if (field.getType() == FieldType.FIELD_IF) {
        FieldIf fieldIf = (FieldIf) field;

        String fieldCode = fieldIf.getFieldCode();

        if (containsNestedFields) {
            fieldCode = fieldIf.getFieldCode(true);
        } else {
            fieldCode = fieldIf.getFieldCode(false);
        }
    }
}

getFieldCode

→ inherited from Field
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 text between field start and field separator (or field end if there is no separator).
Document doc = new Document(getMyDir() + "Nested fields.docx");

for (Field field : doc.getRange().getFields()) {
    if (field.getType() == FieldType.FIELD_IF) {
        FieldIf fieldIf = (FieldIf) field;

        String fieldCode = fieldIf.getFieldCode();

        if (containsNestedFields) {
            fieldCode = fieldIf.getFieldCode(true);
        } else {
            fieldCode = fieldIf.getFieldCode(false);
        }
    }
}

remove

→ inherited from Field
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 work with a document's field collection.
public void fieldCollection() throws Exception {
    // Create a new document and insert some fields
    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();

    // Get the collection that contains all the fields in a document
    FieldCollection fields = doc.getRange().getFields();
    Assert.assertEquals(fields.getCount(), 6);

    // 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());

    // Get a field to remove itself
    fields.get(0).remove();
    Assert.assertEquals(fields.getCount(), 5);

    // Remove a field by reference
    Field lastField = fields.get(3);
    fields.remove(lastField);
    Assert.assertEquals(fields.getCount(), 4);

    // Remove a field by index
    fields.removeAt(2);
    Assert.assertEquals(fields.getCount(), 3);

    // Remove all fields from the document
    fields.clear();
    Assert.assertEquals(fields.getCount(), 0);
}

/// <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 StringBuilder mBuilder;
}

Example:

Inserts a field into a document using DocumentBuilder and FieldCode.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a simple Date field into the document
// When we insert a field through the DocumentBuilder class we can get the
// special Field object which contains information about the field
Field dateField = builder.insertField("DATE \\* MERGEFORMAT");

// Update this particular field in the document so we can get the FieldResult
dateField.update();

// Display some information from this field
// The field result is where the last evaluated value is stored. This is what is displayed in the document
// When field codes are not showing
System.out.println(MessageFormat.format("FieldResult: {0}", dateField.getResult()));

// Display the field code which defines the behavior of the field. This can been seen in Microsoft Word by pressing ALT+F9
System.out.println(MessageFormat.format("FieldCode: {0}", dateField.getFieldCode()));

// The field type defines what type of field in the Document this is. In this case the type is "FieldDate"
System.out.println(MessageFormat.format("FieldType: {0}", dateField.getType()));

// Finally let's completely remove the field from the document. This can easily be done by invoking the Remove method on the object
dateField.remove();

unlink

→ inherited from Field
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 specific field.
Document doc = new Document(getMyDir() + "Linked fields.docx");
doc.getRange().getFields().get(1).unlink();

update

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

Example:

Inserts a field into a document using DocumentBuilder and FieldCode.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a simple Date field into the document
// When we insert a field through the DocumentBuilder class we can get the
// special Field object which contains information about the field
Field dateField = builder.insertField("DATE \\* MERGEFORMAT");

// Update this particular field in the document so we can get the FieldResult
dateField.update();

// Display some information from this field
// The field result is where the last evaluated value is stored. This is what is displayed in the document
// When field codes are not showing
System.out.println(MessageFormat.format("FieldResult: {0}", dateField.getResult()));

// Display the field code which defines the behavior of the field. This can been seen in Microsoft Word by pressing ALT+F9
System.out.println(MessageFormat.format("FieldCode: {0}", dateField.getFieldCode()));

// The field type defines what type of field in the Document this is. In this case the type is "FieldDate"
System.out.println(MessageFormat.format("FieldType: {0}", dateField.getType()));

// Finally let's completely remove the field from the document. This can easily be done by invoking the Remove method on the object
dateField.remove();

update

→ inherited from Field
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.

Example:

Shows a way to update a field ignoring the MERGEFORMAT switch.
LoadOptions loadOptions = new LoadOptions();
{
    loadOptions.setPreserveIncludePictureField(true);
}

Document doc = new Document(getMyDir() + "Field INCLUDEPICTURE.docx", loadOptions);

for (Field field : doc.getRange().getFields()) {
    if (((field.getType()) == (FieldType.FIELD_INCLUDE_PICTURE))) {
        FieldIncludePicture includePicture = (FieldIncludePicture) field;
        includePicture.setSourceFullName(getImageDir() + "Transparent background logo.png");
        includePicture.update(true);
    }
}

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

See Also:
          Aspose.Words Documentation - the home page for the Aspose.Words Product Documentation.
          Aspose.Words Support Forum - our preferred method of support.