C# word中圖片複製到另一個新的word中
阿新 • • 發佈:2018-12-12
先引用元件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); } } }