4

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.

Isma
  • 14,604
  • 5
  • 37
  • 51
Batman
  • 378
  • 1
  • 3
  • 11

1 Answers1

5

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?

Isma
  • 14,604
  • 5
  • 37
  • 51
  • what if i want to add a picture to an existing document. i tried to change the WordprocessingDocument.Create to WordprocessingDocument.open(path,true) but it exited with (DocumentFormat.OpenXml.Packaging.OpenXmlPackageException: 'Only one instance of the type is allowed for this parent.') exception – sam saleh Nov 21 '17 at 13:30
  • You should be able to open it as you did, you also need to read the document part instead of creating it https://msdn.microsoft.com/en-us/library/office/ff478255.aspx – Isma Nov 21 '17 at 14:00