Intro

WordTemplate can insert images from byte arrays or ADO.NET objects into your Word documents.


The AdventureWorks SQL query includes the ProductPhoto.ThumbNailPhoto field, which is a binary image stored in the database. By using special merge field syntax (click "View template" to see the template document and merge fields), you can import the image from the DataColumn into the document at runtime.

Code

   public void GenerateDocument()
        {
            //Retrieve the datatable with a a helper method
            DataTable dt = GetData();
            // A list of the mergefield names in the template file
            string[] fieldNames = { "ProductNumber", "ProductName", "ProductPrice", "ProductImage" };
 
            // Name of the template bookmark that marks the repeatblock
            string repeatBlockName = "ProductRow";
 
            WordTemplate wt = new WordTemplate();
 
            // Open the template document
            wt.Open(@"..\..\WordTemplateFiles\InsertImageTemplate.docx");
 
            // Set the repeat block by providing the data source,
             // a list of mergefield names in the proper order, and
             // the name of the repeat block bookmark
            
            wt.SetRepeatBlock(dt, repeatBlockName);
 
            // Call process() after setting the data source and/or repeat blocks
            wt.Process();
 
            //Save the output to the desired location
            wt.Save(@"..\..\WordOutputFiles\InsertImage_output.docx");
 
            return;
 
        }

 Downloads

 Template: InsertImageTemplate.docx

Output: InsertImage_output.docx