2017-11-20 10 views
4

Im Entwickeln einer WPF-App, die einfach ein Bild in ein Word-Dokument einfügt. Jedes Mal wenn das Word-Dokument geöffnet ist i das Bild will das Bild von einem Server nennen, zum Beispiel (server.com/Images/image_to_be_insert.png) Mein Code ist wie folgt:Ein Online-Bild in ein Word-Dokument laden

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

Im Grunde, was mein Code Das heißt, laden Sie das Bild herunter und fügen Sie es dem Dokument hinzu. Ich möchte, dass das Bild vom Server geladen wird, wenn das Word-Dokument geöffnet wird.

Antwort

4

Anstatt die Office Interop-Bibliotheken zu verwenden, können Sie dies mit dem neuen OpenXML-SDK erreichen, für das keine Installation von MS Office erforderlich ist.

Anforderungen

die OpenXML NuGet von Visual Studio installieren: DocumentFormat.OpenXml

Fügen Sie die erforderlichen Namespaces:

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

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

Dadurch wird ein neues Word-Dokument erstellt, das beim Öffnen das Google-Logo von der angegebenen URL lädt.

Referenzen

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?

+0

es für mich Dank gearbeitet. – Batman

+0

Was ist, wenn ich ein Bild zu einem vorhandenen Dokument hinzufügen möchte. Ich habe versucht, die WordprocessingDocument.Create in WordprocessingDocument.open (Pfad, true) zu ändern, aber es beendet mit (DocumentFormat.OpenXml.Packaging.OpenXmlPackageException: 'Nur eine Instanz des Typs ist für diese übergeordnete zulässig.') Ausnahme –

+0

Sie sollten In der Lage, es zu öffnen, wie Sie es taten, müssen Sie auch den Dokumentteil lesen, anstatt es https://msdn.microsoft.com/en-us/library/office/ff478255.aspx zu erstellen – Isma