C# 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);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35106907/article/details/84582588