com.aspose.words
Class FieldMergingArgs

java.lang.Object
  extended by FieldMergingArgsBase
      extended by com.aspose.words.FieldMergingArgs

public class FieldMergingArgs 
extends FieldMergingArgsBase

Provides data for the MergeField event.

The MergeField event occurs during mail merge when a simple mail merge field is encountered in the document. You can respond to this event to return text for the mail merge engine to insert into the document.

Example:

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

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

    final String htmlText = "<html>\r\n<h1>Hello world!</h1>\r\n</html>";

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

    // 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 /*IFieldMergingCallback.*/imageFieldMerging(ImageFieldMergingArgs args) {
        // Do nothing
    }
}
See Also:
IFieldMergingCallback

Property Getters/Setters Summary
DocumentgetDocument()→ inherited from FieldMergingArgsBase
           Returns the Document object for which the mail merge is performed.
java.lang.StringgetDocumentFieldName()→ inherited from FieldMergingArgsBase
           Gets the name of the merge field as specified in the document.
FieldMergeFieldgetField()→ inherited from FieldMergingArgsBase
           Gets the object that represents the current merge field.
java.lang.StringgetFieldName()→ inherited from FieldMergingArgsBase
           Gets the name of the merge field in the data source.
java.lang.ObjectgetFieldValue()→ inherited from FieldMergingArgsBase
voidsetFieldValue(java.lang.Object value)
           Gets or sets the value of the field from the data source.
intgetRecordIndex()→ inherited from FieldMergingArgsBase
           Gets the zero based index of the record that is being merged.
java.lang.StringgetTableName()→ inherited from FieldMergingArgsBase
           Gets the name of the data table for the current merge operation or empty string if the name is not available.
java.lang.StringgetText()
voidsetText(java.lang.String value)
           Gets or sets the text that will be inserted into the document for the current merge field.
 

Property Getters/Setters Detail

getDocument

→ inherited from FieldMergingArgsBase
public Document getDocument()
Returns the Document object for which the mail merge is performed.

Example:

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

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

    final String htmlText = "<html>\r\n<h1>Hello world!</h1>\r\n</html>";

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

    // 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 /*IFieldMergingCallback.*/imageFieldMerging(ImageFieldMergingArgs args) {
        // Do nothing
    }
}

getDocumentFieldName

→ inherited from FieldMergingArgsBase
public java.lang.String getDocumentFieldName()
Gets the name of the merge field as specified in the document.

If you have a mapping from a document field name to a different data source field name, then this is the original field name as specified in the document.

If you specified a field name prefix, for example "Image:MyFieldName" in the document, then DocumentFieldName returns field name without the prefix, that is "MyFieldName".

Example:

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

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

    final String htmlText = "<html>\r\n<h1>Hello world!</h1>\r\n</html>";

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

    // 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 /*IFieldMergingCallback.*/imageFieldMerging(ImageFieldMergingArgs args) {
        // Do nothing
    }
}

getField

→ inherited from FieldMergingArgsBase
public FieldMergeField getField()
Gets the object that represents the current merge field.

Example:

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

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

    final String htmlText = "<html>\r\n<h1>Hello world!</h1>\r\n</html>";

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

    // 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 /*IFieldMergingCallback.*/imageFieldMerging(ImageFieldMergingArgs args) {
        // Do nothing
    }
}

getFieldName

→ inherited from FieldMergingArgsBase
public java.lang.String getFieldName()
Gets the name of the merge field in the data source.

If you have a mapping from a document field name to a different data source field name, then this is the mapped field name.

If you specified a field name prefix, for example "Image:MyFieldName" in the document, then FieldName returns field name without the prefix, that is "MyFieldName".

Example:

