如何使用OpenXml将外部图像添加到Word文档? [英] How can I add an external image to a word document using OpenXml?

查看:123
本文介绍了如何使用OpenXml将外部图像添加到Word文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C#和Open XML将url中的图像插入到文档中.图片可能会更改,所以我不想下载它,我希望它保留为外部参考.

I am trying to use C# and Open XML to insert an image from a url into a doc. The image may change so I don't want to download it, I want it to remain an external reference.

我发现了几个类似的示例,这些示例使我可以添加本地图像:

I've found several examples like this one that allow me to add a local image:

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

我该如何调整它以获取URI?还是完全有另一种方法?

How can I adapt that to take a URI? Or is there another approach altogether?

推荐答案

您可以通过快速零件字段将外部图像添加到Word文档中. 有关说明,请参见

You can add an external image to an word document via a quick parts field. For a description please see the following answer on superuser.

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

To realize the described steps programmatically you have to use an external releationship to include an image from an URL.

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

Here are the steps to accomplish this:

  1. 创建Picture类的实例.
  2. 添加形状以指定图片的样式(宽度/高度).
  3. 使用ImageData类指定外部版本的ID.
  4. 在主文档部分中添加外部版本.给外部 释放与您在步骤3中指定的ID相同.
  1. Create an instance of the Picture class.
  2. Add a Shape to specify the style of the picture (width/height).
  3. Use the ImageData class to specify the ID of the external releationship.
  4. Add an external releationship to the main document part. Give the external releationship the same ID you specified in step 3.

以下代码仅实现上述步骤.图像已添加到 Word文档的第一段.

The following code just implements the steps described above. The image is added to the first paragraph in the word document.

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生产力工具之类的工具 检查与文档有外部关联的Word文档.

In the code above I've omitted the code to define the shape type. I advise you to use a tool like the OpenXML SDK productivity tool to inspect a word document with an external releationship to an image.

这篇关于如何使用OpenXml将外部图像添加到Word文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