C# word中图片复制到另一个新的word中

本文介绍了一种使用C#和Microsoft Office Interop Word库从Word文档中提取并保存所有内联图片的方法。通过遍历文档中的每个内联形状元素,判断其类型为图片后进行复制、粘贴操作,最终将图片保存到指定目录。
先引用组件Office

using WordMethod = Microsoft.Office.Interop.Word;


private void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog OFD = new OpenFileDialog();
    if ( DialogResult.OK != OFD.ShowDialog())
    {
        return;
    }

    WordMethod.Application app = new Microsoft.Office.Interop.Word.Application();
    WordMethod.Document doc = null;
    WordMethod.Document newDoc = null;

    object unKnown = Type.Missing;
    app.Visible = true;

    object docPath = OFD.FileName;
    doc = app.Documents.Open(ref docPath, 
                             ref unKnown, ref unKnown, ref unKnown, ref unKnown, ref unKnown, 
                             ref unKnown, ref unKnown, ref unKnown, ref unKnown, ref unKnown,
                             ref unKnown, ref unKnown, ref unKnown, ref unKnown, ref unKnown  );

     newDoc = app.Documents.Add(ref unKnown, ref unKnown, ref unKnown);

     if (doc != null)
     {
         string text = doc.Content.Text.Trim();

         //Console.WriteLine(text);
                    //File.WriteAllText(System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\1.doc", text, Encoding.Default);//导出全部文本内容
                
         int i = 0;
         foreach (WordMethod.InlineShape item in doc.InlineShapes)
         {
             if (item.Type == WordMethod.WdInlineShapeType.wdInlineShapePicture) //判断是图片
             {
                 item.Select();
                 app.Selection.Copy();//复制模式
                 Image image = Clipboard.GetImage();
                 if (image != null)
                 {
                     Bitmap bm = new Bitmap(image);
                            bm.Save(System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Sources\\" + i.ToString() + ".jpg");
                     app.Selection.EndKey(ref unKnown, ref unKnown);
                     object range = newDoc.Paragraphs.Last.Range;    //
                     object linkToFile = false;
                     object saveWithDocument = true;
                           newDoc.InlineShapes.AddPicture(System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Sources\\" + i.ToString() + ".jpg", ref linkToFile, ref saveWithDocument, ref range);
                     app.Selection.ParagraphFormat.Alignment = WordMethod.WdParagraphAlignment.wdAlignParagraphCenter;                           
                     i++;
                  }
               }
            }
            doc.Close(ref unKnown, ref unKnown, ref unKnown);
        }
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值