Python: Replace text with image in docx

#install python-docx from docx import Document doc = Document('input.docx') text_to_replace = '{sign file here}' image_filename = 'sign.png' for block in iter_block_items(doc): if isinstance(block,Table): #this is a table #do something here else: if text_to_replace in block.text: replace_image_placeholder(block, text_to_replace, image_filename) previous_block = block def replace_image_placeholder(paragraph, text, image_filename): # --- start with removing the placeholder text --- paragraph.text = paragraph.text.replace(text, "") # --- then append a run containing the image --- run = paragraph.add_run() run.add_picture(image_filename, height=Cm(2)) document.save('output.docx')

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.