簡體   English   中英

如何使用OpenXml將外部圖像添加到Word文檔?

[英]How can I add an external image to a word document using OpenXml?

我正在嘗試使用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<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文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM