How to insert images from the internet into a Word document

Problem

The Element.InsertImageAfter() method in the WordApplication object can insert an image into a document from an image file location or a FileStream. It cannot insert an image from a URL as a string, however. In order to insert an image from a URL, you must first retrieve the image as a stream.

For more information about inserting images with WordTemplate please refer to our documentation.

Solution

Response programmatically and return the Response as a stream. The HttpWebRequest and WebResponse objects are described in Microsoft’s MSDN documentation.

In this example, the Word document is being filled with data using the WordTemplate object. Then, it is passed to the WordApplication object, where the the SearchMatch object is used to find all instances in the document of a string ending in an image file extension that is WordWriter-compatible (.jpg, .jpeg, .gif, .png, .bmp) using a Regular Expression. Then the .NET HttpWebResponse and WebResponse objects are used to retrieve the image as a stream. Finally, the images are inserted into the document.

Note: If you are using this code in a Web Application, you will need to pass the correct credentials to the proxy server or you will receive a 407 error. Microsoft has a support article addressing this issue located here.

Example


protected void InsertImagesFromURL()
{
//Create the Word Template object and open the template WordTemplate
wt = new WordTemplate(); wt.Open(Page.MapPath("templates/DatabaseSourceTest.doc"));


//Insert sample images into a template document
string[] data = new string[2] { "http://www.mbta.com/images/logo-mbta.gif", "http://www.purepage.com/sample/purepageimages/final_logo_bmp.Bmp" };
string[] names = new string[2] { "OrderID", "CustomerID" };


//Set the datasource for the template
wt.SetDataSource(data, names);
wt.Process();


//Open the template as a WordApplication Document for editing
WordApplication wa = new WordApplication();
Document doc = wa.Open(wt);


//Call the SearchAndReplaceWithImage method to search the document for
//image URLs and replace them with images
SearchAndReplaceWithImage(doc);


//Export the final document
wa.Save(doc, Page.Response, "output.doc", false);
}


public void SearchAndReplaceWithImage(Document doc)
{
//Search for all strings in the document ending in
//.jpg, .jpeg, .png, .bmp.
//These are all of the valid picture types that can be imported
//using WordWriter.
//Use regular expressions to perform the search efficiently.
SearchMatch[] searcherator = doc.Search(@"(?i).*jpe?g$|.*gif$|.*png$|.*bmp$");


//For every string that ends with an image extension, do this
for (int i = 0; i < searcherator.Length; i++)
{


//Select a match from the SearchMatch array
SearchMatch match = (SearchMatch)searcherator[i];


//Use the DownloadAndInsertImage method to retrieve the image as
//a stream stream and insert it into the document.
DownloadAndInsertImage(match);
}
}


public void DownloadAndInsertImage(SearchMatch match)
{


//Retrieve the URL as a string from the SearchMatch object
string strhttp = match.Element.Text;


//Send an HTTP request and get the image at the URL as an HTTP response
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(strhttp);
WebResponse myResp = myReq.GetResponse();


//Get a stream from the webresponse
Stream stream = myResp.GetResponseStream();


//Insert the image into the document and delete the URL string
match.Element.InsertImageAfter(stream);
match.Element.DeleteElement(); }

Related posts: