如何使用OpenXml将外部图像添加到word文档?
问题描述:
我正在尝试使用C#和Open XML将URL中的图像插入到文档中。图像可能会改变,所以我不想下载它,我希望它仍然是一个外部参考。如何使用OpenXml将外部图像添加到word文档?
我找到了几个例子是这样一个让我添加本地图片:
http://msdn.microsoft.com/en-us/library/bb497430.aspx
我怎样才能适应,要采取一个URI?还是有另一种方法?
答
,可以将外部图像的word文档通过快速零件字段添加。 有关说明,请参阅superuser上的以下答案。
为了实现所描述的步骤,程序,你必须 使用外部releationship包括从URL的图像。
下面是完成此步骤:
- 创建图片类的一个实例。
- 添加一个形状来指定图片的样式(宽度/高度)。
- 使用ImageData类指定外部关联的ID。
- 在外部文档部分添加一个外部索引。给外部 分辨率与步骤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<Paragraph>().FirstOrDefault();
paragraph.Append(run);
newDoc.MainDocumentPart.AddExternalRelationship(
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
new System.Uri("<url to your picture>", System.UriKind.Absolute), "rId56");
}
在上面的代码中,我省略了定义形状类型的代码。我建议你使用一个 工具像OpenXML SDK productivity tool 检查Word文档与外部releationship到的图像。