Download image in text document

Im developing a wpf application that simply inserts an image into a word document. Every time a word document is opened, I want the image to call the image from the server, for example (server.com/Images/image_to_be_insert.png) My code looks like this:

 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 upload the image and then add it to the document. What I want to do is that I want the image to be downloaded from the server whenever a text document is opened.

+4
source share
1 answer

Instead of using Office Interop libraries, you can achieve this using the new OpenXML SDK, which does not require MS Office to work.

Requirements

OpenGML NuGet Visual Studio: DocumentFormat.OpenXml

:

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

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();
}

Word, Google URL- .

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

Word OpenXml?

+4

Source: https://habr.com/ru/post/1689555/


All Articles