Home > .NET, Office Open XML > Using Word automation to embed linked images

Using Word automation to embed linked images

In my current project I generate reports by creating Word 2007 files. You know the file format consisting of zipped XML files? This project is web-based and the users can enter information through rich text editors. These rich text editors produce html which in turn is inserted in the reports (with the altChunk tag for those who are interested) . All this can be done without any Word automation which is good (having Office on the server is not supported by Microsoft).

Before today, only textual content with formatting could be entered through these text editors. But today I added the ability to upload and insert images as well. And here the problem started. When generating the reports the images would only be linked to and not embedded inside which is not what I wanted…

So how did I solve this? I cheated! Before today we were using Word automation for converting Word 2007 documents to Word 97 (using a web service) for backwards compatability. I decided to try and modify this web service to automatically embed linked images. I found an article by Rick Strahl which led me to the solution. Besides the things the article mentionend I also needed to perform the same thing with InlineShapes. Here comes the code:

private void EmbedLinkedImages(Document doc)
{
    foreach (InlineShape shape in doc.InlineShapes)
    {
        if (shape.LinkFormat != null)
        {
            shape.LinkFormat.SavePictureWithDocument = true;
            shape.LinkFormat.BreakLink();
            doc.UndoClear();
        }
    }

    foreach (Field field in doc.Fields)
    {
        if (field.Type == WdFieldType.wdFieldIncludePicture)
        {
            field.LinkFormat.SavePictureWithDocument = true;
            field.LinkFormat.BreakLink();
            doc.UndoClear();
        }
    }

    foreach (Shape shape in doc.Shapes)
    {
        if (shape.LinkFormat != null)
        {
            shape.LinkFormat.SavePictureWithDocument = true;
            shape.LinkFormat.BreakLink();
            doc.UndoClear();
        }
    }
}

The code is mostly self-explanatory except the doc.UndoClear(). It is there to clear the undo buffer in Word which otherwise can consume a lot of memory.

Categories: .NET, Office Open XML Tags:
  1. booyah79
    September 7th, 2008 at 21:26 | #1

    Is there a way to embed images added through altChunk HTML without using Word automation? I also have users adding rich content via a rich text editor on a website (w/ images) but my server doesn’t support Word automation. I can create docx files using the HTML – but, as you’ve stated, images are created in the document as hyperlinks.

  2. November 17th, 2008 at 00:59 | #2

    Sorry for the long time of not replying. I don’t think it is possibly to do it without Word automation. If you find a way, please let me know.

  1. No trackbacks yet.