Shows how to insert checkbox form fields into a document during mail merge.
public void insertCheckBox() throws Exception {
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.startTable();
    builder.insertCell();
    builder.insertField(" MERGEFIELD  TableStart:StudentCourse ");
    builder.insertCell();
    builder.insertField(" MERGEFIELD  CourseName ");
    builder.insertCell();
    builder.insertField(" MERGEFIELD  TableEnd:StudentCourse ");
    builder.endTable();

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

    // Execute mail merge with regions
    DataTable dataTable = getStudentCourseDataTable();
    doc.getMailMerge().executeWithRegions(dataTable);

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

private class HandleMergeFieldInsertCheckBox implements IFieldMergingCallback {
    /**
     * This is called for each merge field in the document
     * when Document.MailMerge.ExecuteWithRegions is called.
     */
    public void fieldMerging(final FieldMergingArgs args) throws Exception {
        if (args.getDocumentFieldName().equals("CourseName")) {
            // The name of the table that we are merging can be found here
            Assert.assertEquals(args.getTableName(), "StudentCourse");

            // Insert the checkbox for this merge field, using DocumentBuilder
            DocumentBuilder builder = new DocumentBuilder(args.getDocument());
            builder.moveToMergeField(args.getFieldName());
            builder.insertCheckBox(args.getDocumentFieldName() + mCheckBoxCount, false, 0);
            // Get the actual value of the field
            String fieldValue = args.getFieldValue().toString();

            // In this case, for every record index 'n', the corresponding field value is "Course n"
            Assert.assertEquals(args.getRecordIndex(), Character.getNumericValue(fieldValue.charAt(7)));

            builder.write(fieldValue);
            mCheckBoxCount++;
        }
    }

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

    /**
     * Counter for CheckBox name generation.
     */
    private int mCheckBoxCount;
}

/**
 * Create DataTable and fill it with data.
 * In real life this DataTable should be filled from a database.
 */
private static DataTable getStudentCourseDataTable() throws Exception {
    DataTable dataTable = new DataTable("StudentCourse");
    dataTable.getColumns().add("CourseName");
    for (int i = 0; i < 10; i++) {
        DataRow datarow = dataTable.newRow();
        dataTable.getRows().add(datarow);
        datarow.set(0, "Course " + i);
    }
    return dataTable;
}

getFieldValue/setFieldValue

→ inherited from FieldMergingArgsBase
public java.lang.Object getFieldValue() / public void setFieldValue(java.lang.Object value)
Gets or sets the value of the field from the data source. This property contains a value that has just been selected from your data source for this field by the mail merge engine. You can also replace the value by setting the property.

Example:

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

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

    final String htmlText = "<html>\r\n<h1>Hello world!</h1>\r\n</html>";

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

    // 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 /*IFieldMergingCallback.*/imageFieldMerging(ImageFieldMergingArgs args) {
        // Do nothing
    }
}

Example:

Shows how to use data source value of the field.
public void fieldFormats() throws Exception {
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);
    builder.insertField("MERGEFIELD TextField \\* Caps", null);
    builder.write(", ");
    builder.insertField("MERGEFIELD TextField2 \\* Upper", null);
    builder.write(", ");
    builder.insertField("MERGEFIELD NumericField \\# 0.0", null);

    builder.getDocument().getMailMerge().setFieldMergingCallback(new FieldValueMergingCallback());

    builder.getDocument().getMailMerge().execute(
            new String[]{"TextField", "TextField2", "NumericField"},
            new Object[]{"Original value", "Original value", 10});

    Assert.assertEquals("New Value, New value from FieldMergingArgs, 20.0", doc.getText().trim());
}

private static class FieldValueMergingCallback implements IFieldMergingCallback {
    /// <summary>
    /// This is called when merge field is actually merged with data in the document.
    /// </summary>
    public void /*IFieldMergingCallback.*/fieldMerging(FieldMergingArgs e) {
        switch (e.getFieldName()) {
            case "TextField":
                Assert.assertEquals("Original value", e.getFieldValue());
                e.setFieldValue("New value");
                break;
            case "TextField2":
                Assert.assertEquals("Original value", e.getFieldValue());
                e.setText("New value from FieldMergingArgs");   // Should suppress e.FieldValue and ignore format
                e.setFieldValue("new value");
                break;
            case "NumericField":
                Assert.assertEquals(10, e.getFieldValue());
                e.setFieldValue(20);
                break;
        }
    }

    public void /*IFieldMergingCallback.*/imageFieldMerging(ImageFieldMergingArgs e) {
        // Do nothing
    }
}

getRecordIndex

→ inherited from FieldMergingArgsBase
public int getRecordIndex()
Gets the zero based index of the record that is being merged.

Example:

