Problem inserting a image in a docx file

Hi all!

We need to replace the text “form.pdfsection.name.Contenido.end” that is in the file “Plantilla.docx” with the image file “page0.jpeg”.

The print result can be seen in the file “Doc- Target.docx”.

We need the image inserted in that word file respect the original size and is centralized on the page.

I attached “files.zip”.

Our version is 15.9 Aspose words

Best regards
Martin Fernandez
Senior Java Developer

Hi Martin,

Thanks for your inquiry. You can achieve your requirement by implementing IReplacingCallback interface. Please use following code example to achieve your requirements and read following articles for your kind reference. Hope this helps you.

Find and Replace Overview
How to Find and Highlight Text

class FindandInsertImage implements IReplacingCallback
{
    String image;
    DocumentBuilder builder;
    FindandInsertImage(String imagepath)
    {
        image = imagepath;
    }
    /**
     * This method is called by the Aspose.Words find and replace engine for each match.
     */
    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();
        if(builder == null)
            builder = new DocumentBuilder((Document)currentNode.getDocument());
        // 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());
        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));
        Shape shape = builder.insertImage(image);
        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;
    }
    private Boolean isLink(Run run, String text) throws Exception
    {
        for(Field field : run.getParentParagraph().getRange().getFields())
        {
            if(field.getType() == FieldType.FIELD_HYPERLINK
                    &&field.getResult().trim().equals(text))
            {
                return true;
            }
        }
        return false;
    }
    /**
     * 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 + "Plantilla.docx");
Pattern regex = Pattern.*compile*("form.pdfsection.name.Contenido.end", Pattern.CASE_INSENSITIVE);
FindandInsertImage obj = new FindandInsertImage(MyDir +"page0.jpeg");
doc.getRange().replace(regex, obj, false);
doc.save(MyDir + "Out.docx");