使用OpenXML将图像添加到word文档

时间:2017-11-23 10:55:37

标签: c# openxml

我开发了一个应用程序,它应该将图像添加到word文档中。它从word文档中获取副本并将图片添加到副本中。我试图添加文本,它工作得很好,但通过添加图像文档word想要打开一个文件,通过给出一个错误(文件“名称”无法打开,因为内容有问题。)

我的代码如下所示:

File.Copy(file, newFile, true);
     WordprocessingDocument wordFile = WordprocessingDocument.Open(newFile, true);
     Body body = wordFile.MainDocumentPart.Document.Body;

     var picture = new Picture();
     var shape = new Shape() { Style = "width: 20px; height: 20px" };
     var imageData = new ImageData() { RelationshipId = "img" };

     shape.Append(imageData);
     picture.Append(shape);
     wordFile.MainDocumentPart.AddExternalRelationship(
          "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
           new Uri(link_of_image, UriKind.Absolute),"img");

     Paragraph para = body.AppendChild(new Paragraph());
     Run run = para.AppendChild(new Run());
     run.AppendChild(new Picture(picture));

     wordFile.Close();

可能出现什么问题?

1 个答案:

答案 0 :(得分:1)

此解决方案用于在本地驱动器上添加图像,但我不知道如何从在线服务器添加图像 解: 首先添加这些程序集:

WORD

然后打开文件

using System.IO;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using A = DocumentFormat.OpenXml.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;

然后定义图像的引用并将引用附加到正文。

        WordprocessingDocument wordprocessingDocument =
        WordprocessingDocument.Open(newFile, true);

        MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
        ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);

        using (FileStream stream = new FileStream(@"C:\Users\User\Desktop\img.PNG", FileMode.Open))
        {
            imagePart.FeedData(stream);
        }
        AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart));

        wordprocessingDocument.Close();

参考https://msdn.microsoft.com/en-us/library/office/bb497430.aspx