Enhancing your Word Document with Images Using OfficeWriter

One of the questions that comes up frequently when talking with customers is how can they get their images into their Word document with OfficeWriter? Depending on how you are using OfficeWriter and making your Word documents, there are a few ways to do this. The following outline several of these methods and cases in which to use them.

1. Design your document in Word with images

This is the easiest way to get images into your document. Since OfficeWriter can use the Word file you have already created and allow you to enhance it with data from a database, you can get all of the design functionality of Word with the enhanced capabilities of OfficeWriter. This method is commonly used when designing a document that uses your company logo, for example.

2. Dynamically insert images into a document

Another option is to design your document in Word, but leave a place holder for a dynamically loaded image. (A quick overview on how to do this can be found here.) This method is great when the document is structured the same each time it is run and you want to keep your company logo static, but use different department logos.

3. Design your report with images stored in a database

You can use one of two methods to directly insert images into a Word template from an image column: the placeholder method or the the image modifier method.  For example, in MS SQL Server, there is a column type “varbinary” used just for that purpose. This method is perfect for creating an employee directory containing the employee’s picture along with their contact information, or for a product catalog, showing the product alongside the product details. (For further details on how to to design your report with images stored in a database, please see our documentation on inserting an image.)

4. Design your report with images referenced by PATH in a database

This is the more complicated case of the bunch. Unlike the previous instances where you were obtaining your images directly from a database, this process involves accessing your images stored in another location, such as a network share. This means that in order to get your images into the Word document, we will have to load the image in code using the file path in the database. Details outlined below:

Step 0. Overview of the process

OfficeWriter is designed to automatically load images from a database into a Word document. That means the solution to utilizing OfficeWriter is to bridge the gap from a file reference string into a byte[]. Please refer to our Hello, World! documentation for getting started on creating a Word template file. The project below will also be using MS SQL Server connections built into .NET, and the SQL statements will be taken from the AdventureWorks 2008 R2 database, which can be downloaded from Microsoft.

Step 1. Get the Data

First, we have to load the data into a .NET DataTable from a database. This uses the AdventureWorks database from Microsoft. In this case, the database already contains the images in the column “LargePhoto”, which is of type “varbinary”.

private DataTable getProductData()
{
    var connString = @"Server=localhost\SQL2008R2;database=AdventureWorks2008R2;Trusted_Connection=true;";
    var sql = @"SELECT * FROM Production.vProductAndDescription AS Prod " +
                "INNER JOIN Production.ProductProductPhoto AS ProdPhotos ON Prod.ProductID = ProdPhotos.ProductID " +
                "INNER JOIN Production.ProductPhoto AS ProdPhoto ON Prodphotos.ProductPhotoID = ProdPhoto.ProductPhotoID";

    // Retrieve the data
    var conn = new SqlConnection(connString);
    conn.Open();

    DataTable products = new DataTable();
    SqlCommand cmd = new SqlCommand(sql, conn);
    new SqlDataAdapter(cmd).Fill(products);

    conn.Close();

    return products;
}

Step 2. Load the images

Instead of using the existing LargePhoto field, I can use the “LargePhotoFieldName” column to load the images via code. I will call the new column “LargePhotoDynamic”.

private void loadImages(DataTable products)
{
    // Load the images from the file path
    var largeImageColumn = products.Columns.Add("LargePhotoDynamic", typeof(byte[])); // create a new DataColumn in the DataTable
    var unavailableFileName = Page.MapPath("~/images/no_image_available_large.gif"); // in case the file can't be found use this image

    foreach (DataRow row in products.Rows)
    {
        var fileName = Page.MapPath("~/images/" + row["LargePhotoFileName"].ToString());

        row[largeImageColumn] = getPicture(fileName, unavailableFileName);
    }
}

In addition to the above, a small helper method for loading a file:

    private byte[] getPicture(String fileName, String unavailableFileName)
    {
        FileStream fs = null;
        byte[] data = null;
        try
        {
            if (File.Exists(fileName))
                fs = File.OpenRead(fileName);
            else
                fs = File.OpenRead(unavailableFileName);
            data = new byte[fs.Length];
            fs.Read(data, 0, data.Length);
        }
        finally
        {
            if (fs != null)
                fs.Close();
        }
        return data;
    }

Step 3. Generate the Document

Now that we have loaded the image dynamically and have placed a merge field in our document, we are ready to process the document.

private void generateDocument(DataTable products)
{
    // Generate the Product Catalog in Word using OfficeWriter
    var wt = new WordTemplate();
    wt.Open(Page.MapPath(@"~\templates\EmployeeDirectory_Template.docx")); // open the file that has the merge fields

    wt.SetRepeatBlock(products, "Product"); // set the data for processing in a repeat block

    wt.Process(); // process the document
    wt.Save(Page.Response); // download to the user
}

More Information

Aside from working with images to enhance your Word documents and reports, there are many other ways OfficeWriter can automate document and spreadsheet creation. Curious to learn more? View our OfficeWriter demo center.

Related posts: