com.aspose.words

Class ImageFieldMergingArgs

public class ImageFieldMergingArgs 
extends FieldMergingArgsBase

This event occurs during mail merge when an image mail merge field is encountered in the document. You can respond to this event to return a file name, stream, or an java.awt.image.BufferedImage object to the mail merge engine so it is inserted into the document.

There are three properties available ImageFileName, ImageStream and Image to specify where the image must be taken from. Set only one of these properties.

To insert an image mail merge field into a document in Word, select Insert/Field command, then select MergeField and type Image:MyFieldName.

Example:

Shows how to insert images stored in a database BLOB field into a report.
public void mailMergeImageFromBlob() throws Exception {
    Document doc = new Document(getMyDir() + "MailMerge.MergeImage.doc");

    // Set up the event handler for image fields.
    doc.getMailMerge().setFieldMergingCallback(new HandleMergeImageFieldFromBlob());

    // Loads the driver
    Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");

    // Open the database connection.
    String connString = "jdbc:ucanaccess://" + getDatabaseDir() + "Northwind.mdb";

    // DSN-less DB connection.
    java.sql.Connection conn = java.sql.DriverManager.getConnection(connString, "Admin", "");

    // Create and execute a command.
    java.sql.Statement statement = conn.createStatement();
    java.sql.ResultSet resultSet = statement.executeQuery("SELECT * FROM Employees");

    DataTable table = new DataTable(resultSet, "Employees");

    // Perform mail merge.
    doc.getMailMerge().executeWithRegions(table);

    // Close the database.
    conn.close();

    doc.save(getArtifactsDir() + "MailMerge.MergeImage.doc");
}

private class HandleMergeImageFieldFromBlob implements IFieldMergingCallback {
    public void fieldMerging(final FieldMergingArgs args) {
        // Do nothing.
    }

    /**
     * This is called when mail merge engine encounters Image:XXX merge field in the document.
     * You have a chance to return an Image object, file name or a stream that contains the image.
     */
    public void imageFieldMerging(final ImageFieldMergingArgs e) {
        // The field value is a byte array, just cast it and create a stream on it.
        ByteArrayInputStream imageStream = new ByteArrayInputStream((byte[]) e.getFieldValue());
        // Now the mail merge engine will retrieve the image from the stream.
        e.setImageStream(imageStream);
    }
}

Example:

