Losing images in docx template while rendering

117 Views Asked by At

I am using docxtpl (python-docx-template) to render a template before I actually render the content from a dict. Although everything works, my images keep missing.

I collect multiple other docx-files for my template, access them, render content from a dict and keep them in a byte-stream. But when the components are loaded and put in the main-file, the images are missing. Any ideas why?

from io import BytesIO

from docx import Document
from docxtpl import DocxTemplate

from docxcompose.composer import Composer

templates_folder = os.path.join(os.path.dirname(__file__), 'templates')
output_folder = os.path.join(os.path.dirname(__file__), 'output')

test_data = {
    'MODUL_header': {
        'something': 'bla'
},


def generate_header(template_path):
    document = DocxTemplate(template_path)
    document.render(test_data)

    file_stream = BytesIO()
    document.save(file_stream)
    file_stream.seek(0)
    return file_stream



def test(template_path):
    with open(template_path, 'rb') as f:
        source_stream = BytesIO(f.read())

    # Declare Template-Object
    document = DocxTemplate(source_stream)

    if "MODUL_header" in test_data:
        _path = os.path.join(templates_folder, 'header.docx')
        header = document.new_subdoc(generate_kopfzeile(_path))
        test_data['MODUL_header'] = header

    document.render(test_data)

    file_path = os.path.join(output_folder, 'test.docx')
    document.save(file_path)


if __name__ == '__main__':
    template_path = os.path.join(templates_folder, 'main_template.docx')
    test(template_path)

Of course there is a var with the name MODUL_header in my docx-file :)

1

There are 1 best solutions below

1
Austin On

I had a similar issue where there was a collision with an ID in the header images and an image in the body.

To check, open the word folder in the docx file with something like 7-Zip and check that any picture IDs in the header.xml file don't clash with any IDs in the document.xml file.