I want to insert an image after a certain phrase. I am testing on the following document:
chapters_generator33354.docx (39.7 KB)
I am using the following code:
import sys
import aspose.words as aw
import requests
from io import BytesIO
def insert_image_after_phrase(doc_path, phrase_match, image_url):
# Create Aspose Words document object
document = aw.Document(doc_path)
builder = aw.DocumentBuilder(document)
# Download the image from the URL
response = requests.get(image_url)
image_bytes = BytesIO(response.content)
for r in document.get_child_nodes(aw.NodeType.RUN, True):
run = r.as_run()
if phrase_match in run.text:
builder.move_to(run)
builder.insert_image(image_bytes)
# Save the document
document.save(doc_path)
# Usage example:
if __name__ == "__main__":
if len(sys.argv) != 4:
print("Usage: python script.py <doc_path> <phrase_match> <image_url>")
sys.exit(1)
doc_path = sys.argv[1]
phrase_match = sys.argv[2]
image_url = sys.argv[3]
insert_image_after_phrase(doc_path, phrase_match, image_url)
I run it like this:
python3 insert_img_after_phrase.py chapters_generator33354.docx "Infine, non dimentichiamo l'importanza dell'acquacoltura " "https://cdn.leonardo.ai/users/e084d054-0537-4095-a7b6-4ca61b2950ac/generations/47a21e29-e31c-49c7-9aa3-3851d7683189/Default_An_illustrative_image_depicting_the_journey_of_Rossi_0.jpg"
The image is inserted before the phrase. When I tried to insert the image after the phrase using:
for r in document.get_child_nodes(aw.NodeType.RUN, True):
run = r.as_run()
if phrase_match in run.text:
next_run = run.next_sibling
if next_run is not None:
builder.move_to(next_run)
builder.insert_image(image_bytes)
break
The image is not inserted at all.
Any help is appreciated.