Replace a word using an image

Hi,

Is it possible to replace a text in a word document using an image. I was able to replace an image using an image. But I want to replace a word using an image. Is there a way to do it.
Thank You.

Hi Ravindu,

Thanks for your inquiry. Yes, you can achieve your requirement by implementing IReplacingCallback interface. Please use the same approach shared in following article to achieve your requirements.

Following Java code example shows how to find and text and replace it with image. Hope this helps you.

public class FindandReplace implements IReplacingCallback
{
    public String imagepath;
    DocumentBuilder builder;
    public FindandReplace(DocumentBuilder db, String path)
    {
        builder = db;
        imagepath = path;
    }

    public int replacing(ReplacingArgs e) throws Exception
    {
        // This is a Run node that contains either the beginning or the complete match.
        Node currentNode = e.getMatchNode();

        // The first (and may be the only) run can contain text before the match,
        // in this case it is necessary to split the run.
        if (e.getMatchOffset() > 0)
            currentNode = splitRun((Run)currentNode, e.getMatchOffset());

        // This array is used to store all nodes of the match for further highlighting.
        ArrayList runs = new ArrayList();

        // Find all runs that contain parts of the match string.
        int remainingLength = e.getMatch().group().length();
        while (
                (remainingLength > 0) &&
                        (currentNode != null) &&
                        (currentNode.getText().length() <= remainingLength))
        {
            runs.add(currentNode);
            remainingLength = remainingLength - currentNode.getText().length();

            // Select the next Run node.
            // Have to loop because there could be other nodes such as BookmarkStart etc.
            do
            {
                currentNode = currentNode.getNextSibling();
            }
            while ((currentNode != null) && (currentNode.getNodeType() != NodeType.RUN));
        }

        // Split the last run that contains the match if there is any text left.
        if ((currentNode != null) && (remainingLength > 0))
        {
            splitRun((Run)currentNode, remainingLength);
            runs.add(currentNode);
        }

        builder.moveTo((Run)runs.get(0));
        builder.insertImage(imagepath);
        //Remove runs
        for (Run run : (Iterable) runs)
        {
            run.remove();
        }

        // Signal to the replace engine to do nothing because we have already done all what we wanted.
        return ReplaceAction.SKIP;
    }

    /**
     * Splits text of the specified run into two runs.
     * Inserts the new run just after the specified run.
     */
    private Run splitRun(Run run, int position) throws Exception
    {
        Run afterRun = (Run)run.deepClone(true);
        afterRun.setText(run.getText().substring(position));
        run.setText(run.getText().substring((0), (0) + (position)));
        run.getParentNode().insertAfter(afterRun, run);
        return afterRun;
    }
}

