Search code examples
c#asp.net-mvcasposeaspose.words

How to display SQL Server database image base64 in Aspose Word Document


I am new in Aspose and I have the following issue:

I have images in a SQL Server 2008 database, stored as a Base64 strings. I would like to display them in a Word document using Aspose.

I have successfully exported the other data, but can't display the images. Can anyone help me please?

Thanks in advance for your support.

Here is my code:

private Document createDocs(Guid ? ID)
{
    Document doc = new Document(HostingEnvironment.MapPath("~/Content/Template.doc"));
    DataTable Order = ExecuteDataTable(inspID);

    if (!(Order == null))
    {
        doc.MailMerge.FieldMergingCallback = new HandleMergeImageFieldFromBlob();
        doc.MailMerge.ExecuteWithRegions(Order);
    }

    return doc;
}

public DataTable ExecuteDataTable(Guid? ID)
{
    var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyStringConnection"];

    SqlConnection Conn = new SqlConnection(connectionString.ConnectionString);

    try
    {
        Conn.Open();

        SqlCommand cmd = new SqlCommand("SELECT * FROM blahblah, Conn);
        cmd.Parameters.Add("@ID", SqlDbType.UniqueIdentifier).Value = ID;

        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.SelectCommand = cmd;

        DataTable table = new DataTable();
        da.Fill(table);

        return table;
    }
    finally
    {
        if (!(Conn == null))
        {
            Conn.Close();
        }
    }
}

private void SendToBrowser (Document doc, string outputFormat, Page page)
{
    MemoryStream stream = new MemoryStream();
    doc.Save(stream, SaveFormat.Doc);

    page.Response.Clear();
    page.Response.ClearHeaders();
    page.Response.ClearContent();
    page.Response.ContentType = "application/doc";
    page.Response.AddHeader("content-disposition", "attachment; filename=base_file.doc");

    byte[] bytes = stream.GetBuffer();

    page.Response.BinaryWrite(bytes);
    page.Response.End();
}

public class HandleMergeImageFieldFromBlob : IFieldMergingCallback
{
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // Do nothing.
    }

    /// <summary>
    /// 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.
    /// </summary>
    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        // The field value is a byte array, just cast it and create a stream on it.
        var imageStream = new MemoryStream((byte[])e.FieldValue);

        // Now the mail merge engine will retrieve the image from the stream.
        e.ImageStream = imageStream;
    }
}

Solution

  • To insert an image mail merge field into a document in Word, select Insert/Field command, then select MergeField and type Image:MyFieldName. Following code example shows how perform mail merge operation with Base64 image. Please check the modified code of IFieldMergingCallback.ImageFieldMerging.

    public void mailmerge()
    {
        string base64String;
        using (Image image = Image.FromFile(MyDir + @"image.png"))
        {
            using (MemoryStream m = new MemoryStream())
            {
                image.Save(m, image.RawFormat);
                byte[] imageBytes = m.ToArray();
    
                // Convert byte[] to Base64 String
                base64String = Convert.ToBase64String(imageBytes);
            }
        }
    
        DataTable dt = new DataTable();
        dt.Columns.Add("ImageData", typeof(string));
    
        DataRow row1 = dt.NewRow();
        row1["ImageData"] = base64String;
        dt.Rows.Add(row1);
    
        Document doc = new Document(MyDir + "in.docx");
        doc.MailMerge.FieldMergingCallback = new HandleMergeImageFieldFromBlob();
        doc.MailMerge.Execute(dt);
        doc.Save(MyDir + "Out.docx");
    }
    
    public class HandleMergeImageFieldFromBlob : IFieldMergingCallback
    {
        void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
        {
            // Do nothing.
        }
    
        /// <summary>
        /// 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.
        /// </summary>
        void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
        {
            var imageStream = new MemoryStream((byte[])Convert.FromBase64String(e.FieldValue.ToString()));
    
            // Now the mail merge engine will retrieve the image from the stream.
            e.ImageStream = imageStream;
        }
    }
    

    I work with Aspose as Developer evangelist.