-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainProg.py
902 lines (788 loc) · 40 KB
/
MainProg.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
# python3
# coding: utf-8
# import threading
import openpyxl as px
import pandas as pd
from helper_Word import helper_Word
from Docx_to_pdf import Docx_to_PDF
from PDF_Combiner import Combine_PDF
from shutil import copyfile
import os
import subprocess
# from collections import OrderedDict
import time
import json_helper
# import Excel_to_Word_in_arbeit
# from helper_Word import helper_Word as hw
__version__ = "0.0.19"
__author__ = "Stefan Holstein"
__repo__ = r"https://github.com/StefanHol/SchoolReport_Excel2Word2PDF"
__config_json__ = "config.json"
__Anleitung__ = "README.pdf"
# rebuild_GUI = True
rebuild_GUI = False
# # ToDo: Add certificate
# # Could not find a suitable TLS CA certificate bundle, invalid path
# # https://github.com/pyinstaller/pyinstaller/issues/6352
used_Qt_Version = 0
try:
from PyQt5.QtWidgets import QMainWindow, QInputDialog, QMessageBox
from PyQt5.QtWidgets import QWidget, QComboBox, QCheckBox, QLineEdit, QFileDialog, QTableWidgetItem
from PyQt5.QtGui import QFont, QIcon, QPixmap
from PyQt5.QtWidgets import QTableView, QAbstractItemView, QCompleter, QLineEdit, QHeaderView
from PyQt5.QtCore import QAbstractTableModel, Qt, QSize
used_Qt_Version = 5
except Exception as e:
print(e)
exit()
pass
def compile_GUI():
if used_Qt_Version == 4:
print("Compile QUI for Qt Version: " + str(used_Qt_Version))
os.system("pyuic4 -o GUI\Converter_ui.py GUI\Converter.ui")
elif used_Qt_Version == 5:
print("Compile QUI for Qt Version: " + str(used_Qt_Version))
os.system("pyuic5 -o GUI\Converter_ui.py GUI\Converter.ui")
if rebuild_GUI:
compile_GUI()
from GUI.Converter_ui import Ui_MainWindow
import logging
logging.basicConfig(level=logging.INFO)
# logging level
# ERROR: 40
# WARNING: 30
# INFO: 20
# DEBUG: 10
class PandasModel(QAbstractTableModel):
"""
Class to populate a table view with a pandas dataframe
https://stackoverflow.com/questions/31475965/fastest-way-to-populate-qtableview-from-pandas-data-frame
"""
def __init__(self, data, parent=None):
QAbstractTableModel.__init__(self, parent)
self._data = data
logger = logging.getLogger(__name__)
logger.debug("init Pandas Model")
def rowCount(self, parent=None):
return self._data.shape[0]
def columnCount(self, parent=None):
return self._data.shape[1]
def data(self, index, role=Qt.DisplayRole):
if index.isValid():
if role == Qt.DisplayRole:
return str(self._data.iloc[index.row(), index.column()])
return None
def headerData(self, col, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self._data.columns[col]
return None
class create_letter_of_reference():
def __init__(self):
self.logger = logging.getLogger("SR_E2W2P.create_letter_of_reference")
self.logger.info("init create_letter_of_reference")
self.Array_CheckBox_Namen = None
self.Text_Feld_Namen = None
self.wb = None
self.df = None
self.srcFileName = ""
self.destination_Folder = ""
self.Excel_Filename = ""
self.wichtige_meldung = ""
def read_word_information_fields(self, srcFileName):
self.srcFileName = srcFileName
self.logger.info("read_word_information_fields")
word_doc = helper_Word()
word_doc.init_file(srcFileName, False)
self.logger.info("get_all_fieldnames_from_word")
word_doc.get_all_fieldnames_from_word()
self.logger.info("find_arrays_and_text_field_names")
word_doc.find_arrays_and_text_field_names()
self.logger.info("find_arrays_and_text_field_names: done")
self.Array_CheckBox_Namen = word_doc.Text_FieldArray_Row_Names
self.Text_Feld_Namen = word_doc.Text_Field_Names
self.logger.info("Array_CheckBox_Namen:")
self.logger.info(self.Array_CheckBox_Namen)
self.logger.info("Text_Feld_Namen:")
self.logger.info(self.Text_Feld_Namen)
try:
word_doc.doc.Close()
self.logger.info("Word Document Closed")
except Exception as e:
self.logger.error(e)
return self.Array_CheckBox_Namen, self.Text_Feld_Namen
def read_excel_file_to_pandas(self, Excel_Filename):
self.logger.debug("read_excel_file_to_pandas")
# print("Excel_Filename")
self.Excel_Filename = Excel_Filename
# print("self.Excel_Filename: ", self.Excel_Filename)
self.wb = px.load_workbook(self.Excel_Filename, data_only=True)
self.logger.info("loaded Excel File: {}".format(Excel_Filename))
self.logger.info("Array_CheckBox_Namen\n{}".format(self.Array_CheckBox_Namen))
self.df = self.create_dataframe_for_InputFields(self.Array_CheckBox_Namen, self.Text_Feld_Namen)
# print("self.df", self.df)
self.df = self.remove_empty_data(self.df)
self.logger.debug("self.df {}".format(self.df))
return self.df
def get_values_By_range_name(self, range_name):
value_array = []
self.logger.debug("check: {}".format(range_name))
try:
address = list(self.wb.defined_names[range_name].destinations)
# address
for sheetname, cellAddress in address:
cellAddress = cellAddress.replace('$', '')
cellAddress
worksheet = self.wb[sheetname]
for i in range(0, len(worksheet[cellAddress])):
for item in worksheet[cellAddress][i]:
# print(item.value)
value_array.append(item.value)
except Exception as e:
self.logger.error("Error: Textfeld {} ist in Worddokument definiert,".format(range_name) +
"kann aber nicht im Exceldokument gefunden werden.\n{}".format(e))
self.wichtige_meldung = ("Warnung: Textfeld {} ist in Worddokument definiert,".format(range_name) +
"kann aber nicht im Exceldokument gefunden werden.\n{}\n".format(e) +
"Vorlagen überprüfen!\nDie entsprechenden Daten werden nicht übertragen.\n")
return value_array
def create_folder_if_not_exist(self, folder):
if not os.path.exists(folder):
os.mkdir(folder)
def ExtractFileName(self, mypath):
name = mypath.split(os.path.sep)
return name[len(name) - 1]
def zahl_zu_bewertung(self, value):
if str(value) == "1":
return "sehr gut"
if str(value) == "2":
return "gut"
if str(value) == "3":
return "schlecht"
if str(value) == "4":
return "sehr schlecht"
def Copy_word_file_and_write_data(self, df, targetname, df_index):
# copy File and create target file object
self.create_folder_if_not_exist(self.destination_Folder)
FileName = self.srcFileName.replace(".docx", "_-_" + (df["Name"].iloc[df_index]).replace(" ", "_") + ".docx")
FileName = self.ExtractFileName(
self.srcFileName.replace(".docx", "_-_" + (df["Name"].iloc[df_index]).replace(" ", "_") + ".docx"))
# dstFileName = srcFileName.replace(".docx", "_-_" + (df["Name"].iloc[df_index]).replace(" ", "_") + ".docx")
logging.info(FileName)
dstFileName = self.destination_Folder + os.path.sep + FileName
# print(srcFileName,"\n"+ dstFileName)
copyfile(self.srcFileName, dstFileName)
# wordFile.doc.Close()
wordFile = helper_Word()
wordFile.init_file(dstFileName, False)
self.logger.info(FileName)
for ColumnName in df:
# print(df["Name"].iloc[df_index], ":\t",ColumnName , "\t", df[ColumnName].iloc[df_index])
# ToDo: Call Input Function here
SchuelerName = df["Name"].iloc[df_index]
ZellenNameOderArray = ColumnName
Cellen_Oder_Array_Wert = df[ColumnName].iloc[df_index]
self.logger.info("Name: {} \t {} \t {}".format(SchuelerName, ColumnName, Cellen_Oder_Array_Wert))
# ToDo: Call Input Function here
try:
counter = 0
for TextElement in self.Text_Feld_Namen:
# print(counter)
# print(TextElement)
counter += 1
outputText = df[TextElement].iloc[df_index]
try:
try:
self.logger.info("int: TextElement {} {}".format(TextElement, int(outputText)))
outputText = int(outputText)
except Exception as e:
self.logger.info("str: TextElement {} {}".format(TextElement, str(outputText)))
outputText = str(outputText)
# print(e, str(outputText), str(TextElement))
wordFile.set_WordField_Text(TextElement, str(outputText))
self.logger.info("TextElement {} {}".format(TextElement, wordFile.get_WordField_Text(TextElement)))
except Exception as e:
self.logger.debug("{} {} {}".format(e, str(outputText), str(TextElement)))
# print(e, str(outputText), str(TextElement))
counter = 0
for ArrayElement in self.Array_CheckBox_Namen:
# print(counter)
counter += 1
outputText = df[ArrayElement].iloc[df_index]
#########################################################################
# Noten CheckBox und Text
# korrigieren
#########################################################################
SetCheckBox = False
realerror = True
error_message = ""
try:
outputText = int(outputText)
self.logger.debug("int: ArrayElement {} {}".format(outputText, ArrayElement))
self.logger.debug(str(ArrayElement) + " = " + self.zahl_zu_bewertung(outputText))
realerror = False
except Exception as e:
try:
outputText = str(outputText)
self.logger.debug("str: ArrayElement {} {}".format(outputText, ArrayElement))
self.logger.debug(str(ArrayElement) + " = " + self.zahl_zu_bewertung(outputText))
realerror = False
except Exception as e:
realerror = True
self.logger.debug("{} try of try outputText: {} {}".format(e, ArrayElement, outputText))
error_message = "{}: try of try outputText: {}, {}".format(e, ArrayElement, outputText)
# print(e, ArrayElement, outputText)
pass
try:
if not (outputText is None):
CheckBox = ArrayElement + str(outputText - 1)
SetCheckBox = True
realerror = False
else:
self.logger.debug("Skip Checkbox: {} {}".format(outputText, ArrayElement))
pass
except Exception as e:
realerror = True
self.logger.debug("tryexcept 2: {} {} {}".format(e, outputText, ArrayElement))
error_message = "warning: nichts in checkbox eingetragen {}, {}, {}".format(e, outputText,
ArrayElement)
SetCheckBox = False
# print(CheckBox)
if SetCheckBox:
realerror = False
wordFile.check_checkbox(CheckBox)
# save & close target file here
if realerror:
self.logger.debug("Hinweis: {}".format(error_message))
except Exception as e:
self.logger.error("Fehler hier: {}".format(e))
finally:
try:
wordFile.save_and_close()
except Exception as e:
print(e)
return FileName
def create_wordDocxs_from_dataframe(self, df):
# print(df.head())
if True:
start_time = time.time()
file_name_list = []
for index in range(len(df)):
# print(index)
# #ToDo: Call Input Function here
self.logger.debug(str(df["Name"].iloc[index]))
file_name = self.Copy_word_file_and_write_data(df, df["Name"].iloc[index], index)
file_name_list.append(file_name)
if True:
self.logger.info("Creation takes %.2f seconds" % (time.time() - start_time))
# print("create_wordDocxs_from_dataframe", file_name_list)
return file_name_list
def create_dataframe_for_InputFields(self, Array_CheckBox_Namen, Text_Feld_Namen):
self.logger.debug("create_dataframe_for_InputFields")
df = pd.DataFrame({})
# df.to_excel("tempout.xlsx")
# df.to_csv("tempout.csv", index=False, header=True)
self.logger.info("Text_Feld_Namen\n{}".format(Text_Feld_Namen))
for index, HeaderName in enumerate(Text_Feld_Namen):
# print(index, HeaderName)
if index == 0:
# print(HeaderName)
# print(HeaderName, self.get_values_By_range_name(HeaderName),
# len(self.get_values_By_range_name(HeaderName)))
try:
df = pd.DataFrame(self.get_values_By_range_name(HeaderName), columns=[HeaderName])
except Exception as e:
self.logger.error("create_dataframe_for_InputFields_1 {}".format(e))
# df = pd.DataFrame.from_dict([(HeaderName, self.get_values_By_range_name(HeaderName))])
# print(HeaderName, len(df))
else:
self.logger.debug("{}, {}, {}".format(HeaderName, str(self.get_values_By_range_name(HeaderName)),
len(self.get_values_By_range_name(HeaderName))))
try:
se = pd.Series(self.get_values_By_range_name(HeaderName))
# print(HeaderName ,len(df), len(se))
df[HeaderName] = se.values
except Exception as e:
self.logger.error("create_dataframe_for_InputFields_2 {}".format(e))
# print(df.head())
#
# df.to_excel("tempout.xlsx")
for index, HeaderName in enumerate(Array_CheckBox_Namen):
# if index ==0:
# print(HeaderName)
# df = pd.DataFrame.from_items([(HeaderName, get_values_By_range_name(HeaderName))])
# print(HeaderName, len(df))
# else:
try:
# print(index, HeaderName)
se = pd.Series(self.get_values_By_range_name(HeaderName))
self.logger.debug("HeaderName: {} len(df): {} len(se): {}".format(HeaderName, len(df), len(se)))
df[HeaderName] = se.values
except Exception as e:
self.logger.debug("checkbox not found: {}".format(e))
self.logger.debug("{} {}".format(index, HeaderName))
# print("end for loop Array_CheckBox_Namen")
return df
def remove_empty_data(self, df):
Empty_List = df.loc[df['Name'].isin([None])].index.tolist()
df.drop(df.index[Empty_List], inplace=True)
df = df.reset_index(drop=True)
return df
class MainProg(QMainWindow):
"""Scanstation GUI"""
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.logger = logging.getLogger("SR_E2W2P.MainProg")
self.logger.info("init MainProg")
# load default json config if not existing
self.check_or_create_default_json_config()
self.config_information = json_helper.read_json_file(__config_json__)
self.logger.debug(self.config_information)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.work_folder = self.config_information.get("dokumenten_start_ordner")
self.converter = Docx_to_PDF()
self.creator_class = create_letter_of_reference()
self.output_pdf_folder = ""
self.auto_pdf_folder = self.config_information.get("Autotomatisch_PDF_Ordner_anlegen")
self.ui.actionAutomatisch_PDF_Ordner_anlegen.setChecked(self.auto_pdf_folder)
self.ui.pushButton_PDF_Folder.setEnabled(not self.auto_pdf_folder)
self.word_selected = False
self.excel_selected = False
self.output_selected = False
self.pdf_output_selected = False
self.ui.pushButton_Zeugnisvorlage.clicked.connect(self.select_new_Word_Template_File)
self.ui.pushButton_Excel_Zeugnisse.clicked.connect(self.select_Excel_Zeugnis_File)
self.ui.pushButton_Ausgabe_Ordner.clicked.connect(self.select_output_folder)
self.ui.pushButton_OpenOutputFolder.clicked.connect(self.open_output_folder)
self.ui.pushButton_OpenPDFOutputFolder.clicked.connect(self.open_PDF_output_folder)
self.ui.pushButton_create_only_selected_docx.clicked.connect(self.create_single_selected_reference_word)
self.ui.pushButton_create_only_selected_docx_pdf.clicked.connect(
self.create_single_selected_reference_word_and_pdf)
self.ui.pushButton_create_all_docx.clicked.connect(self.create_all_references_word)
self.ui.pushButton_create_all_docx_pdf.clicked.connect(self.create_all_references_word_and_pdf)
self.ui.pushButton_Dummy.clicked.connect(self.dummy)
self.ui.pushButton_combine_pdfs.clicked.connect(self.combine_all_PDFs_in_selected_output_folder)
self.ui.pushButton_convert_all_docx_to_pdf.clicked.connect(self.convert_all_docx_to_pdf)
self.ui.pushButton_convert_selected_docx_to_pdf.clicked.connect(self.convert_selected_docx_to_pdf)
self.ui.pushButton_PDF_Folder.clicked.connect(self.select_PDF_folder)
self.ui.pushButton_go.clicked.connect(self.run_go_button)
self.ui.actionSet_search_folder.triggered.connect(self.set_dokument_search_folder)
self.ui.actionAutomatisch_PDF_Ordner_anlegen.triggered.connect(self.Toggle_actionAutomatisch_PDF_Ordner_anlegen)
self.ui.actionAnleitung_oeffnen.triggered.connect(self.Anleitung_oeffnen)
self.ui.actionkill_winword.triggered.connect(self.kill_winword)
self.ui.actionAbout.triggered.connect(self.show_about)
self.ui.tabWidget.removeTab(2)
self.ui.tabWidget.removeTab(1)
# tabtohide = self.ui.tabWidget.ta
# hiddenindex = self.ui.tabWidget.indexOf()
# Dummy Button en- / disable
self.ui.pushButton_Dummy.setHidden(True)
# self.ui.pushButton_Dummy.setHidden(False)
# self.ui.pushButton_Dummy.setEnabled(True)
self.ui.pushButton_create_only_selected_docx.setHidden(True)
self.ui.pushButton_create_only_selected_docx_pdf.setHidden(True)
self.ui.pushButton_create_all_docx.setHidden(True)
self.ui.pushButton_create_all_docx_pdf.setHidden(True)
self.ui.pushButton_combine_pdfs.setHidden(True)
self.ui.pushButton_convert_all_docx_to_pdf.setHidden(True)
self.ui.pushButton_convert_selected_docx_to_pdf.setHidden(True)
# add banner image
banner_name = "img" + os.path.sep + "Logo.png"
banner_path = os.path.dirname(__file__) + os.path.sep + banner_name
self.pixmap = QPixmap(banner_path)
# self.pixmap = self.pixmap.scaledToWidth(300)
self.ui.banner.setPixmap(self.pixmap)
self.ui.banner.setScaledContents(True)
# Dummy Data
data = ([["Name 1", "Demo Daten", "Demo Daten", "Demo Daten", "Demo Daten"],
["Name 2", "Demo Daten", "Demo Daten", "Demo Daten", "Demo Daten"],
["Name 3", "Demo Daten", "Demo Daten", "Demo Daten", "Demo Daten"]])
your_pandas_data = pd.DataFrame(data)
your_pandas_data.columns = ['Name', 'Spalte 1', 'Spalte 2', 'Spalte 3', 'Spalte 4']
TableModel = PandasModel(your_pandas_data)
self.ui.tableView.setModel(TableModel)
def check_or_create_default_json_config(self):
if not os.path.isfile(__config_json__):
data = {
"dokumenten_start_ordner": r"C:\work\Excel2Word2PDF_SchoolReport\Demo",
"logging_level": "Debug",
"Autotomatisch_PDF_Ordner_anlegen": True
}
json_helper.write_json_file(__config_json__, data)
def write_json_config_information(self):
json_helper.write_json_file(__config_json__, self.config_information)
def select_output_folder(self):
dialog = QFileDialog()
dialog.setFileMode(QFileDialog.FileMode())
self.output_folder = dialog.getExistingDirectory(None, 'Wähle einen leeren Ausgabeordner', self.work_folder)
temp = str(self.output_folder.replace('/', os.path.sep))
selected = False
if os.path.exists(temp):
self.output_folder = temp
self.logger.debug(self.output_folder)
selected = True
if selected:
self.ui.lineEdit_ZeugnisAusgabe.setText(self.output_folder)
self.creator_class.destination_Folder = self.output_folder
self.output_selected = True
self.enable_buttons()
if self.auto_pdf_folder:
self.set_PDF_Folder(self.output_folder + os.path.sep + "_PDF_")
self.enable_buttons()
def open_output_folder(self):
self.logger.debug("open_output_folder")
# Open Script File Location
self.logger.debug('open =', self.output_folder)
subprocess.Popen(r'explorer ' + self.output_folder)
def open_PDF_output_folder(self):
self.logger.debug("open_PDF_output_folder")
# Open Script File Location
self.logger.debug('open =', self.output_pdf_folder)
subprocess.Popen(r'explorer ' + self.output_pdf_folder)
def select_PDF_folder(self):
dialog = QFileDialog()
dialog.setFileMode(QFileDialog.FileMode())
folder = dialog.getExistingDirectory(None, 'Wähle den PDF Ausgabeordner', self.work_folder)
folder = str(folder.replace('/', os.path.sep))
if os.path.exists(folder):
self.logger.info("PDF_folder: {}".format(folder))
selected = True
self.set_PDF_Folder(folder)
def set_PDF_Folder(self, folder):
self.output_pdf_folder = folder
self.creator_class.create_folder_if_not_exist(self.output_pdf_folder)
self.ui.lineEdit_PDF_output.setText(self.output_pdf_folder)
self.pdf_output_selected = True
self.enable_buttons()
def run_go_button(self) -> None:
if self.ui.radioButton_create_only_selected_docx.isChecked():
self.create_single_selected_reference_word()
elif self.ui.radioButton_create_only_selected_docx_pdf.isChecked():
self.create_single_selected_reference_word_and_pdf()
elif self.ui.radioButton_create_all_docx.isChecked():
self.create_all_references_word()
elif self.ui.radioButton_create_all_docx_pdf.isChecked():
self.create_all_references_word_and_pdf()
elif self.ui.radioButton_combine_pdfs.isChecked():
self.combine_all_PDFs_in_selected_output_folder()
elif self.ui.radioButton_convert_all_docx_to_pdf.isChecked():
self.convert_all_docx_to_pdf()
elif self.ui.radioButton_convert_selected_docx_to_pdf.isChecked():
self.convert_selected_docx_to_pdf()
def enable_buttons(self):
if self.word_selected and not self.excel_selected:
self.ui.pushButton_Excel_Zeugnisse.setEnabled(True)
if self.excel_selected and self.word_selected:
self.ui.pushButton_Ausgabe_Ordner.setEnabled(True)
if self.excel_selected and self.word_selected and self.output_selected:
self.ui.pushButton_create_only_selected_docx.setEnabled(True)
self.ui.pushButton_create_all_docx.setEnabled(True)
# radio buttons
self.ui.radioButton_create_only_selected_docx.setEnabled(True)
self.ui.radioButton_create_all_docx.setEnabled(True)
self.ui.pushButton_go.setEnabled(True)
if self.excel_selected and self.word_selected and self.output_selected and self.pdf_output_selected:
self.ui.pushButton_create_only_selected_docx.setEnabled(True)
self.ui.pushButton_create_only_selected_docx_pdf.setEnabled(True)
self.ui.pushButton_create_all_docx.setEnabled(True)
self.ui.pushButton_create_all_docx_pdf.setEnabled(True)
self.ui.pushButton_convert_all_docx_to_pdf.setEnabled(True)
self.ui.pushButton_combine_pdfs.setEnabled(True)
# radio buttons
self.ui.radioButton_create_only_selected_docx.setEnabled(True)
self.ui.radioButton_create_only_selected_docx_pdf.setEnabled(True)
self.ui.radioButton_create_all_docx.setEnabled(True)
self.ui.radioButton_create_all_docx_pdf.setEnabled(True)
self.ui.radioButton_convert_all_docx_to_pdf.setEnabled(True)
self.ui.radioButton_combine_pdfs.setEnabled(True)
self.ui.pushButton_go.setEnabled(True)
if self.output_selected:
self.ui.pushButton_OpenOutputFolder.setEnabled(True)
self.ui.pushButton_convert_selected_docx_to_pdf.setEnabled(True)
self.ui.pushButton_convert_all_docx_to_pdf.setEnabled(True)
self.ui.pushButton_combine_pdfs.setEnabled(True)
# radio buttons
self.ui.radioButton_convert_selected_docx_to_pdf.setEnabled(True)
self.ui.radioButton_convert_all_docx_to_pdf.setEnabled(True)
self.ui.radioButton_combine_pdfs.setEnabled(True)
self.ui.pushButton_go.setEnabled(True)
if self.pdf_output_selected:
self.ui.pushButton_OpenPDFOutputFolder.setEnabled(True)
self.ui.pushButton_combine_pdfs.setEnabled(True)
self.ui.radioButton_combine_pdfs.setEnabled(True)
self.ui.pushButton_go.setEnabled(True)
def set_dokument_search_folder(self):
dialog = QFileDialog()
dialog.setFileMode(QFileDialog.FileMode())
temp = dialog.getExistingDirectory(None, 'Wähle deinen haupt Dokumentenordner', self.work_folder)
temp = str(temp.replace('/', os.path.sep))
self.work_folder = temp
self.config_information["dokumenten_start_ordner"] = self.work_folder
self.logger.info(self.config_information)
json_helper.write_json_file(__config_json__, self.config_information)
def select_new_Word_Template_File(self):
# ToDo: Inputfile
# ToDo: filter richtig setzen nur *.docx anzeigen
self.srcFileName = ""
dialog = QFileDialog()
dialog.setFileMode(QFileDialog.FileMode())
selected = False
try:
filter = "Office File (*.docx)"
word_template = dialog.getOpenFileName(self, 'Wähle die Zeugnis Vorlage *.docx', self.work_folder, filter,
"*.docx")
word_template = str(word_template[0].replace('/', os.path.sep))
self.srcFileName = word_template
if os.path.exists(self.srcFileName):
self.Array_CheckBox_Namen, self.Text_Feld_Namen = self.creator_class.read_word_information_fields(
self.srcFileName)
selected = True
else:
self.logger.debug("kein Word Dokument gewählt")
except Exception as e:
self.logger.info("select_new_Word_Template_File: {}".format(str(e)))
# print("select_new_Word_Template_File" + str(e))
if selected:
self.word_selected = True
self.logger.info(self.srcFileName)
self.ui.lineEdit_Zeugnisvorlage.setText(str(self.srcFileName))
# ToDo: reactivate
self.logger.info("{}\n{}".format(str(self.Text_Feld_Namen), str(self.Array_CheckBox_Namen)))
self.ui.pushButton_Excel_Zeugnisse.setEnabled(True)
self.enable_buttons()
self.creator_class.wichtige_meldung = ""
def select_Excel_Zeugnis_File(self):
# ToDo: filter richtig setzen nur *.xlsx anzeigen
self.Excel_Filename = ""
selected = False
dialog = QFileDialog()
dialog.setFileMode(QFileDialog.FileMode())
try:
filter = "Office Excel File (*.xlsx)"
excel_file = dialog.getOpenFileName(None, 'Wähle die Excle Zeugnis Datei', self.work_folder, filter,
"*.xlsx")
excel_file = str(excel_file[0].replace('/', os.path.sep))
if os.path.exists(excel_file):
self.Excel_Filename = excel_file
selected = True
except Exception as e:
self.logger.error(e)
if selected:
self.logger.info(self.Excel_Filename)
self.ui.lineEdit_Zeugnisse_xlsx.setText(self.Excel_Filename)
self.creator_class.read_excel_file_to_pandas(self.Excel_Filename)
# print(self.creator_class.df)
self.excel_selected = True
# self.enable_buttons()
self.pandas_to_tableview(self.creator_class.df)
# self.ui.pushButton_Ausgabe_Ordner.setEnabled(True)
if not self.creator_class.wichtige_meldung == "":
self.critical_messagebox("Critical", self.creator_class.wichtige_meldung)
def select_word_file(self):
#
dialog = QFileDialog()
dialog.setFileMode(QFileDialog.FileMode())
selected = False
try:
filter = "Office File (*.docx)"
word_file = dialog.getOpenFileName(self, 'Wähle ein Dokument zum Konvertieren *.docx -> pdf', self.output_folder, filter,
"*.docx")
word_file = str(word_file[0].replace('/', os.path.sep))
# self.srcFileName = word_file
if os.path.exists(word_file):
selected = True
else:
self.logger.debug("kein Word Dokument gewählt")
except Exception as e:
self.logger.info("select_new_Word_Template_File: {}".format(str(e)))
# # print("select_new_Word_Template_File" + str(e))
if selected:
return [selected, word_file]
else:
return [selected, ""]
def critical_messagebox(self, title="Title", text="text"):
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
# setting message for Message Box
msg.setText(text)
# setting Message box window title
msg.setWindowTitle(title)
# declaring buttons on Message Box
msg.setIcon(QMessageBox.Critical)
msg.setStandardButtons(QMessageBox.Ok)
# start the app
retval = msg.exec_()
def pandas_to_tableview(self, pandas_data):
self.logger.debug("pandas_to_tableview")
TableModel = PandasModel(pandas_data)
self.ui.tableView.setModel(TableModel)
def getSelecet_Row(self):
row = -1
data = ""
if self.ui.tableView.currentIndex().isValid():
row = self.ui.tableView.currentIndex().row()
data = self.ui.tableView.currentIndex().data()
self.logger.info("row {} data {}".format(row, data))
return row
def create_single_selected_reference_word(self):
self.logger.debug("create_single_selected_reference_word")
row = self.getSelecet_Row()
self.logger.info("row {}".format(row))
word_file_names = []
if not self.creator_class.destination_Folder == "" and \
not self.creator_class.Excel_Filename == "" and \
not self.creator_class.srcFileName == "":
Generate_Data = self.creator_class.df.iloc[[row]].reset_index(drop=True)
word_file_names = self.creator_class.create_wordDocxs_from_dataframe(Generate_Data)
self.logger.info(word_file_names[0])
self.write_infoline(str(word_file_names))
def create_single_selected_reference_word_and_pdf(self):
row = self.getSelecet_Row()
word_file_names = []
if not self.creator_class.destination_Folder == "" and \
not self.creator_class.Excel_Filename == "" and \
not self.creator_class.srcFileName == "":
Generate_Data = self.creator_class.df.iloc[[row]].reset_index(drop=True)
word_file_names = self.creator_class.create_wordDocxs_from_dataframe(Generate_Data)
self.logger.info("create single selected word {}; row {}".format(str(word_file_names), str(row)))
for each in word_file_names:
self.logger.info(each)
infile = self.output_folder + os.path.sep + each
outfile = self.output_pdf_folder + os.path.sep + each.replace(self.converter.FileExtention(each), "pdf")
self.logger.info(outfile)
self.converter.docx_to_pdf(infile, outfile)
self.write_infoline(outfile)
def create_all_references_word(self):
# row = self.getSelecet_Row()
word_file_names = []
if not self.creator_class.destination_Folder == "" and \
not self.creator_class.Excel_Filename == "" and \
not self.creator_class.srcFileName == "":
# Generate_Data = self.creator_class.df.iloc[[row]].reset_index(drop=True)
word_file_names = self.creator_class.create_wordDocxs_from_dataframe(self.creator_class.df)
self.logger.info("create_all_references_word {}".format(str(word_file_names)))
self.write_infoline(str(word_file_names)) # crashed if active
def create_all_references_word_and_pdf(self):
# row = self.getSelecet_Row()
word_file_names = []
if not self.creator_class.destination_Folder == "" and \
not self.creator_class.Excel_Filename == "" and \
not self.creator_class.srcFileName == "":
# Generate_Data = self.creator_class.df.iloc[[row]].reset_index(drop=True)
word_file_names = self.creator_class.create_wordDocxs_from_dataframe(self.creator_class.df)
self.logger.info("create_all_references_word_and_pdf {}".format(str(word_file_names)))
for each in word_file_names:
self.logger.info(each)
infile = self.output_folder + os.path.sep + each
outfile = self.output_pdf_folder + os.path.sep + each.replace(self.converter.FileExtention(each), "pdf")
self.logger.info(outfile)
# self.ui.lineEdit_infoline.setText(str(outfile.split(os.path.sep)[-1]))
self.converter.docx_to_pdf(infile, outfile)
self.write_infoline("Alle Word und PDF-Dokumente erzeugt.")
def convert_all_docx_to_pdf(self):
self.logger.info("convert_all_docx_to_pdf {} {}".format(self.output_folder, self.output_pdf_folder))
converter = Docx_to_PDF()
converter.convert_all_docx_of_inputFolder_to_PDF_in_outputFolder(self.output_folder, self.output_pdf_folder)
self.write_infoline("Alle Word Dokumente zu PDF konvertiert.")
def convert_selected_docx_to_pdf(self):
# Todo:
# 0. Ausgabe Ordner muss definiert sein
# 1. Wähle Datei
# 2. Konvertiere datei in ausgabe ordner
selected, word_file = self.select_word_file()
if selected:
self.logger.info("convert_selected_docx_to_pdf file: {}".format(word_file))
converter = Docx_to_PDF()
converter.convert_selected_docx_file_to_PDF_in_outputFolder(word_file, self.output_pdf_folder)
else:
self.logger.info("convert_selected_docx_to_pdf nothing selected: {}".format(word_file))
def combine_all_PDFs_in_selected_output_folder(self):
PDFOutputName = self.output_pdf_folder + os.path.sep + "Output.pdf"
# self.ui.lineEdit_infoline.setText(PDFOutputName)
self.write_infoline(PDFOutputName)
if os.path.exists(PDFOutputName):
self.logger.debug("lösche PDF: {}".format(str(PDFOutputName)))
os.remove(PDFOutputName)
PDF_combiner = Combine_PDF()
PDF_combiner.PDF_Combiner(self.output_pdf_folder, PDFOutputName)
self.write_infoline("Alle PDFs zu {} zusammengefügt.".format(str(PDFOutputName)))
def Toggle_actionAutomatisch_PDF_Ordner_anlegen(self):
# self.show_hide_channel_buttons
if self.auto_pdf_folder:
self.auto_pdf_folder = False
self.ui.actionAutomatisch_PDF_Ordner_anlegen.setChecked(self.auto_pdf_folder)
self.ui.pushButton_PDF_Folder.setEnabled(not self.auto_pdf_folder)
self.config_information["Autotomatisch_PDF_Ordner_anlegen"] = self.auto_pdf_folder
self.write_json_config_information()
else:
self.auto_pdf_folder = True
self.ui.actionAutomatisch_PDF_Ordner_anlegen.setChecked(self.auto_pdf_folder)
self.ui.pushButton_PDF_Folder.setEnabled(not self.auto_pdf_folder)
self.config_information["Autotomatisch_PDF_Ordner_anlegen"] = self.auto_pdf_folder
self.write_json_config_information()
def show_about(self):
msgBox = QMessageBox()
msgBox.setWindowTitle("About")
msgBox.setWindowIcon(QIcon("Logo.png"))
msgBox_Text = "SchoolReport_Excel2Word2PDF" + "\n" + \
"" + "\n" + \
"Version: " + __version__ + "\n" + \
"Author: " + __author__ + "\n" + \
"Repo: " + __repo__ + "\n"
msgBox.setText(msgBox_Text)
size = 14
# print("font size", size)
new_font = QFont("", size) # , QFont.Bold)
msgBox.setFont(new_font)
msgBox.setStandardButtons(QMessageBox.Ok)
result = msgBox.exec()
def Anleitung_oeffnen(self):
# __Anleitung__
os.startfile(__Anleitung__)
def kill_winword(self):
'''
https://www.instructables.com/Python-Script-to-Stop-Windows-ApplicationsShutdown/
'''
button_reply = QMessageBox.question(self,
"Word beenden?",
"Alle Word Prozesse beenden?\n"
"- Bitte vorher alle offenen Dokumente speichern!\n"
"",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if button_reply == QMessageBox.Yes:
reply = os.system(r"taskkill /f /im winword.exe")
if reply == 0:
self.write_infoline("Der Prozess WINWORD.EXE wurde beendet.")
elif reply == 128:
self.write_infoline("Der Prozess winword.exe wurde nicht gefunden.")
else:
self.write_infoline("Unbekannte Rückmeldung")
else:
# print("Nö", QMessageBox.Yes)
pass
def write_infoline(self, text):
self.ui.lineEdit_infoline.setText(text)
def dummy(self):
# https://stackoverflow.com/questions/37035756/how-to-select-multiple-rows-in-qtableview-using-selectionmodel
# row = self.getSelecet_Row()
# indexes = self.ui.tableView.selectionModel().selectedRows()
# self.logger.info(row, indexes)
# outfile = r"W:\jdsfjkhkdfsfjk\hijfsdhjfdskhk\file.xlsx"
# print(outfile.split(os.path.sep))
# print(outfile.split(os.path.sep)[-1])
# self.ui.lineEdit_infoline.setText(outfile.split(os.path.sep)[-1])
# reply = os.system(r"tasklist")
# print(reply)
# print(type(reply))
converter = Docx_to_PDF()
converter.check_word_running()
# from subprocess import Popen, PIPE
# command = ["tasklist"]
# pipe = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
# pipe.communicate()
# reply = str(pipe.communicate())
# process_to_find = "winword.exe"
# if process_to_find in reply.lower():
# print(process_to_find + " ist drin")
# pass
# else:
# print("kein " + process_to_find)