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

Free Support Forum - aspose.com

Replace a word with an image in Java

Hi,
Is it possible to replace a word with an image in aspose word v21.
In v18 I managed to do it using the following code snippet.

Pattern regex = Pattern.compile("searchtext", Pattern.CASE_INSENSITIVE);
range.replace(regex, new FindandReplace(builder, getImgValueByte()));

@ravindueranga,

For example, you can replace word “Aspose” in Word document with its logo image by using the following code:

Document doc = new Document("C:\\temp\\input.docx");

ReplacingCallbackHandler handler = new ReplacingCallbackHandler();
FindReplaceOptions opts = new FindReplaceOptions(FindReplaceDirection.BACKWARD);
opts.setReplacingCallback(handler);

doc.getRange().replace("Aspose", "C:\\Temp\\Logo.png", opts);

doc.save("C:\\Temp\\awjava-21.9.docx");

static class ReplacingCallbackHandler implements IReplacingCallback {

    public int replacing(ReplacingArgs e) throws Exception {
        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 removing.
        ArrayList runs = new ArrayList();

        // Find all runs that contain parts of the match string.
        int remainingLength = e.getMatch().group(0).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);
        }

        DocumentBuilder builder = new DocumentBuilder((Document) e.getMatchNode().getDocument());
        builder.moveTo((Run) runs.get(0));
        builder.insertImage(e.getReplacement());

        //Now remove all runs in the sequence.
        for (Run run : (Iterable<Run>) runs)
            run.remove();

        return ReplaceAction.SKIP;
    }

    private static 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, position));
        run.getParentNode().insertAfter(afterRun, run);
        return afterRun;
    }
}

@awais.hafeez

Thanks alot awais. I have stumble upon another problem. This sample code accept a string for the image location. Is it possible to pass the image to be replaced as an byte[]. Instead of giving a image location, since I get the image from a DB as a byte[]

@ravindueranga,

Yes, it is possible to pass the image to be replaced as an byte[].

InputStream is = new FileInputStream(new File("C:\\Temp\\Logo.png"));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
    buffer.write(data, 0, nRead);
}
buffer.flush();
byte[] imageBytes = buffer.toByteArray();

Document doc = new Document("C:\\temp\\input.docx");

ReplacingCallbackHandler handler = new ReplacingCallbackHandler(imageBytes);
FindReplaceOptions opts = new FindReplaceOptions(FindReplaceDirection.BACKWARD);
opts.setReplacingCallback(handler);

doc.getRange().replace("Aspose", "", opts);

doc.save("C:\\Temp\\awjava-21.9.docx");

static class ReplacingCallbackHandler implements IReplacingCallback {

    public static byte[] _imageBytes;

    public ReplacingCallbackHandler(byte[] imageBytes) {
        _imageBytes = imageBytes;
    }

    public int replacing(ReplacingArgs e) throws Exception {
        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 removing.
        ArrayList runs = new ArrayList();

        // Find all runs that contain parts of the match string.
        int remainingLength = e.getMatch().group(0).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);
        }

        DocumentBuilder builder = new DocumentBuilder((Document) e.getMatchNode().getDocument());
        builder.moveTo((Run) runs.get(0));
        builder.insertImage(_imageBytes);

        //Now remove all runs in the sequence.
        for (Run run : (Iterable<Run>) runs)
            run.remove();

        return ReplaceAction.SKIP;
    }

    private static 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, position));
        run.getParentNode().insertAfter(afterRun, run);
        return afterRun;
    }
}