Skip to content

can not insert a inline image and a subdoc with an image #66

Closed

Description

@cvas22

Copied from python-docx-template issue 474, opened by @MWMWM on 2023-01-04.


Describe the bug

I have a template that is supposed to render an inline image and a sub template containing an image but it fails (rendering only with a sub template or an inline image works great, rendering an inline image and a sub template NOT containing an image is also working)

To Reproduce

index

template1.docx
template2.docx

from docxtpl import DocxTemplate, InlineImage

doc = DocxTemplate("template2.docx")
subdoc = doc.new_subdoc('template1.docx')
photo = InlineImage(doc, image_descriptor='index.jpeg')
doc.render({"template": subdoc, "photo": photo}, autoescape=True)

Current behavior

The following error happens

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "xxx/site-packages/docxtpl/template.py", line 343, in render
    xml_src = self.build_xml(context, jinja_env)
  File "xxx/site-packages/docxtpl/template.py", line 290, in build_xml
    xml = self.render_xml_part(xml, self.docx._part, context, jinja_env)
  File "xxx/site-packages/docxtpl/template.py", line 239, in render_xml_part
    dst_xml = template.render(context)
  File "xxx/site-packages/jinja2/environment.py", line 1301, in render
    self.environment.handle_exception()
  File "/xxx/site-packages/jinja2/environment.py", line 936, in handle_exception
    raise rewrite_traceback_stack(source=source)
  File "<template>", line 4, in top-level template code
  File "xxx/site-packages/docxtpl/inline_image.py", line 39, in __html__
    return self._insert_image()
  File "xxx/site-packages/docxtpl/inline_image.py", line 24, in _insert_image
    pic = self.tpl.current_rendering_part.new_pic_inline(
  File "xxx/site-packages/docx/parts/story.py", line 57, in new_pic_inline
    cx, cy = image.scaled_dimensions(width, height)
AttributeError: 'ImageWrapper' object has no attribute 'scaled_dimensions'

Expected behavior

Template is rendered


Comments from the original thread

@sanjass on 2023-01-14:

I'm having the same issue. Based on some investigation the bug seems to happen only for some images and is coming from the python-docx package. For example, I don't get the bug if I use this image from the python-docx test images

What fixed it in my case is opening and saving the image with PIL:

from PIL import Image
f = Image.open('sample_image.jpeg')
f.save('new_sample_image.jpeg')    
f.close()
myimage = InlineImage(tpl, image_descriptor="new_sample_image.jpeg", width=Mm(100), height=Mm(100))
context["myimage"] = myimage

this might not work in all cases, so I'm still hoping there's a better fix here

@MWMWM on 2023-04-12:

@sanjass so maybe it's a different case - image from this image from the python-docx test images is not working in my case (the same image has to be present in template and added as an InlineImage)

@theodore86 on 2024-04-17:

did anyone noticed that the Inline image class is changing the docx template format? Seems like that the final format is letter rather than e.g A4

@MecHR17 on 2025-06-03:

Does anyone have a nice solution to this? As a temporary measure, I make a copy of the image with PIL (just copying the file normally does not seem to work) and use that instead in one of my documents. A general temporary solution could be to just have 2 separate image folders in that fashion, one to be used in the main doc and the other for subdocs (repeating the inline image in the subdocs does not seem to be problematic).

@alexcraviotto on 2025-07-04:

Does anyone have a nice solution to this? As a temporary measure, I make a copy of the image with PIL (just copying the file normally does not seem to work) and use that instead in one of my documents. A general temporary solution could be to just have 2 separate image folders in that fashion, one to be used in the main doc and the other for subdocs (repeating the inline image in the subdocs does not seem to be problematic).

Did you fix this?

@BigChickenLegs on 2026-03-13:

I have no idea, but I encountered the same problem

After word with AI, this problem seems to be solved, I don't understand the principle, but it does work.

def _patch_docxcompose_image_wrapper() -> None:
	try:
		from docx.image.image import Image
		from docxcompose.image import ImageWrapper
	except Exception:
		return

	if hasattr(ImageWrapper, "scaled_dimensions"):
		return

	def _compat_image(self):
		image = getattr(self, "_docx_compat_image", None)
		if image is None:
			image = Image.from_blob(self.blob)
			self._docx_compat_image = image
		return image

	@property
	def width(self):
		return _compat_image(self).width

	@property
	def height(self):
		return _compat_image(self).height

	def scaled_dimensions(self, width=None, height=None):
		return _compat_image(self).scaled_dimensions(width, height)

	ImageWrapper.width = width
	ImageWrapper.height = height
	ImageWrapper.scaled_dimensions = scaled_dimensions


_patch_docxcompose_image_wrapper()


Description from AI:
The hook is a runtime monkey patch that makes docxcompose.ImageWrapper conform to the image interface expected by newer python-docx.

ImageWrapper contains image bytes, but it does not implement:

width
height
scaled_dimensions(...)

python-docx assumes those members exist when it reuses image objects during document composition. Without them, rendering fails with:

'ImageWrapper' object has no attribute 'scaled_dimensions'
The patch fixes that by attaching the missing API to ImageWrapper at import time.

Implementation strategy:

lazily build a native python-docx Image from self.blob
cache it on the wrapper instance
delegate width, height, and scaled_dimensions(...) to that native object
So the patch does not change rendering logic.
It only restores interface compatibility between docxcompose and python-docx.

If you want to reuse this in another project, the key requirement is simple:

The patch only needs to run once per Python process, before any code path starts composing Word documents.

The cleanest way is to put it in a module that is imported during application startup.

Recommended options:

  1. Package init.py
    If the report/document package is always imported before rendering, place the patch there and call it at module import time.

Example:

# myproject/reporting/__init__.py

def patch_docxcompose_image_wrapper():
    ...

patch_docxcompose_image_wrapper()

This is the simplest approach if that package is guaranteed to load before document generation.

  1. Application startup hook
    If you want the patch to be more explicit, put it in a dedicated compatibility module and import it from your app bootstrap.

Example:

# myproject/compat/docxcompose_patch.py

def patch_docxcompose_image_wrapper():
    ...

Then call it once at startup:

from myproject.compat.docxcompose_patch import patch_docxcompose_image_wrapper

patch_docxcompose_image_wrapper()

Typical startup locations:

  • FastAPI: app initialization in main.py
  • Flask: app factory
  • Django: AppConfig.ready()
  • CLI tool: program entrypoint
  • Worker: worker bootstrap code
  1. Dedicated “compat” import side effect
    You can also make a module whose only job is to apply compatibility patches on import:
# myproject/compat/__init__.py
from .docxcompose_patch import patch_docxcompose_image_wrapper

patch_docxcompose_image_wrapper()

Then ensure startup imports:

import myproject.compat

Best practice
Use a dedicated function plus an idempotent guard, like your current version:

if hasattr(ImageWrapper, "scaled_dimensions"):
    return

That makes it safe even if the module is imported multiple times. In practice, Python module loading already prevents repeated execution in the same interpreter, but the guard is still the right design.

Most important rule
Do not place it inside the rendering function itself unless you have to. It is better as a startup-time compatibility patch, because:

  • it runs once
  • it is easy to reason about
  • it keeps rendering code clean
  • it guarantees the environment is patched before third-party code uses it

Short version you can reuse:

Run this patch once at process startup, ideally from a module imported during application bootstrap. A package init.py, app entrypoint, or dedicated compatibility module are all valid places, as long as the patch executes before any docx composition logic runs.

Activity

  1. added
    bug
    on Nov 9, 2026
  2. cvas22 commented on Nov 22, 2026

    @cvas22
    OwnerAuthor

    @MWMWM @sanjass @ahmetmusab42-stack fixed in #172, an inline image and a subdoc that has its own image can be used in the same template now. Thx for the fix!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions