当前位置: 移动技术网 > IT编程>开发语言>c# > C#采用OpenXml给word里面插入图片

C#采用OpenXml给word里面插入图片

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了c#采用openxml给word里面插入图片的方法,分享给大家供大家参考。具体分析如下:

首先需要指出的是在msdn官网有完整的openxml教程,虽然是全英文的不过还是很有帮助的。

注,原来摘抄代码里面没有模板,在copy过来发现插入word中的图片大小不一样,我们如何查找设置图片大小带代码的那一块,建议自己用在word里面插入一张图片,通过openxml tools 反编译出c#代码,然后改变图片的大小,再次反编译。

使用byeond compare 【 下载地址】比较c#代码,就会发现是因为new dw.extent() { cx = 990000l, cy = 792000l}  是因为这段设置造成的。以后其实很多地方都可以借助openxml tools反编译来进行对比。查看设置样式的属性位置。

msdn openxml学习链接:  。感兴趣的朋友可以查看一下。

示例代码如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;
using documentformat.openxml;
using documentformat.openxml.packaging;
using documentformat.openxml.wordprocessing;
using system.io;
using dw = documentformat.openxml.drawing.wordprocessing;
using pic = documentformat.openxml.drawing.pictures;
using a = documentformat.openxml.drawing;

namespace addpictureintoword
{
  public class program
  {
    public static void main(string[] args)
    {
      string picpath = "u=639047729,3872612606&fm=11&gp=0.bmp";
      string filepath = "test.docx";
      addpictureintoword(filepath, picpath);
    }

    public static void addpictureintoword(string filepath, string picturepath)
    {
      using (wordprocessingdocument doc = wordprocessingdocument.open(filepath, true))
      {
        string pictype = picturepath.split('.').last();
        imageparttype imageparttype;
        imagepart imagepart = null;
        // 通过后缀名判断图片类型, true 表示忽视大小写
        if (enum.tryparse<imageparttype>(pictype, true, out imageparttype))
        {
          imagepart = doc.maindocumentpart.addimagepart(imageparttype);
        }

        imagepart.feeddata(file.open(picturepath, filemode.open)); // 读取图片二进制流
        addimagetobody(doc, doc.maindocumentpart.getidofpart(imagepart));
      }
    }

    // 摘抄自http://msdn.microsoft.com/en-us/library/office/bb497430(v=office.15).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-5    
   private static void addimagetobody(wordprocessingdocument worddoc, string relationshipid)
    {
      // define the reference of the image.
      var element =
         new drawing(
           new dw.inline(
             new dw.extent() { cx = 990000l, cy = 792000l }, // 调节图片大小
             new dw.effectextent()
             {
               leftedge = 0l,
               topedge = 0l,
               rightedge = 0l,
               bottomedge = 0l
             },
             new dw.docproperties()
             {
               id = (uint32value)1u,
               name = "picture 1"
             },
             new dw.nonvisualgraphicframedrawingproperties(
               new a.graphicframelocks() { nochangeaspect = true }),
             new a.graphic(
               new a.graphicdata(
                 new pic.picture(
                   new pic.nonvisualpictureproperties(
                     new pic.nonvisualdrawingproperties()
                     {
                       id = (uint32value)0u,
                       name = "new bitmap image.jpg"
                     },
                     new pic.nonvisualpicturedrawingproperties()),
                   new pic.blipfill(
                     new a.blip(
                       new a.blipextensionlist(
                         new a.blipextension()
                         {
                           uri =
                            "{28a0092b-c50c-407e-a947-70e740481c1c}"
                         })
                     )
                     {
                       embed = relationshipid,
                       compressionstate =
                       a.blipcompressionvalues.print
                     },
                     new a.stretch(
                       new a.fillrectangle())),
                   new pic.shapeproperties(
                     new a.transform2d(
                       new a.offset() { x = 0l, y = 0l },
                       new a.extents() { cx = 990000l, cy = 792000l }), //与上面的对准
                     new a.presetgeometry(
                       new a.adjustvaluelist()
                     ) { preset = a.shapetypevalues.rectangle }))
               ) { uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
           )
           {
             distancefromtop = (uint32value)0u,
             distancefrombottom = (uint32value)0u,
             distancefromleft = (uint32value)0u,
             distancefromright = (uint32value)0u,
             editid = "50d07946"
           });

      // append the reference to body, the element should be in a run.
      worddoc.maindocumentpart.document.body.appendchild(new paragraph(new run(element)));
    }
  }
}

本文示例运行效果如下图所示:

希望本文所述对大家的c#程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网