47 lines
1.8 KiB
Python
47 lines
1.8 KiB
Python
from docx import Document
|
|
|
|
def preencher_documento(template_path, output_path, dados):
|
|
# Abrir o documento modelo
|
|
doc = Document(template_path)
|
|
|
|
# Substituir placeholders no texto principal
|
|
for paragraph in doc.paragraphs:
|
|
for placeholder, valor in dados.items():
|
|
if placeholder in paragraph.text:
|
|
paragraph.text = paragraph.text.replace(placeholder, valor)
|
|
|
|
# Substituir placeholders em tabelas (se houver)
|
|
for table in doc.tables:
|
|
for row in table.rows:
|
|
for cell in row.cells:
|
|
for placeholder, valor in dados.items():
|
|
if placeholder in cell.text:
|
|
cell.text = cell.text.replace(placeholder, valor)
|
|
|
|
# Substituir placeholders em caixas de texto (shapes)
|
|
for shape in doc.inline_shapes:
|
|
try:
|
|
if shape.text_frame:
|
|
for placeholder, valor in dados.items():
|
|
for paragraph in shape.text_frame.paragraphs:
|
|
if placeholder in paragraph.text:
|
|
paragraph.text = paragraph.text.replace(placeholder, valor)
|
|
except AttributeError:
|
|
# Caso o shape não tenha texto
|
|
pass
|
|
|
|
# Salvar o documento preenchido
|
|
doc.save(output_path)
|
|
print(f"Documento salvo em: {output_path}")
|
|
|
|
# Exemplo de uso
|
|
dados_exemplo = {
|
|
"{{Filiacao:}}": "João Silva",
|
|
"{{Nome:}}": "Lisboa",
|
|
"{{EstadoCivil}}": "Casado(a)"
|
|
}
|
|
template_path = "C:/Users/garci/OneDrive/Área de Trabalho/Programa PJM/Programa final/Dataset/6_ainqtestemunha.docx"
|
|
output_path = "C:/Users/garci/OneDrive/Área de Trabalho/Programa PJM/Programa final/Dataset/6_ainqtestemunha_Final.docx"
|
|
preencher_documento(template_path, output_path, dados_exemplo)
|
|
|