We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Inserting and changing an image size in Words for Java

We have a application that replaces instances of the text <{myImage}> in a .doc file with an image using documentBuilder.insertImage();

We put the text <{myImage}> inside of a textbox in Word and we would like to resize the image to be the size of the textbox container. We have accomplished this in using Aspose.Slides for PPT (using placeholders instead of a textbox), and would like to do the same in Word.

Thanks in advance.

What step exactly are you having a problem with? Replacing text with an image or sizing the image?

We happen to discuss the same question in a neighbouring thread <A href="</A></P> <P>There we simply replace a textbox object with an image object. The code is there, you can easily port it to Java.</P> <P>We also discussed an issue of modifying the size of the image to be different from the original textbox (that involved local coordinates etc), but you don't need that. If you just insert an image in place of a textbox object, you just do image.Width = textbox.Width etc.</P> <P> </P>

I can replace text with an image. I would like to be able to replace the textbox that contains the text with an image (resized to the size of the textbox) using a ReplaceEvaluator.

public int replace(Object object, ReplaceEvaluatorArgs e) throws Exception {
DocumentBuilder docBuilder = new DocumentBuilder(e.getMatchNode().getDocument());
Node myNode = e.getMatchNode();
docBuilder.moveTo(myNode);

// How do I get the shape that the text is in so I can resize the image?


docBuilder.insertImage("C:\\myImage.png");
e.setReplacement("");
return ReplaceAction.REPLACE;
}

The following code seems to do the job nicely:

[Test]

public void TestRepaceTextInTextboxWithImage()

{

Document doc = TestUtil.Open("TestRepaceTextInTextboxWithImage.doc");

doc.Range.Replace(new Regex("<{myImage}>"), new ReplaceEvaluator(ReplaceEvaluator3), false);

TestUtil.SaveShow(doc, @"TestRepaceTextInTextboxWithImage Out.doc");

}

private ReplaceAction ReplaceEvaluator3(object sender, ReplaceEvaluatorArgs e)

{

DocumentBuilder builder = new DocumentBuilder(e.MatchNode.Document);

builder.MoveTo(e.MatchNode);

Shape shape = builder.InsertImage(@"E:\Aspose.Words\Tests\TestOne\bin\Aspose.Words.gif");

Shape textboxShape = (Shape)shape.GetAncestor(typeof(Shape));

if (textboxShape != null && textboxShape.ShapeType == ShapeType.TextBox)

{

textboxShape.TextBox.InternalMarginLeft = 0;

textboxShape.TextBox.InternalMarginTop = 0;

shape.Width = textboxShape.Width;

shape.Height = textboxShape.Height;

}

e.Replacement = "";

return ReplaceAction.Replace;

}

It is in C#. Please let me know if you have any trouble to convert it to Java.

Best regards,

It worked perfectly. Thank you for another quick response.