Search code examples
c#office-interopopenxml-sdk

Loading an online image in a word document


Im developing a wpf app that simply inserts an image to a word document. Each time the word document is open i want the picture to call the image from a server, for example (server.com/Images/image_to_be_insert.png) My code is as follow:

 Application application = new Application();
 Document doc = application.Documents.Open(file);

 var img = doc.Application.Selection.InlineShapes.AddPicture("server.com/Images/img.png");
 img.Height = 20;
 img.Width = 20;

 document.Save();
 document.Close();

Basically what my code does is, download the image then add it to the document. What i want to do is that i want the image to be loaded from the server whenever the word document is opened.


Solution

  • Instead of using the Office Interop libraries, you could achieve this using the new OpenXML SDK which does not require MS Office to be installed in order to work.

    Requirements

    Install the OpenXML NuGet from Visual Studio: DocumentFormat.OpenXml

    Add the required namespaces:

    using DocumentFormat.OpenXml;
    using DocumentFormat.OpenXml.Packaging;
    using DocumentFormat.OpenXml.Vml;
    using DocumentFormat.OpenXml.Wordprocessing;
    

    The code

    using (WordprocessingDocument package = WordprocessingDocument.Create(@"c:/temp/img.docx", WordprocessingDocumentType.Document))
    {
        package.AddMainDocumentPart();
    
        var picture = new Picture();
        var shape = new Shape() { Style="width: 272px; height: 92px" };
        var imageData = new ImageData() { RelationshipId = "rId1" };
        shape.Append(imageData);
        picture.Append(shape);
    
        package.MainDocumentPart.Document = new Document(
            new Body(
                new Paragraph(
                    new Run(picture))));
    
                package.MainDocumentPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
       new System.Uri("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png", System.UriKind.Absolute), "rId1");
    
        package.MainDocumentPart.Document.Save();
    }
    

    This will create a new Word document that will load the Google logo from the provided URL when open it.

    References

    https://msdn.microsoft.com/en-us/library/dd440953(v=office.12).aspx

    How can I add an external image to a word document using OpenXml?