Converting images from word document into bitmap object

落爺英雄遲暮 提交于 2019-11-30 08:44:24

问题


As per project requirement we need to convert images from word document into bitmap object. To achieve this we tried to convert inlineshape object from Microsoft.Office.Interop.Word dll into bitmap. However unable to get success, getting clipboard object as null. Please find the code which we tried as below;

using System.Drawing;
using Microsoft.Office.Interop.Word;
namespace WordApp1
{
    class Program
    {
        static void Main(string[] args)
        {
           Application wordApp = (Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
           Documents documents = wordApp.Documents;

           Document d = null;
           foreach (Document document in documents)
           {
              if (document.ActiveWindow.Caption.Contains("{Word document name}"))
              {
                 d = document;
              }
           }

           foreach (InlineShape shape in d.InlineShapes)
           {
              shape.Range.Select();
              d.ActiveWindow.Selection.Range.CopyAsPicture();
              System.Windows.Forms.IDataObject dobj = System.Windows.Forms.Clipboard.GetDataObject();  //Getting clipboard object as null
              if(dobj.GetDataPresent(typeof(System.Drawing.Bitmap)))
              {
                 Bitmap bmp;
                 System.IO.MemoryStream ms = new System.IO.MemoryStream();
                 bmp = (Bitmap)dobj.GetData(typeof(System.Drawing.Bitmap));
              }
            }
        }        
     }
 }

Does anyone has worked on converting word images into bitmap? It would be great help if you could guide us how to go ahead with converting images from word document into bitmap object.


回答1:


Resolved in this post: https://stackoverflow.com/a/7937590/1071212 It's a problem with STAThread:

Thread thread = new Thread([Method]);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();



回答2:


Try this.

foreach (InlineShape shape in d.InlineShapes)             
{ 
    if (shape != null)
    {
        shape.Range.Select(); 
        d.ActiveWindow.Selection.Copy();
        Bitmap bitmap = new Bitmap(Clipboard.GetImage());
    }
}



回答3:


There's two Clipboard.

Usually we'd use System.Windows.Forms.Clipboard, but it sucks.

Use System.Windows.Clipboard instead, just add PresentationCore to your references.

(in my case, C:\Program Files\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\Profile\Client\PresentationCore.dll)



来源:https://stackoverflow.com/questions/4870267/converting-images-from-word-document-into-bitmap-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!