So I’m having a really annoying issue with django and docxtpl. I have a few placeholders in my document that I’m trying to replace. The placeholders content consists of html content. Im firstly setting this content in a subdoc based on the main doc (which works, the document is being saved and all the content that has been provided in the placeholder is inside of the sub_doc).
Then Im trying to merge it, and here is where it gets really weird. As you can see I’m saving the merged document document.save("end_doc/doc.docx") # Save for local inspection
. For some reason when I open this file it’s empty. But my function returns the document in memory as you can see, in that file there is some content but it’s missing some.
So for example. If my placeholders content has a few elements, such as 5
tags. It only shows 1
tag in the merged file. But in the sub doc it shows every single tag.
Thanks in advance
from docx import Document
from docxtpl import DocxTemplate
from htmldocx import HtmlToDocx
from docx import Document as _Document
def convert_placeholders_to_text_in_doc(document, context, document_name):
document = DocxTemplate(document)
sub_docs = {}
for placeholder, html_content in context.items():
new_parser = HtmlToDocx()
desc_document = _Document()
try:
# Convert HTML to a DOCX subdocument
new_parser.add_html_to_document(html_content, desc_document)
desc_result_path = f"temp_doc/{placeholder}-subdoc.docx"
desc_document.save(desc_result_path)
# Create subdocument for insertion
sub_doc = document.new_subdoc(desc_result_path)
sub_docs[placeholder] = sub_doc
except Exception as e:
raise Exception(f"Error processing placeholder '{placeholder}': {e}")
try:
document.render(sub_docs)
except Exception as e:
raise Exception(f"Error rendering main document: {e}")
document_io = io.BytesIO()
try:
document.save("end_doc/doc.docx") # Save for local inspection
document.save(document_io)
document_io.seek(0)
except Exception as e:
raise Exception(f"Error saving rendered document: {e}")
return ContentFile(document_io.read(), name=document_name)
python version: 3.11.9
docxtpl version: 0.16.6
python-docx version: 0.8.11
htmldocx version: 0.0.6