With images it is a bit more trickier. You see, an image can be added to a paragraph/run only, so before using AddDrawing
you also need to create a paragraph/run. Something like this:
image = api.Call("CreateImage", "temp.png", 100, 50) // Define image
para = api.Call("CreateParagraph") // Create new paragraph to insert image to
para.Call("AddDrawing", image); // Insert image into the paragraph
document.Call("InsertContent", [para]) // Insert paragraph with image
I’ve used AddDrawing for paragraph in this example.
yt-0r
16 May 2025 01:55
23
I tried your method but it doesn’t work. Instead of a picture I get a blank space. Maybe there are alternative ways to add a picture?
Are you performing search, select, delete prior to inserting the image?
yt-0r
23 May 2025 04:27
25
I’m trying this
source file
final file
code:
import sys
import os
try:
# Проверка пути к файлу
sys.path.append('C:/Program Files/ONLYOFFICE/DocumentBuilder')
import docbuilder
builder = docbuilder.CDocBuilder()
input_file = '123.docx'
input_file = os.path.abspath(input_file)
builder.OpenFile(input_file, 'docx')
context = builder.GetContext()
api = context.GetGlobal()["Api"]
document = api.Call("GetDocument")
# create image
image = api.Call("CreateImage", "temp.png", 1000, 500)
para = api.Call("CreateParagraph")
para.Call("AddDrawing", image)
document.Call("InsertContent", [para])
key = 'image'
search_results = document.Call("Search", "{{" + key + "}}")
if search_results:
search_results[0].Call("Select")
document.Call("InsertContent", [image])
builder.SaveFile("docx", '1234.docx')
except Exception as e:
print(f"Ошибка: {e}")
finally:
builder.CloseFile()
You do not seem to be paying attention to the way elements interact with others. Here is simplified version of your script:
import sys
import os
try:
sys.path.append('C:/Program Files/ONLYOFFICE/DocumentBuilder')
import docbuilder
builder = docbuilder.CDocBuilder()
input_file = 'image.docx'
input_file = os.path.abspath(input_file)
builder.OpenFile(input_file, 'docx')
context = builder.GetContext()
api = context.GetGlobal()["Api"]
document = api.Call("GetDocument")
image = api.Call("CreateImage", "https://static.onlyoffice.com/assets/docs/samples/img/onlyoffice_logo.png", 60 * 36000, 35 * 36000)
para = api.Call("CreateParagraph")
para.Call("AddDrawing", image)
search_results = document.Call("Search", "{{image}}")
search_results[0].Call("Select")
document.Call("InsertContent", [para])
builder.SaveFile("docx", '1234.docx')
except Exception as e:
print(f"Error: {e}")
finally:
builder.CloseFile()
As a result: