refactored code

This commit is contained in:
Dominik Rimpf 2022-05-15 18:51:06 +02:00
parent 5c9de76dc4
commit eb691683f0

View file

@ -1,8 +1,8 @@
#!/usr/bin/env python3
import csv
import os
import sys
import tempfile
from math import ceil
from operator import itemgetter
from fillpdf import fillpdfs
@ -26,82 +26,75 @@ form_mapping = [("6", "20", "21"), ("19", "40", "41"), ("18", "39", "22"),
def read_csv(csv_path):
persons = []
try:
csvfile = open(csv_path, newline='')
except FileNotFoundError:
print("[X] File {} not found!".format(csv_path))
exit(-1)
sys.exit(1)
else:
with csvfile:
reader = csv.DictReader(csvfile, delimiter=",")
persons = [{"Name": f"{t['Vorname']} {t['Nachname']}", "Hochschule": f"{t['Standort']}"} for t in reader if
t['Status'] == "Student"]
persons.sort(key=itemgetter("Hochschule", "Name"))
for idx, p in enumerate(persons):
p["Position"] = str(idx + 1)
return persons
def fill_pdf_form(working_directory, form, persons, zeitraum, form_date, org_name, name, add_sheets):
def fill_template(template_path, persons_list, headers, output_path):
fields = {}
for person, mapping in zip(persons_list, form_mapping):
fields[mapping[0]] = person["Position"]
fields[mapping[1]] = person["Name"]
fields[mapping[2]] = person["Hochschule"]
fields = {**headers, **fields}
fillpdfs.write_fillable_pdf(input_pdf_path=template_path, output_pdf_path=output_path, data_dict=fields,
flatten=True)
def create_pdf(output_pdf, form, persons_chunks, zeitraum, form_date, org_name, name, add_sheets):
page = 1
output_file_name = "output"
personen_pro_seite = 14
anzahl_seiten = ceil(len(persons) / personen_pro_seite)
pdfs = []
for j in range(anzahl_seiten + add_sheets):
felder = {}
i = 0
for item in form_mapping:
if personen_pro_seite * j + i < len(persons):
felder[item[0]] = str(j * personen_pro_seite + i + 1)
felder[item[1]] = persons[j * personen_pro_seite + i]["Name"]
felder[item[2]] = persons[j * personen_pro_seite + i]["Hochschule"]
i += 1
if i == personen_pro_seite:
output_file_path = os.path.join(working_directory, f'{output_file_name}{page}.pdf')
headers = {"1": page, "2": zeitraum, "3": form_date, "4": org_name, "5": name}
fields = {**headers, **felder}
fillpdfs.write_fillable_pdf(input_pdf_path=form, output_pdf_path=output_file_path, data_dict=fields,
flatten=True)
pdfs.append(output_file_path)
page += 1
return pdfs
def concat_pdfs(file_list: list, output_pdf: str):
writer = PdfWriter()
for input_file in file_list:
reader = PdfReader(input_file)
writer.addpages(reader.pages)
writer.trailer.Info = reader.Info
form_reader = PdfReader(template_form)
writer.trailer.Info = form_reader.Info
writer.write(output_pdf)
with tempfile.TemporaryDirectory() as workdir:
for persons_list in persons_chunks + [[] for i in range(add_sheets)]:
output_file_path = os.path.join(workdir, f'{output_file_name}{page}.pdf')
headers = {"1": page, "2": zeitraum, "3": form_date, "4": org_name, "5": name}
fill_template(template_path=form, persons_list=persons_list, headers=headers, output_path=output_file_path)
reader = PdfReader(output_file_path)
writer.addpages(reader.pages)
page += 1
writer.write(output_pdf)
if __name__ == "__main__":
workdir = tempfile.mkdtemp()
cwd = os.getcwd()
csv_file_path = os.path.join(cwd, attendees_csv)
person_list = read_csv(csv_file_path)
form_path = os.path.join(cwd, template_form)
# check if form exits
if not os.path.exists(form_path):
print("[X] File {} not found!".format(form_path))
exit(1)
sys.exit(1)
person_list = read_csv(csv_file_path)
persons_per_page = len(form_mapping)
person_list_per_page = [person_list[i:i + persons_per_page] for i in range(0, len(person_list), persons_per_page)]
for date in date_list:
final_pdf_name = f'teilnehmendenliste_{date.replace(". ", "_")}.pdf'
print(f'Creating {final_pdf_name}... ', end='')
final_pdf_name = f'teilnehmendenliste_{date.replace(".", "_").replace(" ", "")}.pdf'
final_pdf_path = os.path.join(cwd, final_pdf_name)
output_files = fill_pdf_form(workdir, form_path, person_list, event_period, date, event_org, event_name,
empty_sheets)
concat_pdfs(file_list=output_files, output_pdf=final_pdf_path)
print(f'Creating {final_pdf_name}... ', end='')
create_pdf(final_pdf_path, form_path, person_list_per_page, event_period, date, event_org, event_name, empty_sheets)
print('done!')