File size: 1,581 Bytes
a872010
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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 %}