Replace picture and keep position- size attributes

Hello,

I have been trying to do something with ASPOSE words that I have done previously using MS word and that is to replace an existing shape with another shape from a file. This used to be done doing something like the following where the relevant shape had been named via a macro.

Dim sNewPicture As Microsoft.Office.Interop.Word.Shape
Dim sFileName as String = "C:\Temp\test.bmp"

For Each oPicture In oWordAppl.ActiveDocument.Shapes
If oPicture.Name = "Photo" Then
oPicture.Select()
sNewPicture = myWordApp.ActiveDocument.Shapes.AddPicture(FileName:=sFileName, Left:=oPicture.Left, Top:=oPicture.Top, Width:=oPicture.Width, Height:=oPicture.Height, Anchor:=myWordApp.Selection.Range)
oPicture.Delete()
End If
Next oPicture

I have tried to do something similar with aspose as per the following

Dim shapes As Aspose.Words.NodeCollection = oDoc.GetChildNodes(NodeType.Shape, True, False)
Dim shape As Aspose.Words.Drawing.Shape
Dim insertShape As Aspose.Words.Drawing.Shape

For Each shape In shapes
If shape.HasImage Then
If shape.ImageData.ImageType = Drawing.ImageType.Jpeg Then
insertShape = builder.InsertImage("C:\Temp\test.bmp")
insertShape.Top = shape.Top
insertShape.Left = shape.Left
insertShape.Width = shape.Width
insertShape.Height = shape.Height
shape.Remove()
End If
End If
Next

however without much luck - I have attached the document I am working off and the picture to be replaced is in the top left corner "Place Photo Here".

Can you please offer any suggestions?

thanks
Simon

Dear Simon,

Thank you for your request. Actually, the Aspose.Words approach is even simpler. You may not replace the whole shape, you can merely set a new image data to the same image and it will preserve all shape properties such as location or size:

Document doc = new Document(@"D:\Work\Test.doc");

// I querying Body because the target shape is placed in there.

Shape image = (Shape)doc.FirstSection.Body.GetChild(NodeType.Shape, 0, true);

image.ImageData.SetImage(@"D:\Work\Test.png");

doc.Save(@"D:\Work\Test Out.doc");

Please let me know if it helps.

Hi Dmitry,

thanks very much for that - is there any way to do that in VB so that no casting is required?

thanks
Simon

Hi Dmitry,

sorry about that I did the following and all works fine

Dim shapes As NodeCollection = oDoc.FirstSection.Body.GetChildNodes(NodeType.Shape, True)
Dim shape As Aspose.Words.Drawing.Shape

For Each shape In shapes
If shape.HasImage Then
shape.ImageData.SetImage((@"D:\Work\Test.png")
End If
Next

thanks again for your help
Simon

Great. If you ever need more assistance, please don’t hesitate to ask. I’ll use a C# to VB .NET converter next time :slight_smile: