Python: Replace text with image in docx

""" Replace text with inline image dependencies: python-docx """ import docx from docx.document import Document from docx.text.paragraph import Paragraph from docx.table import _Cell, Table from docx.oxml.table import CT_Tbl from docx.oxml.text.paragraph import CT_P from docx.shared import Cm doc = docx.Document('input.docx') TEXT_TO_REPLACE = '{firma}' IMAGE_FILENAME = 'firma.png' def iter_block_items(parent): """ Generate a reference to each paragraph and table child within *parent*, in document order. Each returned value is an instance of either Table or Paragraph. *parent* would most commonly be a reference to a main Document object, but also works for a _Cell object, which itself can contain paragraphs and tables. """ if isinstance(parent, Document): parent_elm = parent.element.body # print(parent_elm.xml) elif isinstance(parent, _Cell): parent_elm = parent._tc else: raise ValueError("something's not right") for child in parent_elm.iterchildren(): if isinstance(child, CT_P): yield Paragraph(child, parent) elif isinstance(child, CT_Tbl): yield Table(child, parent) def replace_image_placeholder(paragraph, text, image_filename): """replace text with image""" # --- 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.5)) for block in iter_block_items(doc): if not isinstance(block,Table): if TEXT_TO_REPLACE in block.text: replace_image_placeholder(block, TEXT_TO_REPLACE, IMAGE_FILENAME) previous_block = block doc.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.