bmbf/generate_bmbf_list.py
2024-10-30 09:43:57 +01:00

112 lines
4.1 KiB
Python

#!/usr/bin/env python3
import csv
import datetime
import os
import sys
import tempfile
from operator import itemgetter
from fillpdf import fillpdfs
from pdfrw import PdfReader, PdfWriter
# Change to your needs
start_date = "2024-10-30"
end_date = "2024-11-03"
event_org = "Verein der Freunde und Förderer der Bundesfachschaftentagung Elektrotechnik e.V."
event_name = "95. Bundesfachschaftentagung Elektrotechnik"
attendees_csv = "95_teilnehmer.csv"
empty_sheets = 1
template_form = "Teilnehmendenliste_FR_22_23_final.pdf"
# Nothing to change below here
start = datetime.date.fromisoformat(start_date)
end = datetime.date.fromisoformat(end_date)
event_period = f'{start.strftime("%d.%m")} - {end.strftime("%d.%m.%y")}'
days = int((end - start).days)
date_list = [(start + datetime.timedelta(days=i)).strftime('%d.%m.%y') for i in range(days + 1)]
form_mapping = [("6", "20", "21"), ("19", "40", "41"), ("18", "39", "22"),
("17", "42", "23"), ("16", "43", "24"), ("15", "44", "25"), ("14", "45", "26"),
("13", "46", "27"), ("12", "Text7", "28"), ("11", "29", "34"), ("10", "30", "35"),
("9", "31", "36"), ("8", "32", "37"), ("7", "33", "38")]
def read_csv(csv_path):
try:
csvfile = open(csv_path, newline='')
except FileNotFoundError:
print("[X] File {} not found!".format(csv_path))
sys.exit(1)
else:
with csvfile:
reader = csv.DictReader(csvfile, delimiter=",")
persons = [{"Name": f"{t['Amtlicher Vorname'] if t['Amtlicher Vorname'] else t['Vorname']} {t['Nachname']}", "Hochschule": f"{t['Standort']}"} for t in reader if
t['Status'] == "Immatrikuliert"]
persons.sort(key=itemgetter("Hochschule", "Name"))
for idx, p in enumerate(persons):
p["Position"] = str(idx + 1)
return persons
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"
writer = PdfWriter()
form_reader = PdfReader(template_form)
writer.trailer.Info = form_reader.Info
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__":
cwd = os.getcwd()
csv_file_path = os.path.join(cwd, attendees_csv)
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))
sys.exit(1)
person_list = read_csv(csv_file_path)
if not person_list:
print("CSV file was empty")
sys.exit(0)
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)]
generated_files = []
for date in date_list:
final_pdf_name = f'teilnehmendenliste_{date.replace(".", "_").replace(" ", "")}.pdf'
generated_files.append(final_pdf_name)
final_pdf_path = os.path.join(cwd, final_pdf_name)
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!')