Intro
Excerpt |
---|
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
Code Block |
---|
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;
}
//Gets all data for product catalog including pictures.
private DataTable GetData()
{
DataTable dt = GetProductData(@"..\..\WordData\InsertImageData.csv");
dt.Columns.Add("ProductImage", typeof(byte[]));
for (int k = 0; k < dt.Rows.Count; k++)
{
string imageName = dt.Rows[k].ItemArray[3].ToString();
dt.Rows[k][4] = GetPictures(imageName);
}
return dt;
}
// Get a DataTable of product data excluding photos
private DataTable GetProductData(string csvFileName)
{
DataTable dt = new DataTable();
using (GenericParserAdapter parser = new GenericParserAdapter(csvFileName))
{
parser.ColumnDelimiter = ',';
parser.FirstRowHasHeader = true;
dt = parser.GetDataTable();
}
return dt;
}
private byte[] GetPictures(string picName)
{
//Opens image and returns byte array
byte[] imageArray = File.ReadAllBytes(@"..\..\WordImages\InsertImageDemoImages\" + picName);
//ReadAllBytes() is able to find the files.
return imageArray;
}
|
...