-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.py
71 lines (54 loc) · 2.03 KB
/
core.py
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from typing import Union
import os
from pathlib import Path
import pandas as pd
from docxtpl import DocxTemplate
from docx2pdf import convert
import fitz
import config
def read_excel_table(file_path: Union[str, Path]) -> pd.DataFrame:
frame = pd.read_excel(file_path, header=None)
return frame
def _render_docx(template_name, context: dict, number: int):
template_path = config.TEMPLATE_PATH / f"{template_name}.docx"
report_template = DocxTemplate(str(template_path))
save_path = config.TEMP_PATH / f"{number}.docx"
report_template.render(context)
report_template.save(save_path)
def _generate_pdf(number: int) -> None:
in_path = config.TEMP_PATH / f"{number}.docx"
out_path = config.TEMP_PATH / f"{number}.pdf"
convert(in_path, out_path, keep_active=True)
_delete_file(in_path)
def _clean_dir(file_dir: Path) -> None:
for file in os.listdir(file_dir):
os.remove(file_dir / file)
def _delete_file(file_path: Union[str, Path]) -> None:
os.remove(file_path)
def _connect_user_pdfs(context: dict, save_path: str) -> None:
new_pdf = fitz.open()
for file in sorted(os.listdir(config.TEMP_PATH)):
path = str(config.TEMP_PATH / file)
if ".pdf" not in path:
_delete_file(path)
continue
pdf = fitz.open(path)
if "3.pdf" not in path:
new_pdf.insert_pdf(pdf)
else:
pdf = fitz.open(path)
report = fitz.open(config.TEMPLATE_PATH / "report.pdf")
pdf.insert_pdf(report)
new_pdf.insert_pdf(pdf)
report.close()
pdf.close()
_delete_file(path)
new_pdf.save(str(save_path + f"/{context['name']}.pdf"))
new_pdf.close()
def process_user(contex: dict, save_path: str) -> None:
template_names = ["performance", "certification", "referral", "report"]
_clean_dir(config.TEMP_PATH)
for num, template in enumerate(template_names):
_render_docx(template, contex, num)
_generate_pdf(num)
_connect_user_pdfs(contex, save_path)