如何使用OpenXml将外部图像添加到Word文档?

我正在尝试使用C#和Open XML将图像从url插入到doc中。 图像可能会更改,因此我不想下载它,我希望它保留为外部参考。

我发现了几个像这样的例子,允许我添加一个本地图像:

http://msdn.microsoft.com/en-us/library/bb497430.aspx

我如何调整它以获取URI? 或者还有另一种方法吗?

您可以通过快速部件字段将外部图像添加到word文档。 有关说明,请在超级用户上查看以下答案。

要以编程方式实现所描述的步骤,您必须使用外部关联来包含URL中的图像。

以下是完成此操作的步骤:

  1. 创建Picture类的实例。
  2. 添加形状以指定图片的样式(宽度/高度)。
  3. 使用ImageData类指定外部关联的ID。
  4. 在主文档部分添加外部关联。 为外部关联提供您在步骤3中指定的相同ID。

以下代码仅实现上述步骤。 图像将添加到word文档的第一个段落中。

using (WordprocessingDocument newDoc = WordprocessingDocument.Open(@"c:\temp\external_img.docx", true)) { var run = new Run(); var picture = new Picture(); var shape = new Shape() { Id = "_x0000_i1025", Style = "width:453.5pt;height:270.8pt" }; var imageData = new ImageData() { RelationshipId = "rId56" }; shape.Append(imageData); picture.Append(shape); run.Append(picture); var paragraph = newdoc.MainDocumentPart.Document.Body.Elements().FirstOrDefault(); paragraph.Append(run); newDoc.MainDocumentPart.AddExternalRelationship( "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", new System.Uri("", System.UriKind.Absolute), "rId56"); } 

在上面的代码中,我省略了定义形状类型的代码。 我建议您使用类似OpenXML SDK生产力工具的工具来检查与图像外部关联的word文档。