Search code examples
python-docx

Add image to header using python-docx and docxtpl


I have working code to insert an image into a DOCX template (using Jinja template format provided by docxtpl) but while the image works when inserted into the document body the image fails to render in the header. The insertion point in the document {{p my_image}} displays the message 'Read Error'.

I assume this is a bug/limitation in the python-docx library but I was wondering if there's a known workaround. I've tried 2 methods to create the image but both fail with the same 'Read Error' message only when used in the header:

Method 1:

sub_doc = self.template.new_subdoc()
p = sub_doc.add_paragraph()
r = p.add_run()
r.add_picture(output_path)
return sub_doc

Method 2:

from docxtpl import InlineImage
return InlineImage(template, image_path, width, height)

Solution

  • Old question but maybe someone need it.

    I write images into the header of a DOCX file with the following by using the docx module. In my case I have to write the image into a table.

    from docx import Document
    from docx.shared import Inches
    
    header = doc.sections[0].header
    
    #Insert table with 2 rows and 3 columns
    headertable = header.add_table(2, 3, Inches(6))
    headertable.style("borderColor:black")
    a = headertable.cell(0, 0)
    b = headertable.cell(1, 0)
    A = a.merge(b)
    
    #add table in header
    headertab_cells = headertable.rows[0].cells
    
    ht0 = headertab_cells[0].add_paragraph()
    kh = ht0.add_run()
    kh.add_picture('logo.jpg', width=Inches(1))