I have a Word document (referred to as "doc" in the code below) with a bunch of .jpg images. Some of them have text wrapped around them (= Shapes), some of them don't (= InlineShapes). I am able to save the InlineShapes like so:
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);
}
But if I try to get the other ones by replacing the first two lines with these –
Shape s = doc.Shapes[1];
s.Select();
– it won't work. And if I check the formats with "data.GetFormats()" I notice that Bitmap isn't listed, which explains why it doesn't work. Instead it lists the "Office Drawing Shape Format". I suppose that I should try to convert the Shape to a InlineShape somehow, but I haven't been able to make it work. When I try to do it like this –
s.ConvertToInlineShape();
– I get an "invalid parameter" exception.
OK, the problem seems to have been that I tried to convert it at the wrong time. If I loop through all Shapes and convert them before trying to do anything else it works fine.
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);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments