template_maker / fill_doc.py
TheDarkLord69696969's picture
Upload fill_doc.py
a872010
from docx import Document
import os
import sys
def fill_doc(file_path, result_path, variables):
template_document = Document(file_path)
for variable_key, variable_value in variables.items():
for paragraph in template_document.paragraphs:
replace_text_in_paragraph(paragraph, variable_key, variable_value)
for table in template_document.tables:
for col in table.columns:
for cell in col.cells:
for paragraph in cell.paragraphs:
replace_text_in_paragraph(paragraph, variable_key, variable_value)
template_document.save(result_path)
def replace_text_in_paragraph(paragraph, key, value):
if key in paragraph.text:
inline = paragraph.runs
for item in inline:
if key in item.text:
item.text = item.text.replace(key, value)
# {% comment %} '''
# file_path = 'Copy of Last Will and Testament.docx'
# result_path = 'result.docx'
# variables = {
# "{{What is your name?}}": "",
# } {% endcomment %}
sys.modules[__name__] = fill_doc
#os.chdir(r"C:\Users\Prince Raj\Desktop\BOT/")
# file_path = r"C:\Users\Prince Raj\Desktop\BOT\Last Will and Testament.docx"
# assert os.path.isfile(file_path)
# with open(file_path, "r") as f:
# pass
#file_path = r"Last Will and Testament.docx"
# result_path = r"C:\Users\Prince Raj\Desktop\BOT"
#assert os.path.isfile(result_path)
#with open(result_path, "r") as f:
#pass
# {% comment %} fill_doc(file_path, result_path, variables)
# '''
# variables = {} {% endcomment %}