将Word文档中的图像转换为位图对象

5

根据项目要求,我们需要将Word文档中的图像转换为位图对象。为了实现这一目标,我们尝试将Microsoft.Office.Interop.Word dll中的inlineshape对象转换为位图。然而,我们无法成功,因为获取到的剪贴板对象为空。请查看我们尝试的代码如下:

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

有没有人尝试将Word图像转换为位图?如果您能指导我们如何将Word文档中的图像转换为位图对象,那将是非常有帮助的。

3个回答

2

在这个帖子中得到解决:https://dev59.com/7lzUa4cB1Zd3GeqP5rPP#7937590 它是与STAThread相关的问题:

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

0

试试这个。

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

0

有两个剪贴板。

通常我们会使用System.Windows.Forms.Clipboard,但它很糟糕。

改用System.Windows.Clipboard,只需将PresentationCore添加到您的引用中即可。

(在我的情况下,C:\ Program Files \ Reference Assemblies \ Microsoft \ Framework.NETFramework \ v4.0 \ Profile \ Client \ PresentationCore.dll)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接