elapouya / python-docx-template

Use a docx as a jinja2 template
GNU Lesser General Public License v2.1
1.92k stars 378 forks source link

I/O operations on closed file #505

Closed AlirezaM02 closed 11 months ago

AlirezaM02 commented 11 months ago

Rendering (persian, idk if it's related or not) docx template, causes this exception:

Traceback (most recent call last):
  File "/home/alireza-g14/Workspaces/Repoters-test/main.py", line 99, in <module>
    template.render(context)
  File "/venv_location/lib/python3.11/site-packages/docxtpl/template.py", line 368, in render
    xml_src = self.build_xml(context, jinja_env)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/venv_location/lib/python3.11/site-packages/docxtpl/template.py", line 315, in build_xml
    xml = self.render_xml_part(xml, self.docx._part, context, jinja_env)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/venv_location/lib/python3.11/site-packages/docxtpl/template.py", line 239, in render_xml_part
    dst_xml = template.render(context)
              ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/venv_location/lib/python3.11/site-packages/jinja2/environment.py", line 1296, in render
    ctx = self.new_context(dict(*args, **kwargs))
                           ^^^^^^^^^^^^^^^^^^^^^
ValueError: I/O operation on closed file.

Python code used:

template = DocxTemplate("template3.docx")

with open("c.json", "r") as context:
    jsonObj = json.load(context)

for id, item in enumerate(jsonObj["vulnerabilities"][0]["proof"]):
    if item.startswith("imgs"):
        width, height = scale_image(
            input_image_path=jsonObj["vulnerabilities"][0]["proof"][id]
        ) # function that gives width and height.
        jsonObj["vulnerabilities"][0]["proof"][id] = InlineImage(
            template, item, width=Mm(width), height=Mm(height)
        )

template.render(context)

template.save("output3.docx")

Link to template

AlirezaM02 commented 11 months ago

Sorry, stupid typo in the python file i searched two hours to find. 😬😬