c# – 在word文档中加载在线图像
作者:互联网
我开发了一个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文档时从服务器加载图像.
解决方法:
您可以使用新的OpenXML SDK来实现此目的,而不需要使用Office Interop库,而不需要安装MS Office才能工作.
要求
从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?
标签:c,office-interop,openxml-sdk 来源: https://codeday.me/bug/20190607/1195683.html