Shows how to insert checkbox form fields into a document during mail merge.
public void insertCheckBox() throws Exception {
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.startTable();
    builder.insertCell();
    builder.insertField(" MERGEFIELD  TableStart:StudentCourse ");
    builder.insertCell();
    builder.insertField(" MERGEFIELD  CourseName ");
    builder.insertCell();
    builder.insertField(" MERGEFIELD  TableEnd:StudentCourse ");
    builder.endTable();

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

    // Execute mail merge with regions
    DataTable dataTable = getStudentCourseDataTable();
    doc.getMailMerge().executeWithRegions(dataTable);

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

private class HandleMergeFieldInsertCheckBox implements IFieldMergingCallback {
    /**
     * This is called for each merge field in the document
     * when Document.MailMerge.ExecuteWithRegions is called.
     */
    public void fieldMerging(final FieldMergingArgs args) throws Exception {
        if (args.getDocumentFieldName().equals("CourseName")) {
            // The name of the table that we are merging can be found here
            Assert.assertEquals(args.getTableName(), "StudentCourse");

            // Insert the checkbox for this merge field, using DocumentBuilder
            DocumentBuilder builder = new DocumentBuilder(args.getDocument());
            builder.moveToMergeField(args.getFieldName());
            builder.insertCheckBox(args.getDocumentFieldName() + mCheckBoxCount, false, 0);
            // Get the actual value of the field
            String fieldValue = args.getFieldValue().toString();

            // In this case, for every record index 'n', the corresponding field value is "Course n"
            Assert.assertEquals(args.getRecordIndex(), Character.getNumericValue(fieldValue.charAt(7)));

            builder.write(fieldValue);
            mCheckBoxCount++;
        }
    }

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

    /**
     * Counter for CheckBox name generation.
     */
    private int mCheckBoxCount;
}

/**
 * Create DataTable and fill it with data.
 * In real life this DataTable should be filled from a database.
 */
private static DataTable getStudentCourseDataTable() throws Exception {
    DataTable dataTable = new DataTable("StudentCourse");
    dataTable.getColumns().add("CourseName");
    for (int i = 0; i < 10; i++) {
        DataRow datarow = dataTable.newRow();
        dataTable.getRows().add(datarow);
        datarow.set(0, "Course " + i);
    }
    return dataTable;
}

getTableName

→ inherited from FieldMergingArgsBase
public java.lang.String getTableName()
Gets the name of the data table for the current merge operation or empty string if the name is not available.

Example:

Shows how to insert checkbox form fields into a document during mail merge.
public void insertCheckBox() throws Exception {
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.startTable();
    builder.insertCell();
    builder.insertField(" MERGEFIELD  TableStart:StudentCourse ");
    builder.insertCell();
    builder.insertField(" MERGEFIELD  CourseName ");
    builder.insertCell();
    builder.insertField(" MERGEFIELD  TableEnd:StudentCourse ");
    builder.endTable();

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

    // Execute mail merge with regions
    DataTable dataTable = getStudentCourseDataTable();
    doc.getMailMerge().executeWithRegions(dataTable);

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

private class HandleMergeFieldInsertCheckBox implements IFieldMergingCallback {
    /**
     * This is called for each merge field in the document
     * when Document.MailMerge.ExecuteWithRegions is called.
     */
    public void fieldMerging(final FieldMergingArgs args) throws Exception {
        if (args.getDocumentFieldName().equals("CourseName")) {
            // The name of the table that we are merging can be found here
            Assert.assertEquals(args.getTableName(), "StudentCourse");

            // Insert the checkbox for this merge field, using DocumentBuilder
            DocumentBuilder builder = new DocumentBuilder(args.getDocument());
            builder.moveToMergeField(args.getFieldName());
            builder.insertCheckBox(args.getDocumentFieldName() + mCheckBoxCount, false, 0);
            // Get the actual value of the field
            String fieldValue = args.getFieldValue().toString();

            // In this case, for every record index 'n', the corresponding field value is "Course n"
            Assert.assertEquals(args.getRecordIndex(), Character.getNumericValue(fieldValue.charAt(7)));

            builder.write(fieldValue);
            mCheckBoxCount++;
        }
    }

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

    /**
     * Counter for CheckBox name generation.
     */
    private int mCheckBoxCount;
}

/**
 * Create DataTable and fill it with data.
 * In real life this DataTable should be filled from a database.
 */
private static DataTable getStudentCourseDataTable() throws Exception {
    DataTable dataTable = new DataTable("StudentCourse");
    dataTable.getColumns().add("CourseName");
    for (int i = 0; i < 10; i++) {
        DataRow datarow = dataTable.newRow();
        dataTable.getRows().add(datarow);
        datarow.set(0, "Course " + i);
    }
    return dataTable;
}

getText/setText

public java.lang.String getText() / public void setText(java.lang.String value)
Gets or sets the text that will be inserted into the document for the current merge field.

When your event handler is called, this property is set to null.

If you leave Text as null, the mail merge engine will insert FieldValue in place of the merge field.

If you set Text to any string (including empty), the string will be inserted into the document in place of the merge field.

Example:

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

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

    final String htmlText = "<html>\r\n<h1>Hello world!</h1>\r\n</html>";

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

    // 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 /*IFieldMergingCallback.*/imageFieldMerging(ImageFieldMergingArgs args) {
        // Do nothing
    }
}

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