Replace Image in Word document

Hi,

I need to find particular image in word file and I need to replace with another image.
I tried with using document builder and shapes then i checked whether it is hasimage then finally i removed that image but i cant able to insert another image with that place. Please send any piece of code for that…

Thanks,

Logaraja E

Hi logaraja,

Thanks for your query. Please use the following code snippet for your requirements. Hope this helps you. If you still face problem, please share your document along with shape information. We will provide you code snippet accordingly.

Document doc = new Document(MyDir + "in.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);
builder.MoveTo(shape);
Paragraph para = builder.InsertParagraph();
builder.MoveTo(para);
shape.Remove();
Shape image = builder.InsertImage("d:\\Chrysanthemum.jpg");
doc.Save(MyDir + "AsposeOut.docx");

Hi,

Thank you… It works fine for one image replacement. But I need to collect all image in the document and I have to replace them.
This is my code what i am doing right now…

Aspose.Words.Document doc = new Aspose.Words.Document("Old.doc");

DocumentBuilder builder = new DocumentBuilder(doc);

NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true, false);

Image image = Image.FromFile("logaraja.png");
foreach (Aspose.Words.Drawing.Shape nshape in shapes)
//for (int i = 0; i < shapes.Count; i++)
{
    builder.MoveTo(nshape);
    // builder.MoveTo(shapes[i]); 
    Paragraph para = builder.InsertParagraph();
    builder.MoveTo(para);
    nshape.Remove();
    //shapes[i].Remove();
    Shape wordimage = builder.InsertImage(image);

}
doc.Save("new.doc");

while i was testing, first time entered into “for each” and replace that image successfully then it didnt go to the second time. loop exists and save the doc. for that
I changed to “for loop” again it is working fine for first time. then entered into second time it gives null reference.(// builder.MoveTo(shapes[i]) in this line.

Thanks

Hi logaraja,

Thanks for sharing the details. Please use the following code snippet for your requirement. Let us know if you have any more queries.

Document doc = new Document(MyDir + "in.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);
foreach (Aspose.Words.Drawing.Shape nshape in shapes)
{
    nshape.ImageData.SetImage(@"Image.jpg");
}
doc.Save(MyDir + "AsposeOut.docx");

Thank you, Sounds good!!!.