Document doc = new Document(MyDir + "in.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

FindReplaceOptions replaceOptions = new FindReplaceOptions();
replaceOptions.ReplacingCallback = new FindandReplace(builder, MyDir + "input.png");

doc.getRange().replace("this text will replace with image", "", replaceOptions);

doc.save(MyDir + "Out v16.11.0.docx");
1 Like

Hi Tahir,


Thanks for the answer. But I couldn’t find <span class=“pl-smi” style=“color: rgb(51, 51, 51); font-family: Consolas, “Liberation Mono”, Menlo, Courier, monospace; font-size: 12px; white-space: pre; background-color: rgb(255, 255, 255);”>FindReplaceOptions class. I’m using aspose word 15.10.0 version(licensed). The class <span class=“pl-smi” style=“color: rgb(51, 51, 51); font-family: Consolas, “Liberation Mono”, Menlo, Courier, monospace; font-size: 12px; white-space: pre; background-color: rgb(255, 255, 255);”>FindReplaceOptions is in version 16 right. How can I achieved this using my current version?

Thank You

Hi Ravindu,

Thanks for your inquiry. Please note that we do not provide support for older versions of Aspose APIs. We always encourage our customers to use the latest version of Aspose.Words as it contains newly introduced features, enhancements and fixes to the issues that were reported earlier. Please upgrade to the latest version of Aspose.Words for Java 16.11.0.

Please check public API changes in Range.Replace method from here:

Aspose.Words for Java 16.7.0 Release Notes

If you want to use older version of Aspose.Words, please use the following Java code example. Hope this helps you.

Document doc = new Document(MyDir + "in.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

Pattern regex = Pattern.compile("your text", Pattern.CASE_INSENSITIVE);
doc.getRange().replace(regex, new FindandReplace(builder, MyDir + "input.png"), false);

doc.save(MyDir + "Output.docx");

Thanks Tahir,


I need to do this in presentation too. is it possible.
Noe I was able to replace word by a word. But couldn’t replace a word by an image. Please help.

I used iPortion there

String str = iPortion.getText();
//code
iPortion.setText(strStartText + replacedWord + strEndText);


Thank You
Hi Ravindu,

Thanks for your inquiry. Your query is related to Aspose.Slides. I am moving this forum thread to Aspose.Total forum. My colleagues from Aspose.Slides team will reply you soon.

Hi Ravindu,

I have observed your requirements from perspective of Aspose.Slides. I like to share that if you want to replace a text with image in PowerPoint presentation using Aspose.Slides, then unfortunately this is not possible. Actually, image a complete shape when you deal with that in a presentation. Also the text frame belongs to some shape as well. It is not possible to replace only a portion of text with an image inside text frame. I hope this will clarify the concept to you. Please share if your requirement is otherwise in this regard.

Many Thanks,

Hi,

Not a portion of a text. A complete word. for example

Test Line 1
Test Line 2
<>
Test Line 3

In the above example, only the <> should replace with an image. I hope the question is clear.

Or is it possible if there is only one text in a text frame?

Thank You

Hi Ravindu,

I have observed your comments and like to share that you can set the image for entire shape that holds a text frame (the text frame can have 1 word even). If you can find the text in text frame, you can set the FillType for shape to Picture and then add image in that. Doing this will mean that you are setting the shape fill type to Picture for entire shape. Please refer to following sample code for reference on your end. You may change this on your end to serve the purpose.

Presentation pres=new Presentation(path+“test.pptx”);

ISlide slide=pres.getSlides().get_Item(0);

IShape shape=null;
for(int i=0;i<slide.getShapes().size();i++)
{

shape=slide.getShapes().get_Item(i);

if(shape instanceof IAutoShape)
{
IAutoShape ashp=(IAutoShape)shape;

if(ashp.getTextFrame()!=null)
{
ITextFrame text=ashp.getTextFrame();
if(text.getText().contains(textTofind))
{
text.setText("");
ashp.getFillFormat().setFillType(FillType.Picture);

// Set the picture
IPPImage imgx = null;
try {
imgx = pres.getImages().addImage(new FileInputStream(new File(“aspose1.jpg”)));
}
catch (IOException e) {
}

ashp.getFillFormat().getPictureFillFormat().getPicture().setImage(imgx);

}


}
}

}

Many Thanks,

Thanks for the answer.


It’s working. But the image duplicates and doesn’t fit the text frame. I have attached the power point generates. If you resize(increase the width) the text frame you can see multiple pics stacked too.
Please help me in this matter.

Thank You

Hi Ravindu,

I have observed the information shared by you and like to share that text frame is not replaced with image but image gets fit within shape bound that contain textframe. You can alter the text frame shape width and height property in accordance with your desires before replacement. If you still find a confusion them please provide source presentation, image to replace and desired generated presentation. I will investigate that further on my end to help you out.

Many Thanks,

Hi,

I have attached the presentation file and the image I want to add. And a presentation file how it should look like

Hi Ravindu,

I have worked with the presentation files shared by you and suggest you to please only replace following line your code :

text.setText("");

with

text.setText(" ");

Actually, the text that is appearing is actually only default placholder text for user to add the text in placeholder. It is even invisible when you run slide show. The solution to avoid this is to simply set the text to a space character which will solve the issue. I hope this will be helpful.

Many Thanks,

Hey Mudassir,


Actually the problem is the image replaced is duplicated and shoes multiply in the text placeholder.
I have attached a sample presentation.Mudassir is not online. Last active: 11-21-2016, 7:45 AM

Hi Ravindu,

I have observed the presentation file shared by you and like to share that the issue does not seemingly related to Aspose.Slides. Earlier, you have shared the image over this link that I have used to share the working sample code with you. In code, I am simply adding an image and nothing more to a shape. It seems that you are probably trying to add an image that it self has issue. Can you please check the image again on your end that you have used in your presentation as this is not the one that you have earlier shared with me. If there is still issue please share the source image with me along with used sample code and source presentation, I will investigate this further on my end to help you out.

Many Thanks,

Hi,

The problem is it shows multiple images inside that textholder. If you resize it and increase it’s width, you can see a duplicate image joined to that. Open the Verified Exec Presentation 222(Doc Genarated) file and try to resize the placholder with the image. You can see multiple
I have attached the img and the presentation file. The image is get from a byte array.
Here is the code snippet.

presentation.getSlides().forEach(slide -> {
slide.getShapes().forEach(shape -> {

if (shape instanceof IAutoShape) {
IAutoShape ashp = (IAutoShape) shape;

if (ashp.getTextFrame() != null) {

ITextFrame text = ashp.getTextFrame();
documentTagDTOsImg.forEach(tags -> {
if (tags.getType().equals(“I”)) {
if (text.getText().contains(tags.getName())) {
text.setText(" ");
ashp.getFillFormat().setFillType(FillType.Picture);
// Set the picture
IPPImage imgx = null;
imgx = presentation.getImages().addImage(tags.getImgValue());
ashp.getFillFormat().getPictureFillFormat().getPicture().setImage(imgx);

}
}
});

}

}

});

Hi Ravindu,

I have observed your presentation and like to share that the PictureFillMode property, “Tile” is by default set in code. Please add following line in code after you have added image in shape.

ashp.getFillFormat().getPictureFillFormat().setPictureFillMode(PictureFillMode.Stretch);

I am hopeful, things will work on your end.

Many Thanks,

Great, It worked. Thanks Mudassir