从Word到剪贴板到文件的图像(noninlineshape)

时间:2014-12-25 01:23:37

标签: c# image ms-word interop clipboard

我有一组带有一堆.jpg图像的Word文档(在下面的代码中称为“doc”)。它们中的一些包含文本(=形状),其中一些不包含(= InlineShapes)。我能像这样保存InlineShapes:

InlineShape ils = doc.InlineShapes[1];
ils.Select();
application.Selection.Copy();
IDataObject data = Clipboard.GetDataObject();
if (data.GetDataPresent(DataFormats.Bitmap)) {
    Image image = (Image)data.GetData(DataFormats.Bitmap, true);
        image.Save("c:\\image.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}

但是,如果我试图通过用这些 -

替换前两行来获得其他的那些
Shape s = doc.Shapes[1];
s.Select();

- 它不起作用。如果我用“data.GetFormats()”检查格式,我注意到没有列出Bitmap,这解释了为什么它不起作用。相反,它列出了“Office绘图形状格式”。我想我应该尝试以某种方式将Shape转换为InlineShape,但我无法使其工作。当我尝试这样做时 -

s.ConvertToInlineShape();

- 我收到“无效参数”异常。

1 个答案:

答案 0 :(得分:1)

好的,问题似乎是我试图在错误的时间转换它。如果我在尝试做任何其他事情之前遍历所有形状并转换它们就可以正常工作。

int number = doc.InlineShapes.Count;
MessageBox.Show(number.ToString()); // 0 to begin with

foreach (Microsoft.Office.Interop.Word.Shape s in doc.Shapes) {
    MessageBox.Show(s.Type.ToString());
    if (s.Type.ToString() == "msoTextBox") {
        MessageBox.Show(s.TextFrame.TextRange.Text);
    } else if (s.Type.ToString() == "msoPicture") {
        s.ConvertToInlineShape();
    }
}

number = doc.InlineShapes.Count;
MessageBox.Show(number.ToString());  // Now it's 1 as it should be

InlineShape ils = doc.InlineShapes[1];
ils.Select();
application.Selection.Copy();

IDataObject data = Clipboard.GetDataObject();
if (data.GetDataPresent(DataFormats.Bitmap)) {
    Image image = (Image)data.GetData(DataFormats.Bitmap, true);
    image.Save("c:\\image.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}