开发一个wpf应用程序,只需将图像插入到word文档中。每次打开word文档时,我都希望图片从服务器调用图像,例如(server.com/Images/image_to_be_insert.png) 我的代码如下:
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();
基本上我的代码是做什么的,下载图像然后将其添加到文档中。我想要做的是,我想要在打开word文档时从服务器加载图像。
答案 0 :(得分:5)
您可以使用不需要安装MS Office的新OpenXML SDK来实现此目的,而不是使用Office Interop库。
<强>要求强>
从Visual Studio安装OpenXML NuGet: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文档,该文档将在打开时从提供的URL加载Google徽标。
<强>参考强>
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?