Cleanup code, formatting & replaced pdftk stuff by fillpdf & pdfrw2

goodbye external dependencys, this is now python-native code
This commit is contained in:
Dominik Rimpf 2022-05-14 18:46:31 +02:00
parent 048d441cda
commit 5c9de76dc4
3 changed files with 75 additions and 75 deletions

3
.gitignore vendored
View file

@ -1,4 +1 @@
output*.pdf
teilnehmendenliste*.pdf teilnehmendenliste*.pdf
data_fdf.bin

View file

@ -1,25 +1,23 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from fdfgen import forge_fdf
import sh
from math import ceil
import csv import csv
import os
import tempfile
from math import ceil
from operator import itemgetter from operator import itemgetter
from pathlib import Path
from fillpdf import fillpdfs
from pdfrw import PdfReader, PdfWriter
# Change to your needs
event_period = "25.05. - 29.05.22"
event_org = "Verein der Freunde und Förderer der Bundesfachschaftentagung Elektrotechnik e.V."
event_name = "90. Bundesfachschaftentagung Elektrotechnik"
attendees_csv = "teilnehmer_innen.csv"
empty_sheets = 1
template_form = "210705_Teilnehmendenliste_abgestimmt.pdf"
date_list = ["25.05.22", "26.05.22", "27.05.22", "28.05.22", "29.05.22"]
######## Bitte hier Anpassen ########################################## # Nothing to change below here
maßnahmenzeitraum = "25.05. - 29.05.22"
datum="25.05.22"
kif_ev= "Verein der Freunde und Förderer der Bundesfachschaftentagung Elektrotechnik e.V."
maßname="90. Bundesfachschaftentagung Elektrotechnik"
csv_file_name="teilnehmer_innen.csv"
leer_blaetter=1
vorlage = "210705_Teilnehmendenliste_abgestimmt.pdf"
datum_list = ["25.05.22","26.05.22","27.05.22","28.05.22","29.05.22",]
######## Nothing to change below here ##########################################
form_mapping = [("6", "20", "21"), ("19", "40", "41"), ("18", "39", "22"), form_mapping = [("6", "20", "21"), ("19", "40", "41"), ("18", "39", "22"),
("17", "42", "23"), ("16", "43", "24"), ("15", "44", "25"), ("14", "45", "26"), ("17", "42", "23"), ("16", "43", "24"), ("15", "44", "25"), ("14", "45", "26"),
@ -27,77 +25,83 @@ form_mapping = [("6","20","21"),("19","40","41"),("18","39","22"),
("9", "31", "36"), ("8", "32", "37"), ("7", "33", "38")] ("9", "31", "36"), ("8", "32", "37"), ("7", "33", "38")]
def readcsv(csv_file_name): def read_csv(csv_path):
persons = [] persons = []
try: try:
csvfile = open(csv_file_name,newline='') csvfile = open(csv_path, newline='')
except FileNotFoundError: except FileNotFoundError:
print("[X] File {} not found!".format(csv_file_name)) print("[X] File {} not found!".format(csv_path))
exit(-1) exit(-1)
else: else:
with csvfile: with csvfile:
reader = csv.DictReader(csvfile, delimiter=",") 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 = [{"Name": f"{t['Vorname']} {t['Nachname']}", "Hochschule": f"{t['Standort']}"} for t in reader if
t['Status'] == "Student"]
persons.sort(key=itemgetter("Hochschule", "Name")) persons.sort(key=itemgetter("Hochschule", "Name"))
return persons return persons
def generate_pdfs(persons, maßnahmenzeitraum, datum, kif_ev, maßname, leer_blaetter): def fill_pdf_form(working_directory, form, persons, zeitraum, form_date, org_name, name, add_sheets):
seite = 1 page = 1
data_file="data_fdf.bin"
output_file_name = "output" output_file_name = "output"
personen_pro_seite = 14 personen_pro_seite = 14
#check if vorlage exits
test_file = Path(vorlage)
if not test_file.is_file():
print("[X] File {} not found!".format(vorlage))
exit(-1)
anzahl_seiten = ceil(len(persons) / personen_pro_seite) anzahl_seiten = ceil(len(persons) / personen_pro_seite)
pdfs = [] pdfs = []
for j in range(anzahl_seiten+leer_blaetter): for j in range(anzahl_seiten + add_sheets):
felder = [] felder = {}
i = 0 i = 0
for item in form_mapping: for item in form_mapping:
if personen_pro_seite * j + i < len(persons): if personen_pro_seite * j + i < len(persons):
felder.append((item[0],str(j*personen_pro_seite+i+1))) felder[item[0]] = str(j * personen_pro_seite + i + 1)
felder.append((item[1], persons[j*personen_pro_seite+i]["Name"])) felder[item[1]] = persons[j * personen_pro_seite + i]["Name"]
felder.append((item[2], persons[j*personen_pro_seite+i]["Hochschule"])) felder[item[2]] = persons[j * personen_pro_seite + i]["Hochschule"]
i += 1 i += 1
if i == personen_pro_seite: if i == personen_pro_seite:
output_file = output_file_name + str(seite) +".pdf" output_file_path = os.path.join(working_directory, f'{output_file_name}{page}.pdf')
headers = [("1", seite), ("2", maßnahmenzeitraum), ("3", datum), ("4", kif_ev), ("5", maßname)] headers = {"1": page, "2": zeitraum, "3": form_date, "4": org_name, "5": name}
fields = felder + headers fields = {**headers, **felder}
fdf = forge_fdf("",fields,[],[],[])
fdf_file = open(data_file,"wb")
fdf_file.write(fdf)
fdf_file.close()
sh.pdftk(vorlage,"fill_form", data_file,"output",output_file,"flatten")
pdfs.append(output_file)
seite+=1
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 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
writer.write(output_pdf)
if __name__ == "__main__": if __name__ == "__main__":
person_list = readcsv(csv_file_name) workdir = tempfile.mkdtemp()
for datum in datum_list: cwd = os.getcwd()
final_pdf_name = "teilnehmendenliste_{}.pdf".format(datum.replace(". ", "_")) csv_file_path = os.path.join(cwd, attendees_csv)
output_files = generate_pdfs(person_list, maßnahmenzeitraum, datum, kif_ev, maßname, leer_blaetter) person_list = read_csv(csv_file_path)
sh.pdftk(output_files, "cat","output",final_pdf_name ) 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)
for date in date_list:
final_pdf_name = f'teilnehmendenliste_{date.replace(". ", "_")}.pdf'
print(f'Creating {final_pdf_name}... ', end='')
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('done!')

View file

@ -1,3 +1,2 @@
fdfgen fillpdf~=0.7.1
sh pdfrw2~=0.5.0
pathlib