elapouya / python-docx-template

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

Trying to render in multiple documents and merge #491

Open Lupanbr opened 1 year ago

Lupanbr commented 1 year ago

Hi, Im making a test case trying to merge multiple smaller docx files in a main template trying to follow these instructions: [https://github.com/elapouya/python-docx-template/issues/433](url) However, Im getting this error while trying to open the file output.docx: "Word experienced an error trying to open the file."

Python code:

import io
import os
from docxtpl import DocxTemplate, RichText

def create_document_from_template():
    template_path = "templateParecer.docx"
    output_path = "output.docx"
    templatePrincipal = DocxTemplate(template_path)
    subCabecalho = DocxTemplate(
        os.getcwd()+"\\partesparecer\\CabecalhoParecer.docx")
    subEmenta = DocxTemplate(os.getcwd()+"\\partesparecer\\EmentaParecer.docx")

    cabecalhoStream = adicionaCabecalho(subCabecalho)
    ementaStream = adicionaEmenta(subEmenta)

    subCabecalhoMain = templatePrincipal.new_subdoc(cabecalhoStream)
    subEmentaMain = templatePrincipal.new_subdoc(ementaStream)
    templatePrincipal.render(
        {"name": "João Doe", "cabeçalho": subCabecalhoMain, "ementa": subEmentaMain})
    templatePrincipal.save(output_path)

def adicionaCabecalho(subTemplate):
    context = {"anoSolicitacao": "2023",
               "numeroProjeto": "123", "autorTitulo": "João das Dores"}
    subTemplate.render(context)
    returnStream = io.BytesIO()
    subTemplate.save(returnStream)
    returnStream.seek(0)
    return returnStream

def adicionaEmenta(subTemplate):
    context = {
        "ementaTitulo": "Test Titulo"}
    subTemplate.render(context)
    returnStream = io.BytesIO()
    subTemplate.save(returnStream)
    returnStream.seek(0)
    return returnStream

if __name__ == "__main__":
    create_document_from_template()

templateParecer.docx

{{cabeçalho}}
{{ementa}} 

CabecalhoParecer.docx

PARECER Nº. __________/{{anoSolicitacao}}

PROJETO DE LEI ORDINÁRIA Nº {{numeroProjeto}}

AUTORIA: {{autorTitulo}}

EmentaParecer.docx PROPOSIÇÃO QUE {{ementaTitulo}}

Note: If I remove the , "ementa": subEmentaMain , the code runs correctly and I can open the file with the renderings done in subCabecalhoMain.

Please help !

butuzov commented 1 year ago

I would go with https://pypi.org/project/docxcompose as (IMHO) it is the only viable option for combining a few docx files.

Lupanbr commented 1 year ago

I would go with https://pypi.org/project/docxcompose as (IMHO) it is the only viable option for combining a few docx files.

Didnt know about this, Ill try it , thanks !