发布时间:2018-08-13编辑:佚名阅读(3466)
private Bitmap[] WordtoImage(string filePath) { string tmpFilePath = AppDomain.CurrentDomain.BaseDirectory + "\\" + Path.GetFileName(filePath) + ".tmp"; File.Copy(filePath, tmpFilePath,true); List<Bitmap> imageLst = new List<Bitmap>(); MSWord.Application wordApplicationClass = new MSWord.Application(); wordApplicationClass.Visible = false; object missing = System.Reflection.Missing.Value; try { object filePathObject = tmpFilePath; MSWord.Document document = wordApplicationClass.Documents.Open(ref filePathObject, ref missing, false, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); bool finished = false; while (!finished) { document.Content.CopyAsPicture(); IDataObject data = Clipboard.GetDataObject(); if (data.GetDataPresent(DataFormats.MetafilePict)) { Metafile metafile = MetafileHelper.GetEnhMetafileOnClipboard(IntPtr.Zero); //从粘贴板获取数据 Bitmap bm = new Bitmap(metafile.Width, metafile.Height); using (Graphics g = Graphics.FromImage(bm)) { g.Clear(Color.White); g.DrawImage(metafile, 0, 0, bm.Width, bm.Height); } imageLst.Add(bm); Clipboard.Clear(); } object Next = MSWord.WdGoToItem.wdGoToPage; object First = MSWord.WdGoToDirection.wdGoToFirst; object startIndex = "1"; document.ActiveWindow.Selection.GoTo(ref Next, ref First, ref missing, ref startIndex); MSWord.Range start = document.ActiveWindow.Selection.Paragraphs[1].Range; MSWord.Range end = start.GoToNext(MSWord.WdGoToItem.wdGoToPage); finished = (start.Start == end.Start); if (finished) { end.Start = document.Content.End; } object oStart = start.Start; object oEnd = end.Start; document.Range(ref oStart, ref oEnd).Delete(ref missing, ref missing); } document.Close(ref missing, ref missing, ref missing); Marshal.ReleaseComObject(document); return imageLst.ToArray(); } catch (Exception ex) { MessageBox.Show(ex.Message); return null; } finally { wordApplicationClass.Quit(ref missing, ref missing, ref missing); Marshal.ReleaseComObject(wordApplicationClass); File.Delete(tmpFilePath); } }
public class MetafileHelper { [DllImport("user32.dll")] static extern bool OpenClipboard(IntPtr hWndNewOwner); [DllImport("user32.dll")] static extern bool CloseClipboard(); private const int CF_ENHMETAFILE = 14; [DllImport("user32.dll")] private static extern int IsClipboardFormatAvailable(int wFormat); [DllImport("user32.dll")] private static extern IntPtr GetClipboardData(int wFormat); static public Metafile GetEnhMetafileOnClipboard(IntPtr hWnd) { Metafile meta = null; if (OpenClipboard(hWnd)) { try { if (IsClipboardFormatAvailable(CF_ENHMETAFILE) != 0) { IntPtr hEMF = GetClipboardData(CF_ENHMETAFILE); meta = new Metafile(hEMF, true); } } finally { CloseClipboard(); } } return meta; } }
关键字: C# word转图片
0人
1人
1人
0人