NewAutoUser
NewAutoUser

Reputation: 573

Converting images from word document into bitmap object

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.

Upvotes: 5

Views: 7314

Answers (3)

Skier In Summer
Skier In Summer

Reputation: 1

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)

Upvotes: 0

aclalex
aclalex

Reputation: 107

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();

Upvotes: 2

Stephen
Stephen

Reputation: 3084

Try this.

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

Upvotes: 0

Related Questions