Saturday, February 19, 2011

How can I embed images in an ASP.NET Generated Word File

Hi everyone!

I have a quite common problem, as I saw in the various user groups but could not find a suitable answer.

What I want to do is generate an ASP.NET page in my website which will have the option of being exported into Microsoft Word .doc format.

The method I have used is this:

Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=Test.doc");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/msword";

StringWriter sw = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(sw);
Page.RenderControl(htmlWrite);
Response.Write(sw.ToString());
Response.End();

However this eventhough it generates a word doc, the images are note embedded in the document, rather they are placed as links. I have looked for a way to do this, but have not found something that actually worked.

I would appreciate any help I can get, since this as "last minute" requirement (talk about typical)

Thanks

From stackoverflow
  • Short Answer: You need to provide absolute URLs for the source of the images in your page.

    Longer Answer:

    Microsoft Word will open an HTML document if you rename it with a *.doc extension. This is what the code that you provided is doing. In this case, the images are not embedded in the document like they would be if you created a document in actual Word format. If your images are using relative URLs then Word will not know where to look for them, hence the need for absolute URLs.

    NOTE: This means that anyone viewing the document without an internet connection will not see the images, as they are requested from the server every time the document is opened.

    A more elegant solution would be to create the document in the real Word format. A great library for this is Aspose.Words. Using this library you would be able to embed the images directly into the document so that they do not rely on the server.

    Nikos Steiakakis : It took a while to accept the answer, but I had been working on another project so long, so I couldn't accept it without trying it out first!
    AJ : Glad to hear that it was helpful... did you end up using a third party component or going with absolute urls? If you used a component, which one did you go with?
  • Thanks AJ for your answer.

    The problem is that we are developing a web application that is hosted in the customers premises each time. So the approach of absolute URLs might be a little tricky. We will most probably have to try a third party library after all.

    Thanks anyway!

  • I Also have the same problem. How I can embed the image in the doc from the ASP.net application? Any body know the answer.

0 comments:

Post a Comment