Shows how to set the dimensions of merged images.
@Test
public void mergeFieldImageDimension() throws Exception {
    Document doc = new Document();

    // Insert a merge field where images will be placed during the mail merge
    DocumentBuilder builder = new DocumentBuilder(doc);
    builder.insertField("MERGEFIELD Image:ImageColumn");

    // Create a data table for the mail merge
    // The name of the column that contains our image filenames needs to match the name of our merge field
    DataTable dataTable = createDataTable("Images", "ImageColumn",
            new String[]
                    {
                            getImageDir() + "Aspose.Words.gif",
                            getImageDir() + "Watermark.png",
                            getImageDir() + "dotnet-logo.png"
                    });

    doc.getMailMerge().setFieldMergingCallback(new MergedImageResizer(450.0, 200.0, MergeFieldImageDimensionUnit.POINT));
    doc.getMailMerge().execute(dataTable);

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

/// <summary>
/// Creates a data table with a single column
/// </summary>
private DataTable createDataTable(final String tableName, final String columnName, final String[] columnContents) {
    DataTable dataTable = new DataTable(tableName);
    dataTable.getColumns().add(new DataColumn(columnName));

    for (String s : columnContents) {
        DataRow dataRow = dataTable.newRow();
        dataRow.set(0, s);
        dataTable.getRows().add(dataRow);
    }

    return dataTable;
}

/// <summary>
/// Sets the size of all mail merged images to one defined width and height
/// </summary>
private static class MergedImageResizer implements IFieldMergingCallback {
    public MergedImageResizer(final double imageWidth, final double imageHeight, final int unit) {
        mImageWidth = imageWidth;
        mImageHeight = imageHeight;
        mUnit = unit;
    }

    public void fieldMerging(final FieldMergingArgs args) {
        throw new UnsupportedOperationException();
    }

    public void imageFieldMerging(final ImageFieldMergingArgs args) {
        args.setImageFileName(args.getFieldValue().toString());
        args.setImageWidth(new MergeFieldImageDimension(mImageWidth, mUnit));
        args.setImageHeight(new MergeFieldImageDimension(mImageHeight, mUnit));

        Assert.assertEquals(mImageWidth, args.getImageWidth().getValue());
        Assert.assertEquals(mUnit, args.getImageWidth().getUnit());
        Assert.assertEquals(mImageHeight, args.getImageHeight().getValue());
        Assert.assertEquals(mUnit, args.getImageHeight().getUnit());
    }

    private double mImageWidth;
    private double mImageHeight;
    private int mUnit;
}
See Also:
IFieldMergingCallback

Property Getters/Setters Summary
DocumentgetDocument()
Returns the Document object for which the mail merge is performed.
java.lang.StringgetDocumentFieldName()
Gets the name of the merge field as specified in the document.
FieldMergeFieldgetField()
Gets the object that represents the current merge field.
java.lang.StringgetFieldName()
Gets the name of the merge field in the data source.
java.lang.ObjectgetFieldValue()
Gets the value of the field from the data source.
java.awt.image.BufferedImagegetImage()
void
setImage(java.awt.image.BufferedImagevalue)
           Specifies the image that the mail merge engine must insert into the document.
java.lang.StringgetImageFileName()
void
setImageFileName(java.lang.Stringvalue)
           Sets the file name of the image that the mail merge engine must insert into the document.
MergeFieldImageDimensiongetImageHeight()
void
           Specifies the image height for the image to insert into the document.
java.io.InputStreamgetImageStream()
void
setImageStream(java.io.InputStreamvalue)
           Specifies the stream for the mail merge engine to read an image from.
MergeFieldImageDimensiongetImageWidth()
void
           Specifies the image width for the image to insert into the document.
intgetRecordIndex()
Gets the zero based index of the record that is being merged.
java.lang.StringgetTableName()
Gets the name of the data table for the current merge operation or empty string if the name is not available.
 

    • Property Getters/Setters Detail

      • getDocument

        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.
        // File 'MailMerge.InsertHtml.doc' has merge field named 'htmlField1' in it.
        // File 'MailMerge.HtmlData.html' contains some valid HTML data.
        // The same approach can be used when merging HTML data from database.
        public void mailMergeInsertHtml() throws Exception {
            Document doc = new Document(getMyDir() + "MailMerge.InsertHtml.doc");
        
            // Add a handler for the ApiExamples.Tests.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() + "MailMerge.InsertHtml.doc");
        }
        
        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")) {
                    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 e) {
                // Do nothing.
            }
        }
      • getDocumentFieldName

        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.
        // File 'MailMerge.InsertHtml.doc' has merge field named 'htmlField1' in it.
        // File 'MailMerge.HtmlData.html' contains some valid HTML data.
        // The same approach can be used when merging HTML data from database.
        public void mailMergeInsertHtml() throws Exception {
            Document doc = new Document(getMyDir() + "MailMerge.InsertHtml.doc");
        
            // Add a handler for the ApiExamples.Tests.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() + "MailMerge.InsertHtml.doc");
        }
        
        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")) {
                    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 e) {
                // Do nothing.
            }
        }
      • getField

        public FieldMergeField getField()
        
        Gets the object that represents the current merge field.

        Example:

        Shows how to mail merge HTML data into a document.
        // File 'MailMerge.InsertHtml.doc' has merge field named 'htmlField1' in it.
        // File 'MailMerge.HtmlData.html' contains some valid HTML data.
        // The same approach can be used when merging HTML data from database.
        public void mailMergeInsertHtml() throws Exception {
            Document doc = new Document(getMyDir() + "MailMerge.InsertHtml.doc");
        
            // Add a handler for the ApiExamples.Tests.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() + "MailMerge.InsertHtml.doc");
        }
        
        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")) {
                    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 e) {
                // Do nothing.
            }
        }
      • getFieldName

        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.
        // File 'MailMerge.InsertCheckBox.doc' is a template
        // containing the table with the following fields in it:
        // <<TableStart:StudentCourse>> <<CourseName>> <<TableEnd:StudentCourse>>.
        public void mailMergeInsertCheckBox() throws Exception {
            Document doc = new Document(getMyDir() + "MailMerge.InsertCheckBox.doc");
        
            // Add a handler for the ApiExamples.Tests.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() + "MailMerge.InsertCheckBox.doc");
        }
        
        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 e) throws Exception {
                if (e.getDocumentFieldName().equals("CourseName")) {
                    // Insert the checkbox for this merge field, using DocumentBuilder.
                    DocumentBuilder builder = new DocumentBuilder(e.getDocument());
                    builder.moveToMergeField(e.getFieldName());
                    builder.insertCheckBox(e.getDocumentFieldName() + Integer.toString(mCheckBoxCount), false, 0);
                    builder.write((String) e.getFieldValue());
                    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 " + Integer.toString(i));
            }
            return dataTable;
        }
      • getFieldValue

        public java.lang.Object getFieldValue()
        
        Gets 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.

        Example:

        Shows how to mail merge HTML data into a document.
        // File 'MailMerge.InsertHtml.doc' has merge field named 'htmlField1' in it.
        // File 'MailMerge.HtmlData.html' contains some valid HTML data.
        // The same approach can be used when merging HTML data from database.
        public void mailMergeInsertHtml() throws Exception {
            Document doc = new Document(getMyDir() + "MailMerge.InsertHtml.doc");
        
            // Add a handler for the ApiExamples.Tests.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() + "MailMerge.InsertHtml.doc");
        }
        
        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")) {
                    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 e) {
                // Do nothing.
            }
        }
      • getImage/setImage

        public java.awt.image.BufferedImage getImage() / public void setImage(java.awt.image.BufferedImage value)
        
        Specifies the image that the mail merge engine must insert into the document.

        Example:

        Shows how to set which images to merge during the mail merge.
        public void mergeFieldImages() throws Exception {
            Document doc = new Document();
        
            // Insert a merge field where images will be placed during the mail merge
            DocumentBuilder builder = new DocumentBuilder(doc);
            builder.insertField("MERGEFIELD Image:ImageColumn");
        
            // When we merge images, our data table will normally have the full e. of the images we wish to merge
            // If this is cumbersome, we can move image filename logic to another place and populate the data table with just shorthands for images
            DataTable dataTable = createDataTable("Images", "ImageColumn",
                    new String[]
                            {
                                    "Aspose logo",
                                    ".Net logo",
                                    "Watermark"
                            });
        
            // A custom merging callback will contain filenames that our shorthands will refer to
            doc.getMailMerge().setFieldMergingCallback(new ImageFilenameCallback());
            doc.getMailMerge().execute(dataTable);
        
            doc.save(getArtifactsDir() + "Field.MergeFieldImages.docx");
        }
        
        /// <summary>
        /// Image merging callback that pairs image shorthand names with filenames
        /// </summary>
        private static class ImageFilenameCallback implements IFieldMergingCallback {
            public ImageFilenameCallback() {
                imageFilenames.put("Aspose logo", getImageDir() + "Aspose.Words.gif");
                imageFilenames.put(".Net logo", getImageDir() + "dotnet-logo.png");
                imageFilenames.put("Watermark", getImageDir() + "Watermark.png");
            }
        
            public void fieldMerging(FieldMergingArgs e) {
                throw new UnsupportedOperationException();
            }
        
            public void imageFieldMerging(ImageFieldMergingArgs e) throws IOException {
                if (imageFilenames.containsKey(e.getFieldValue().toString())) {
                    BufferedImage image = ImageIO.read(new File(imageFilenames.get(e.getFieldValue().toString())));
                    e.setImage(image);
                }
        
                Assert.assertNotNull(e.getImage());
            }
        
            private HashMap<String, String> imageFilenames = new HashMap<>();
        }
      • getImageFileName/setImageFileName

        public java.lang.String getImageFileName() / public void setImageFileName(java.lang.String value)
        
        Sets the file name of the image that the mail merge engine must insert into the document.

        Example:

        Shows how to set the dimensions of merged images.
        @Test
        public void mergeFieldImageDimension() throws Exception {
            Document doc = new Document();
        
            // Insert a merge field where images will be placed during the mail merge
            DocumentBuilder builder = new DocumentBuilder(doc);
            builder.insertField("MERGEFIELD Image:ImageColumn");
        
            // Create a data table for the mail merge
            // The name of the column that contains our image filenames needs to match the name of our merge field
            DataTable dataTable = createDataTable("Images", "ImageColumn",
                    new String[]
                            {
                                    getImageDir() + "Aspose.Words.gif",
                                    getImageDir() + "Watermark.png",
                                    getImageDir() + "dotnet-logo.png"
                            });
        
            doc.getMailMerge().setFieldMergingCallback(new MergedImageResizer(450.0, 200.0, MergeFieldImageDimensionUnit.POINT));
            doc.getMailMerge().execute(dataTable);
        
            doc.updateFields();
            doc.save(getArtifactsDir() + "Field.MergeFieldImageDimension.docx");
        }
        
        /// <summary>
        /// Creates a data table with a single column
        /// </summary>
        private DataTable createDataTable(final String tableName, final String columnName, final String[] columnContents) {
            DataTable dataTable = new DataTable(tableName);
            dataTable.getColumns().add(new DataColumn(columnName));
        
            for (String s : columnContents) {
                DataRow dataRow = dataTable.newRow();
                dataRow.set(0, s);
                dataTable.getRows().add(dataRow);
            }
        
            return dataTable;
        }
        
        /// <summary>
        /// Sets the size of all mail merged images to one defined width and height
        /// </summary>
        private static class MergedImageResizer implements IFieldMergingCallback {
            public MergedImageResizer(final double imageWidth, final double imageHeight, final int unit) {
                mImageWidth = imageWidth;
                mImageHeight = imageHeight;
                mUnit = unit;
            }
        
            public void fieldMerging(final FieldMergingArgs args) {
                throw new UnsupportedOperationException();
            }
        
            public void imageFieldMerging(final ImageFieldMergingArgs args) {
                args.setImageFileName(args.getFieldValue().toString());
                args.setImageWidth(new MergeFieldImageDimension(mImageWidth, mUnit));
                args.setImageHeight(new MergeFieldImageDimension(mImageHeight, mUnit));
        
                Assert.assertEquals(mImageWidth, args.getImageWidth().getValue());
                Assert.assertEquals(mUnit, args.getImageWidth().getUnit());
                Assert.assertEquals(mImageHeight, args.getImageHeight().getValue());
                Assert.assertEquals(mUnit, args.getImageHeight().getUnit());
            }
        
            private double mImageWidth;
            private double mImageHeight;
            private int mUnit;
        }
      • getImageHeight/setImageHeight

        public MergeFieldImageDimension getImageHeight() / public void setImageHeight(MergeFieldImageDimension value)
        
        Specifies the image height for the image to insert into the document.

        The value of this property initially comes from the corresponding MERGEFIELD's code, contained in the template document. To override the initial value, you should assign an instance of MergeFieldImageDimension class to this property or set the properties for the instance of MergeFieldImageDimension class, returned by this property.

        To indicate that the original value of the image height should be applied, you should assign the null value to this property or set the MergeFieldImageDimension.Value property for the instance of MergeFieldImageDimension class, returned by this property, to a negative value.

        Example:

        Shows how to set the dimensions of merged images.
        @Test
        public void mergeFieldImageDimension() throws Exception {
            Document doc = new Document();
        
            // Insert a merge field where images will be placed during the mail merge
            DocumentBuilder builder = new DocumentBuilder(doc);
            builder.insertField("MERGEFIELD Image:ImageColumn");
        
            // Create a data table for the mail merge
            // The name of the column that contains our image filenames needs to match the name of our merge field
            DataTable dataTable = createDataTable("Images", "ImageColumn",
                    new String[]
                            {
                                    getImageDir() + "Aspose.Words.gif",
                                    getImageDir() + "Watermark.png",
                                    getImageDir() + "dotnet-logo.png"
                            });
        
            doc.getMailMerge().setFieldMergingCallback(new MergedImageResizer(450.0, 200.0, MergeFieldImageDimensionUnit.POINT));
            doc.getMailMerge().execute(dataTable);
        
            doc.updateFields();
            doc.save(getArtifactsDir() + "Field.MergeFieldImageDimension.docx");
        }
        
        /// <summary>
        /// Creates a data table with a single column
        /// </summary>
        private DataTable createDataTable(final String tableName, final String columnName, final String[] columnContents) {
            DataTable dataTable = new DataTable(tableName);
            dataTable.getColumns().add(new DataColumn(columnName));
        
            for (String s : columnContents) {
                DataRow dataRow = dataTable.newRow();
                dataRow.set(0, s);
                dataTable.getRows().add(dataRow);
            }
        
            return dataTable;
        }
        
        /// <summary>
        /// Sets the size of all mail merged images to one defined width and height
        /// </summary>
        private static class MergedImageResizer implements IFieldMergingCallback {
            public MergedImageResizer(final double imageWidth, final double imageHeight, final int unit) {
                mImageWidth = imageWidth;
                mImageHeight = imageHeight;
                mUnit = unit;
            }
        
            public void fieldMerging(final FieldMergingArgs args) {
                throw new UnsupportedOperationException();
            }
        
            public void imageFieldMerging(final ImageFieldMergingArgs args) {
                args.setImageFileName(args.getFieldValue().toString());
                args.setImageWidth(new MergeFieldImageDimension(mImageWidth, mUnit));
                args.setImageHeight(new MergeFieldImageDimension(mImageHeight, mUnit));
        
                Assert.assertEquals(mImageWidth, args.getImageWidth().getValue());
                Assert.assertEquals(mUnit, args.getImageWidth().getUnit());
                Assert.assertEquals(mImageHeight, args.getImageHeight().getValue());
                Assert.assertEquals(mUnit, args.getImageHeight().getUnit());
            }
        
            private double mImageWidth;
            private double mImageHeight;
            private int mUnit;
        }
        See Also:
        MergeFieldImageDimension, MergeFieldImageDimensionUnit
      • getImageStream/setImageStream

        public java.io.InputStream getImageStream() / public void setImageStream(java.io.InputStream value)
        
        Specifies the stream for the mail merge engine to read an image from.

        Aspose.Words closes this stream after it merges the image into the document.

        Example:

        Shows how to insert images stored in a database BLOB field into a report.
        public void mailMergeImageFromBlob() throws Exception {
            Document doc = new Document(getMyDir() + "MailMerge.MergeImage.doc");
        
            // Set up the event handler for image fields.
            doc.getMailMerge().setFieldMergingCallback(new HandleMergeImageFieldFromBlob());
        
            // Loads the driver
            Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
        
            // Open the database connection.
            String connString = "jdbc:ucanaccess://" + getDatabaseDir() + "Northwind.mdb";
        
            // DSN-less DB connection.
            java.sql.Connection conn = java.sql.DriverManager.getConnection(connString, "Admin", "");
        
            // Create and execute a command.
            java.sql.Statement statement = conn.createStatement();
            java.sql.ResultSet resultSet = statement.executeQuery("SELECT * FROM Employees");
        
            DataTable table = new DataTable(resultSet, "Employees");
        
            // Perform mail merge.
            doc.getMailMerge().executeWithRegions(table);
        
            // Close the database.
            conn.close();
        
            doc.save(getArtifactsDir() + "MailMerge.MergeImage.doc");
        }
        
        private class HandleMergeImageFieldFromBlob implements IFieldMergingCallback {
            public void fieldMerging(final FieldMergingArgs args) {
                // Do nothing.
            }
        
            /**
             * This is called when mail merge engine encounters Image:XXX merge field in the document.
             * You have a chance to return an Image object, file name or a stream that contains the image.
             */
            public void imageFieldMerging(final ImageFieldMergingArgs e) {
                // The field value is a byte array, just cast it and create a stream on it.
                ByteArrayInputStream imageStream = new ByteArrayInputStream((byte[]) e.getFieldValue());
                // Now the mail merge engine will retrieve the image from the stream.
                e.setImageStream(imageStream);
            }
        }
      • getImageWidth/setImageWidth

        public MergeFieldImageDimension getImageWidth() / public void setImageWidth(MergeFieldImageDimension value)
        
        Specifies the image width for the image to insert into the document.

        The value of this property initially comes from the corresponding MERGEFIELD's code, contained in the template document. To override the initial value, you should assign an instance of MergeFieldImageDimension class to this property or set the properties for the instance of MergeFieldImageDimension class, returned by this property.

        To indicate that the original value of the image width should be applied, you should assign the null value to this property or set the MergeFieldImageDimension.Value property for the instance of MergeFieldImageDimension class, returned by this property, to a negative value.

        Example:

        Shows how to set the dimensions of merged images.
        @Test
        public void mergeFieldImageDimension() throws Exception {
            Document doc = new Document();
        
            // Insert a merge field where images will be placed during the mail merge
            DocumentBuilder builder = new DocumentBuilder(doc);
            builder.insertField("MERGEFIELD Image:ImageColumn");
        
            // Create a data table for the mail merge
            // The name of the column that contains our image filenames needs to match the name of our merge field
            DataTable dataTable = createDataTable("Images", "ImageColumn",
                    new String[]
                            {
                                    getImageDir() + "Aspose.Words.gif",
                                    getImageDir() + "Watermark.png",
                                    getImageDir() + "dotnet-logo.png"
                            });
        
            doc.getMailMerge().setFieldMergingCallback(new MergedImageResizer(450.0, 200.0, MergeFieldImageDimensionUnit.POINT));
            doc.getMailMerge().execute(dataTable);
        
            doc.updateFields();
            doc.save(getArtifactsDir() + "Field.MergeFieldImageDimension.docx");
        }
        
        /// <summary>
        /// Creates a data table with a single column
        /// </summary>
        private DataTable createDataTable(final String tableName, final String columnName, final String[] columnContents) {
            DataTable dataTable = new DataTable(tableName);
            dataTable.getColumns().add(new DataColumn(columnName));
        
            for (String s : columnContents) {
                DataRow dataRow = dataTable.newRow();
                dataRow.set(0, s);
                dataTable.getRows().add(dataRow);
            }
        
            return dataTable;
        }
        
        /// <summary>
        /// Sets the size of all mail merged images to one defined width and height
        /// </summary>
        private static class MergedImageResizer implements IFieldMergingCallback {
            public MergedImageResizer(final double imageWidth, final double imageHeight, final int unit) {
                mImageWidth = imageWidth;
                mImageHeight = imageHeight;
                mUnit = unit;
            }
        
            public void fieldMerging(final FieldMergingArgs args) {
                throw new UnsupportedOperationException();
            }
        
            public void imageFieldMerging(final ImageFieldMergingArgs args) {
                args.setImageFileName(args.getFieldValue().toString());
                args.setImageWidth(new MergeFieldImageDimension(mImageWidth, mUnit));
                args.setImageHeight(new MergeFieldImageDimension(mImageHeight, mUnit));
        
                Assert.assertEquals(mImageWidth, args.getImageWidth().getValue());
                Assert.assertEquals(mUnit, args.getImageWidth().getUnit());
                Assert.assertEquals(mImageHeight, args.getImageHeight().getValue());
                Assert.assertEquals(mUnit, args.getImageHeight().getUnit());
            }
        
            private double mImageWidth;
            private double mImageHeight;
            private int mUnit;
        }
        See Also:
        MergeFieldImageDimension, MergeFieldImageDimensionUnit
      • getRecordIndex

        public int getRecordIndex()
        
        Gets the zero based index of the record that is being merged.
      • getTableName

        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.