Home     Products      Support      Corporate     Sign In 

Support Knowledge Base, Article 1251

Product
WordWriter
Version
3.8.1
Title
HOW TO: Insert images from the internet into a Word document
Problem
How do I insert images from the internet into a Word document using their URLs?
Solution
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.

Microsoft's HttpWebRequest and WebReponse objects in the System.Net namespace allow you to send an HTTP request and receive an HTTP Response programmatically and return the Response as a stream. The HttpWebRequest and WebResponse objects are described here in Microsoft's MSDN documentation:

HttpWebRequest
WebResponse

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:

IIS 5.0: Error message "HTTP/1.1 407 proxy authentication required

Example:

[C#] [VB.NET]  
     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();
    }

Created : 10/23/2007 10:55:48 AM (last modified : 10/23/2007 10:55:48 AM)

Rate this article!

 
Comments



Copyright 2006 © SoftArtisans, Inc. All Rights Reserved.

Site Map     |     Privacy Policy     |     Contact Us