-
Notifications
You must be signed in to change notification settings - Fork 3
/
Luftmensch_ENG.py
4843 lines (4239 loc) · 210 KB
/
Luftmensch_ENG.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
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from PyQt5.QtCore import (pyqtSignal,QThreadPool,pyqtSlot,QRunnable,QObject,Qt)
from PyQt5.QtWidgets import (QApplication, QMainWindow,QLabel,QFileDialog,QAction,
QProgressBar, QPushButton,QMessageBox,QLineEdit,QMenu,
QGraphicsOpacityEffect,QComboBox,QHBoxLayout,QStackedLayout,
QTextEdit,QCheckBox,QVBoxLayout,QWidget,QListView)
from PyQt5.QtGui import (QIcon,QFont,QPixmap,QCursor)
import time
import sys
import os
import getpass
import shutil
import fitz
from win32com import client
from docx import Document
from re import findall
from webbrowser import open as op
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import UnexpectedAlertPresentException
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.chrome.options import Options
import pandas as pd
# You may need to install Pandas's optional dependencies depending on your working environment:
# xlsxwriter, xlrd, openpyxl, BeautifulSoup4, html5lib, lxml
# Use conda install [package name] if you're in a conda environment
from numpy import nan as npnan
from webdriver_manager.chrome import ChromeDriverManager
import json
import subprocess
import requests
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
# os.chdir(r'/Users/lenin/Documents/Python Scripts/Luftmensch')
""" if hasattr(Qt, 'AA_EnableHighDpiScaling'):
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
if hasattr(Qt, 'AA_UseHighDpiPixmaps'):
QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True) """
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
preferences=resource_path('preferences.json')
with open(preferences, 'r') as openfile:
prev_prefs = json.load(openfile)
icon=resource_path('finalicon.ico')
pic=resource_path('check small.png')
logo=resource_path('app name.png')
# Install Ghostscript and look for "bin" folder inside instalation directory.
# Copy all four files to your current working directory et voilà.
# Take these staps only if you're going to compile the file into an .exe.
# If not, just comment the "gs" definition line below.
gs=resource_path('gswin64c.exe')
# ======================================================================
username=getpass.getuser()
years=[str(i) for i in range(2010,2021)]
years.reverse()
months=[str(i) for i in range(1,13)]
for i in range(len(months)):
if len(months[i])==1:
months[i]='0'+months[i]
months.reverse()
choices=['1. Convertir PDF en PDF/A',
'2. Obtener PDF con páginas del mismo tamaño',
'3. Unir varios archivos PDF',
'4. Convertir una o varias imágenes en un solo archivo PDF',
'5. Crear archivo .zip de Requerimientos y Cartas',
'6. Crear archivo .zip de Valores',
'7. Generar archivo de texto para solicitar descarga de LE',
'8. Detalle de FE recibidas',
'9. Detalle de FE emitidas',
'10. Comprimir PDF']
fontOne = QFont("Helvetica", 9)
fontTwo=QFont("Helvetica", 9)
fontThree=QFont('Consolas', 11) #Done message font
fontFive=QFont('Consolas', 11) #Version font
msg_window_style="color: rgb(255, 255, 255); background-color: rgb(69, 70, 77)"
try:
import pyi_splash
# pyi_splash.update_text('UI Loaded ...')
pyi_splash.close()
except:
pass
progressStyle=("QProgressBar {border: 2px solid grey;border-radius: 5px;text-align: center}"
"QProgressBar::chunk {background-color: IndianRed;width: 10px;margin: 1px;}")
buttonStyle01=("QPushButton { background-color: rgb(155, 61, 61 ); color: rgb(255, 255, 255 );}")
buttonStyle02=("QPushButton { background-color: rgb(69, 70, 77); color: rgb(255, 255, 255);}")
comboStyle=("QComboBox {selection-background-color: rgb(69, 70, 77);background-color: rgb(69, 70, 77); color: rgb(255, 255, 255);padding-left:10px}"
"QComboBox QAbstractItemView::item { min-height: 35px; min-width: 50px;}"
"QListView::item { color: white; background-color: rgb(69, 70, 77)}"
"QListView::item:selected { color: white; background-color: IndianRed}")
style01=("QPushButton { background-color: rgb(155, 61, 61 ); color: rgb(255, 255, 255 );}"
"QPushButton:hover { background-color: rgba(155, 61, 61,230) ;color: white;}"
"QPushButton:pressed { background-color: rgb(69, 70, 77) ;color: rgb(255, 255, 255 );}")
style02=("QPushButton { background-color: rgb(69, 70, 77); color: rgb(255, 255, 255);}"
"QPushButton:hover { background-color: rgba(69, 70, 77,230) ;color: white;}"
"QPushButton:pressed { background-color: rgb(155, 61, 61 ); color: rgb(255, 255, 255 );}")
checkboxStyle="QCheckBox {background-color: rgb(155, 61, 61); color: rgb(255, 255, 255);padding-left:10px;}"
textboxStyle='background-color: rgb(69, 70, 77); color: white'
buttonMinHeight=35
# <codecell>
class WorkerSignalsOne(QObject):
alert=pyqtSignal(str)
finished=pyqtSignal(str)
class JobRunnerOne(QRunnable):
signals = WorkerSignalsOne()
def __init__(self,SaveAs,state):
super().__init__()
self.is_killed = False
self.SaveAs=SaveAs
self.state=state
@pyqtSlot()
def is_opened(self):
temp_filename=self.SaveAs[:-4]+' temp.pdf'
if os.path.exists(self.SaveAs) == True:
try:
os.rename(self.SaveAs,temp_filename)
os.rename(temp_filename,self.SaveAs)
return False
except PermissionError:
return True
else:
return False
def run(self):
try:
if self.is_opened() == True:
self.signals.alert.emit('Error2')
else:
done=False
count=0
while not done:
try:
backup=shutil.copy(self.SaveAs,self.SaveAs[:-4]+' sehr witzig.pdf')
done=True
except PermissionError:
print('Permission denied')
count+=1
time.sleep(count)
time.sleep(1)
# ==============================================================
holder=self.SaveAs[:-4]+' sehr witzig.pdf'
subprocess.check_call(["attrib","+H",holder])
# ==============================================================
tempDocx=os.path.join(os.path.dirname(self.SaveAs),'tempword.docx')
documento = Document()
documento.save(tempDocx)
# =======================================
holder=tempDocx
subprocess.check_call(["attrib","+H",holder])
# =======================================
word = client.DispatchEx('Word.Application')
worddoc = word.Documents.Open(tempDocx,ReadOnly = 1)
worddoc.SaveAs(self.SaveAs,FileFormat = 17)
worddoc.Close(True)
word.Quit()
done=False
count=0
while not done:
try:
os.remove(tempDocx)
done=True
except PermissionError:
print('Permission denied')
count+=1
time.sleep(count)
pdf=fitz.open(self.SaveAs)
opened_file=fitz.open(backup)
pdf.insertPDF(opened_file)
opened_file.close()
pdf.deletePage(0)
pdf.saveIncr()
pdf.close()
time.sleep(1)
done=False
count=0
while not done:
try:
os.remove(backup)
done=True
except PermissionError:
print('Permission denied')
count+=1
time.sleep(count)
if self.state==2:
subprocess.Popen([self.SaveAs],shell=True)
time.sleep(1)
self.signals.finished.emit('Done')
except Exception as e:
self.signals.alert.emit(str(e))
def kill(self):
self.is_killed = True
class ActionsOne(QWidget):
def __init__(self):
super().__init__()
self.runner=None
self.title = 'LuftMensch'
self.var1=None
self.initUI()
self.msg1='Ingresa un archivo PDF.'
def initUI(self):
self.h1=QHBoxLayout()
self.h2=QHBoxLayout()
self.v1=QVBoxLayout()
self.v2=QVBoxLayout()
self.buttonTwo = QPushButton('Cargar PDF', self)
self.buttonTwo.clicked.connect(self.openFileNameDialogOne)
self.buttonTwo.setMinimumHeight(buttonMinHeight)
# self.buttonTwo.setMaximumWidth(200)
self.buttonTwo.setStyleSheet(buttonStyle02)
self.buttonTwo.setFont(fontTwo)
self.buttonTwo.setCursor(QCursor(Qt.PointingHandCursor))
self.h1.addWidget(self.buttonTwo,1)
self.myTextBoxOne = QLineEdit(self)
self.myTextBoxOne.setMinimumHeight(buttonMinHeight)
self.myTextBoxOne.setStyleSheet(textboxStyle)
# self.myTextBoxOne.setMaximumWidth(600)
self.myTextBoxOne.setFont(fontTwo)
self.myTextBoxOne.setReadOnly(True)
self.h1.addWidget(self.myTextBoxOne,4)
self.CheckOne = QCheckBox('Abrir de inmediato el documento generado', self)
self.CheckOne.setFont(fontTwo)
self.CheckOne.setMinimumHeight(buttonMinHeight)
# self.CheckOne.setMaximumWidth(800)
self.CheckOne.setStyleSheet(checkboxStyle)
self.CheckOne.setChecked(prev_prefs["1"])
self.v1.addWidget(self.CheckOne)
# self.lineTwo = QLabel('/'*250, self)
# self.lineTwo.setMaximumWidth(800)
# self.v1.addWidget(self.lineTwo)
self.h2.addStretch()
self.start = QPushButton('Ejecutar', self)
self.start.setStyleSheet(buttonStyle01)
# self.start.setFocus()
self.start.setFont(fontOne)
self.start.setMinimumHeight(buttonMinHeight)
self.start.setEnabled(True)
self.start.setCursor(QCursor(Qt.PointingHandCursor))
self.start.clicked.connect(self.started)
self.h2.addWidget(self.start)
# self.h2.addStretch()
self.button = QPushButton('Limpiar', self)
self.button.setStyleSheet(buttonStyle01)
self.button.setFont(fontOne)
self.button.setMinimumHeight(buttonMinHeight)
# self.button.setMinimumWidth(200)
self.button.setEnabled(True)
self.button.setCursor(QCursor(Qt.PointingHandCursor))
self.button.clicked.connect(self.clean)
self.h2.addWidget(self.button)
# self.h2.addStretch()
self.progress = QProgressBar(self)
self.progress.setFormat("")
self.progress.setStyleSheet(progressStyle)
self.progress.setFont(fontOne)
# self.progress.setMaximumWidth(800)
self.progress.setAlignment(Qt.AlignCenter)
self.progress.setValue(0)
self.progress.setMaximum(0)
self.progress.hide()
self.labelTwo = QLabel('', self)
self.labelTwo.setFont(fontThree)
self.labelTwo.setStyleSheet("color: ForestGreen")
self.labelTwo.setAlignment(Qt.AlignCenter)
# self.labelTwo.hide()
self.effect = QGraphicsOpacityEffect(self)
self.pixmap = QPixmap(pic)
self.pixmap = self.pixmap.scaled(50, 50, Qt.KeepAspectRatio,Qt.SmoothTransformation)
self.labelThree = QLabel('', self)
self.labelThree.setAlignment(Qt.AlignCenter)
# self.info.setIcon(QIcon(self.style.standardIcon(QStyle.SP_FileDialogInfoView)))
self.mainLayout = QVBoxLayout()
# self.mainLayout.setSpacing(30)
# self.v1.setSpacing(0)
self.mainLayout.addLayout(self.h1)
self.mainLayout.addLayout(self.v1)
self.mainLayout.addLayout(self.h2)
self.mainLayout.addWidget(self.progress)
self.mainLayout.addWidget(self.labelTwo)
self.mainLayout.addWidget(self.labelThree)
self.setLayout(self.mainLayout)
self.mainLayout.setAlignment(Qt.AlignCenter)
def started(self):
if self.runner is None:
self.start.setEnabled(False)
if self.var1 is not None:
self.labelTwo.setText('')
self.labelThree.hide()
self.progress.show()
self.state = self.CheckOne.checkState()
# prev_prefs["1"]=self.state
self.threadpool = QThreadPool()
self.runner = JobRunnerOne(self.var1,self.state)
self.threadpool.start(self.runner)
try:
self.runner.signals.alert.disconnect(self.alert)
self.runner.signals.finished.disconnect(self.finished)
except TypeError:
self.runner.signals.alert.connect(self.alert)
self.runner.signals.finished.connect(self.finished)
else:
self.runner.signals.alert.connect(self.alert)
self.runner.signals.finished.connect(self.finished)
else:
self.start.setEnabled(True)
self.labelTwo.setText('Intenta de nuevo.')
self.error(self.msg1)
def clean(self):
self.myTextBoxOne.setText(None)
self.var1=None
self.runner=None
self.labelTwo.setText('')
self.labelThree.hide()
self.progress.hide()
def openFileNameDialogOne(self):
fileName = QFileDialog.getOpenFileName(self,"Selecciona tu documento",'',filter="PDF (*.pdf)")
if len(fileName[0])!=0:
self.myTextBoxOne.setText(fileName[0])
self.var1=os.path.abspath(fileName[0])
def alert(self, msg):
if msg=='Error2':
self.error('Cierra el PDF sobre el cual deseas guardar el resultado.')
else:
self.error('Ocurrió un error inesperado: '+msg)
self.clean()
def finished(self, msg):
if msg=='Done':
self.runner=None
self.myTextBoxOne.setText(None)
self.var1=None
self.start.setEnabled(True)
self.labelTwo.setText('¡Listo, ya puedes visualizar tus documentos!')
self.labelThree.show()
self.labelThree.setPixmap(self.pixmap)
self.labelThree.show()
self.progress.hide()
def error(self,errorMsg):
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setWindowTitle(self.title)
msg.setWindowIcon(QIcon(icon))
msg.setText("Error")
msg.setFont(fontTwo)
msg.setStandardButtons(QMessageBox.Ok)
buttonOk = msg.button(QMessageBox.Ok)
buttonOk.setCursor(QCursor(Qt.PointingHandCursor))
buttonOk.setFont(fontOne)
msg.setStyleSheet(msg_window_style)
msg.setInformativeText(errorMsg)
msg.exec_()
self.start.setEnabled(True)
self.runner=None
def instructions(self):
info = QMessageBox()
info.setWindowTitle(choices[0][3:])
info.setWindowIcon(QIcon(icon))
info.setText('''La opción "Compatible con PDF/A" debe encontrarse activa en Microsoft Word. Para activarla, dirígete a:
Archivo -> Guardar como -> PDF -> Opciones''')
info.setFont(fontTwo)
info.setStyleSheet(msg_window_style)
info.setWindowModality(0)
# info.setModal(True)
info.activateWindow()
info.setStandardButtons(QMessageBox.Ok)
buttonOk = info.button(QMessageBox.Ok)
buttonOk.setCursor(QCursor(Qt.PointingHandCursor))
buttonOk.setText('Entendido')
buttonOk.setFont(fontOne)
info.setDefaultButton(QMessageBox.Ok)
info.show()
retval = info.exec_()
# <codecell>
class WorkerSignalsTwo(QObject):
alert=pyqtSignal(str)
finished=pyqtSignal(str)
class JobRunnerTwo(QRunnable):
signals = WorkerSignalsTwo()
def __init__(self,SaveAs,state,PDFA):
super().__init__()
self.is_killed = False
self.SaveAs=SaveAs
self.state=state
self.PDFA=PDFA
@pyqtSlot()
def is_opened(self):
temp_filename=self.SaveAs[:-4]+' temp.pdf'
if os.path.exists(self.SaveAs) == True:
try:
os.rename(self.SaveAs,temp_filename)
os.rename(temp_filename,self.SaveAs)
return False
except PermissionError:
return True
else:
return False
def run(self):
try:
if self.is_opened() == True:
self.signals.alert.emit('Error2')
else:
done=False
count=0
while not done:
try:
backup=shutil.copy(self.SaveAs,self.SaveAs[:-4]+' sehr witzig.pdf')
done=True
except PermissionError:
print('Permission denied')
count+=1
time.sleep(count)
time.sleep(1)
# ==============================================================
holder=self.SaveAs[:-4]+' sehr witzig.pdf'
subprocess.check_call(["attrib","+H",holder])
# ==============================================================
src= fitz.open(backup)
doc = fitz.open()
for ipage in src:
#Some pages, even though having a landscape aspect, are not actually 'landscape',
#just rotated.
#These lines of code take care of the many problems that arise when dealing with
#different page sizes.
if ipage.get_contents() != []:
if ipage.rotation>0:
ipage.setRotation(0)
if ipage.rect.width > ipage.rect.height:
fmt = fitz.PaperRect("a4-l") # landscape if input suggests
else:
fmt = fitz.PaperRect("a4")
page = doc.newPage(width = fmt.width, height = fmt.height)
page.showPDFpage(page.rect, src, ipage.number)
if page.rect.width > page.rect.height:
page.setRotation(90)
src.close()
#-----------------------------------------MINI-LOOP----------------------------------------#
done=False
count=0
while not done:
try:
print(count)
doc.save(backup,deflate=True)
count=5
print('sucess!')
done=True
except RuntimeError:
print('Pymupdf permission denied')
count+=0.1
time.sleep(count)
#-----------------------------------------MINI-LOOP----------------------------------------#
doc.close()
shutil.move(backup,self.SaveAs)
if self.PDFA==2:
done=False
count=0
while not done:
try:
backup=shutil.copy(self.SaveAs,self.SaveAs[:-4]+' sehr witzig.pdf')
done=True
except PermissionError:
print('Permission denied')
count+=1
time.sleep(count)
time.sleep(1)
# ==============================================================
holder=self.SaveAs[:-4]+' sehr witzig.pdf'
subprocess.check_call(["attrib","+H",holder])
# ==============================================================
tempDocx=os.path.join(os.path.dirname(self.SaveAs),'tempword.docx')
documento = Document()
documento.save(tempDocx)
# =======================================
holder=tempDocx
subprocess.check_call(["attrib","+H",holder])
# =======================================
word = client.DispatchEx('Word.Application')
worddoc = word.Documents.Open(tempDocx,ReadOnly = 1)
worddoc.SaveAs(self.SaveAs,FileFormat = 17)
worddoc.Close(True)
word.Quit()
done=False
count=0
while not done:
try:
os.remove(tempDocx)
done=True
except PermissionError:
print('Permission denied')
count+=1
time.sleep(count)
pdf=fitz.open(self.SaveAs)
opened_file=fitz.open(backup)
pdf.insertPDF(opened_file)
opened_file.close()
pdf.deletePage(0)
pdf.saveIncr()
pdf.close()
time.sleep(1)
done=False
count=0
while not done:
try:
os.remove(backup)
done=True
except PermissionError:
print('Permission denied')
count+=1
time.sleep(count)
if self.state==2:
subprocess.Popen([self.SaveAs],shell=True)
time.sleep(1)
self.signals.finished.emit('Done')
except Exception as e:
self.signals.alert.emit(str(e))
def kill(self):
self.is_killed = True
class ActionsTwo(QWidget):
def __init__(self):
super().__init__()
self.runner=None
self.title = 'LuftMensch'
self.var1=None
self.initUI()
self.msg1='Ingresa un archivo PDF.'
def initUI(self):
self.h1=QHBoxLayout()
self.h2=QHBoxLayout()
self.v1=QVBoxLayout()
self.v2=QVBoxLayout()
self.buttonTwo = QPushButton('Cargar PDF', self)
self.buttonTwo.clicked.connect(self.openFileNameDialogOne)
self.buttonTwo.setMinimumHeight(buttonMinHeight)
# self.buttonTwo.setMaximumWidth(200)
self.buttonTwo.setStyleSheet(buttonStyle02)
self.buttonTwo.setFont(fontTwo)
self.buttonTwo.setCursor(QCursor(Qt.PointingHandCursor))
self.h1.addWidget(self.buttonTwo,1)
self.myTextBoxOne = QLineEdit(self)
self.myTextBoxOne.setMinimumHeight(buttonMinHeight)
self.myTextBoxOne.setStyleSheet(textboxStyle)
self.myTextBoxOne.setFont(fontTwo)
self.myTextBoxOne.setReadOnly(True)
self.h1.addWidget(self.myTextBoxOne,4)
# self.lineOne = QLabel('/'*250, self)
# self.lineOne.setMaximumWidth(800)
# self.v1.addWidget(self.lineOne)
self.CheckOne = QCheckBox('Abrir de inmediato el documento generado', self)
self.CheckOne.setFont(fontTwo)
self.CheckOne.setMinimumHeight(buttonMinHeight)
# self.CheckOne.setMaximumWidth(800)
self.CheckOne.setStyleSheet(checkboxStyle)
self.CheckOne.setChecked(prev_prefs["2"])
self.v1.addWidget(self.CheckOne)
self.CheckTwo = QCheckBox('Convertir de inmediato a PDF/A', self)
self.CheckTwo.setFont(fontTwo)
self.CheckTwo.setMinimumHeight(buttonMinHeight)
# self.CheckTwo.setMaximumWidth(800)
self.CheckTwo.setStyleSheet(checkboxStyle)
self.CheckTwo.setChecked(prev_prefs["3"])
self.v1.addWidget(self.CheckTwo)
# self.lineTwo = QLabel('/'*250, self)
# self.lineTwo.setMaximumWidth(800)
# self.v1.addWidget(self.lineTwo)
self.h2.addStretch()
self.start = QPushButton('Ejecutar', self)
self.start.setStyleSheet(buttonStyle01)
# self.start.setFocus()
self.start.setFont(fontOne)
self.start.setMinimumHeight(buttonMinHeight)
# self.start.setMaximumWidth(200)
self.start.setEnabled(True)
self.start.setCursor(QCursor(Qt.PointingHandCursor))
self.start.clicked.connect(self.started)
self.h2.addWidget(self.start)
self.button = QPushButton('Limpiar', self)
self.button.setStyleSheet(buttonStyle01)
self.button.setFont(fontOne)
self.button.setMinimumHeight(buttonMinHeight)
# self.button.setMaximumWidth(200)
self.button.setEnabled(True)
self.button.setCursor(QCursor(Qt.PointingHandCursor))
self.button.clicked.connect(self.clean)
self.h2.addWidget(self.button)
self.progress = QProgressBar(self)
self.progress.setFormat("")
self.progress.setStyleSheet(progressStyle)
self.progress.setFont(fontOne)
# self.progress.setMaximumWidth(800)
self.progress.setAlignment(Qt.AlignCenter)
self.progress.setValue(0)
self.progress.setMaximum(0)
self.progress.hide()
self.labelTwo = QLabel('', self)
self.labelTwo.setFont(fontThree)
self.labelTwo.setStyleSheet("color: ForestGreen")
self.labelTwo.setAlignment(Qt.AlignCenter)
# self.labelTwo.hide()
self.pixmap = QPixmap(pic)
self.pixmap = self.pixmap.scaled(50, 100, Qt.KeepAspectRatio,Qt.SmoothTransformation)
self.labelThree = QLabel('', self)
self.labelThree.setAlignment(Qt.AlignCenter)
# self.info.setIcon(QIcon(self.style.standardIcon(QStyle.SP_FileDialogInfoView)))
self.mainLayout = QVBoxLayout()
self.mainLayout.setAlignment(Qt.AlignCenter)
# self.mainLayout.setSpacing(30)
# self.v1.setSpacing(0)
self.mainLayout.addLayout(self.h1)
self.mainLayout.addLayout(self.v1)
self.mainLayout.addLayout(self.h2)
self.mainLayout.addWidget(self.progress)
self.mainLayout.addWidget(self.labelTwo)
self.mainLayout.addWidget(self.labelThree)
self.setLayout(self.mainLayout)
# quit = QAction("Quit", self)
# quit.triggered.connect(self.closeEvent)
def started(self):
if self.runner is None:
self.start.setEnabled(False)
if self.var1 is not None:
self.labelTwo.setText('')
self.labelThree.hide()
self.progress.show()
self.state = self.CheckOne.checkState()
self.PDFA=self.CheckTwo.checkState()
# prev_prefs["2"]=self.state
# prev_prefs["3"]=self.PDFA
self.threadpool = QThreadPool()
self.runner = JobRunnerTwo(self.var1,self.state,self.PDFA)
self.threadpool.start(self.runner)
try:
self.runner.signals.alert.disconnect(self.alert)
self.runner.signals.finished.disconnect(self.finished)
except TypeError:
self.runner.signals.alert.connect(self.alert)
self.runner.signals.finished.connect(self.finished)
else:
self.runner.signals.alert.connect(self.alert)
self.runner.signals.finished.connect(self.finished)
else:
self.start.setEnabled(True)
self.labelTwo.setText('Intenta de nuevo.')
self.error(self.msg1)
def clean(self):
self.myTextBoxOne.setText(None)
self.var1=None
self.runner=None
self.labelTwo.setText('')
self.labelThree.hide()
self.progress.hide()
def openFileNameDialogOne(self):
fileName = QFileDialog.getOpenFileName(self,"Selecciona tu documento",'',filter="PDF (*.pdf)")
if len(fileName[0])!=0:
self.myTextBoxOne.setText(fileName[0])
self.var1=os.path.abspath(fileName[0])
def alert(self, msg):
if msg=='Error2':
self.error('Cierra el PDF sobre el cual intentas guardar el resultado.')
else:
self.error('Ocurrió un error inesperado: '+msg)
self.clean()
def finished(self, msg):
if msg=='Done':
self.runner=None
self.myTextBoxOne.setText(None)
self.var1=None
self.start.setEnabled(True)
self.labelTwo.setText('¡Listo, ya puedes visualizar tus documentos!')
self.labelThree.show()
self.labelThree.setPixmap(self.pixmap)
self.labelThree.show()
self.progress.hide()
def error(self,errorMsg):
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setWindowTitle(self.title)
msg.setWindowIcon(QIcon(icon))
msg.setText("Error")
msg.setFont(fontTwo)
msg.setStandardButtons(QMessageBox.Ok)
buttonOk = msg.button(QMessageBox.Ok)
buttonOk.setCursor(QCursor(Qt.PointingHandCursor))
buttonOk.setFont(fontOne)
msg.setStyleSheet(msg_window_style)
msg.setInformativeText(errorMsg)
msg.exec_()
self.start.setEnabled(True)
self.runner=None
# <codecell>
class WorkerSignalsThree(QObject):
alert=pyqtSignal(str)
finished=pyqtSignal(str)
class JobRunnerThree(QRunnable):
signals = WorkerSignalsThree()
def __init__(self,documents,SaveAs,state,PDFA):
super().__init__()
self.is_killed = False
self.documents=documents
self.SaveAs=SaveAs
self.state=state
self.PDFA=PDFA
@pyqtSlot()
def is_opened(self):
temp_filename=self.SaveAs[:-4]+' temp.pdf'
if os.path.exists(self.SaveAs) == True:
try:
os.rename(self.SaveAs,temp_filename)
os.rename(temp_filename,self.SaveAs)
return False
except PermissionError:
return True
else:
return False
def run(self):
try:
if len(self.documents)<2:
self.signals.alert.emit('Error3')
elif self.SaveAs in self.documents:
self.signals.alert.emit('Error1')
elif self.is_opened() == True:
self.signals.alert.emit('Error2')
else:
pdf=fitz.open()
for element in self.documents:
opened_file=fitz.open(element)
pdf.insertPDF(opened_file)
opened_file.close()
pdf.save(self.SaveAs,deflate=True)
pdf.close()
if self.PDFA==2:
done=False
count=0
while not done:
try:
backup=shutil.copy(self.SaveAs,self.SaveAs[:-4]+' sehr witzig.pdf')
done=True
except PermissionError:
print('Permission denied')
count+=1
time.sleep(count)
time.sleep(1)
# ==============================================================
holder=self.SaveAs[:-4]+' sehr witzig.pdf'
subprocess.check_call(["attrib","+H",holder])
# ==============================================================
tempDocx=os.path.join(os.path.dirname(self.SaveAs),'tempword.docx')
documento = Document()
documento.save(tempDocx)
# =======================================
holder=tempDocx
subprocess.check_call(["attrib","+H",holder])
# =======================================
word = client.DispatchEx('Word.Application')
worddoc = word.Documents.Open(tempDocx,ReadOnly = 1)
worddoc.SaveAs(self.SaveAs,FileFormat = 17)
worddoc.Close(True)
word.Quit()
done=False
count=0
while not done:
try:
os.remove(tempDocx)
done=True
except PermissionError:
print('Permission denied')
count+=1
time.sleep(count)
pdf=fitz.open(self.SaveAs)
opened_file=fitz.open(backup)
pdf.insertPDF(opened_file)
opened_file.close()
pdf.deletePage(0)
pdf.saveIncr()
pdf.close()
time.sleep(1)
done=False
count=0
while not done:
try:
os.remove(backup)
done=True
except PermissionError:
print('Permission denied')
count+=1
time.sleep(count)
if self.state==2:
subprocess.Popen([self.SaveAs],shell=True)
time.sleep(1)
self.signals.finished.emit('Done')
except Exception as e:
self.signals.alert.emit(str(e))
def kill(self):
self.is_killed = True
class ActionsThree(QWidget):
def __init__(self):
super().__init__()
self.runner=None
self.title = 'LuftMensch'
self.var1=None
self.var2=None
self.initUI()
self.msg1='Verifica los datos ingresados.'
def initUI(self):
self.h1=QHBoxLayout()
self.h2=QHBoxLayout()
self.h3=QHBoxLayout()
self.v1=QVBoxLayout()
self.v2=QVBoxLayout()
self.buttonTwo = QPushButton('Cargar PDFs', self)
self.buttonTwo.clicked.connect(self.openFileNameDialogOne)
self.buttonTwo.setMinimumHeight(buttonMinHeight)
# self.buttonTwo.setMaximumWidth(200)
self.buttonTwo.setStyleSheet(buttonStyle02)
self.buttonTwo.setFont(fontTwo)
self.buttonTwo.setCursor(QCursor(Qt.PointingHandCursor))
self.h1.addWidget(self.buttonTwo,1)
self.myTextBoxOne = QLineEdit(self)
self.myTextBoxOne.setMinimumHeight(buttonMinHeight)
self.myTextBoxOne.setStyleSheet(textboxStyle)
self.myTextBoxOne.setFont(fontTwo)
self.myTextBoxOne.setReadOnly(True)
self.h1.addWidget(self.myTextBoxOne,4)
self.buttonThree = QPushButton('Guardar como', self)
self.buttonThree.clicked.connect(self.openFileNameDialogTwo)
self.buttonThree.setMinimumHeight(buttonMinHeight)
# self.buttonThree.setMaximumWidth(200)
self.buttonThree.setStyleSheet(buttonStyle02)
self.buttonThree.setFont(fontTwo)
self.buttonThree.setCursor(QCursor(Qt.PointingHandCursor))
self.h3.addWidget(self.buttonThree,1)
self.myTextBoxTwo = QLineEdit(self)
self.myTextBoxTwo.setMinimumHeight(buttonMinHeight)
self.myTextBoxTwo.setStyleSheet(textboxStyle)
self.myTextBoxTwo.setFont(fontTwo)
self.myTextBoxTwo.setReadOnly(True)
self.h3.addWidget(self.myTextBoxTwo,4)
# self.lineOne = QLabel('/'*250, self)
# self.lineOne.setMaximumWidth(800)
# self.v1.addWidget(self.lineOne)
self.CheckOne = QCheckBox('Abrir de inmediato el documento generado', self)
self.CheckOne.setFont(fontTwo)
self.CheckOne.setMinimumHeight(buttonMinHeight)
# self.CheckOne.setMaximumWidth(800)
self.CheckOne.setStyleSheet(checkboxStyle)
self.CheckOne.setChecked(prev_prefs["4"])
self.v1.addWidget(self.CheckOne)
self.CheckTwo = QCheckBox('Convertir de inmediato a PDF/A', self)
self.CheckTwo.setFont(fontTwo)
self.CheckTwo.setMinimumHeight(buttonMinHeight)
# self.CheckTwo.setMaximumWidth(800)
self.CheckTwo.setStyleSheet(checkboxStyle)
self.CheckTwo.setChecked(prev_prefs["5"])
self.v1.addWidget(self.CheckTwo)
# self.lineTwo = QLabel('/'*250, self)
# self.lineTwo.setMaximumWidth(800)
# self.v1.addWidget(self.lineTwo)
self.h2.addStretch()
self.start = QPushButton('Ejecutar', self)
self.start.setStyleSheet(buttonStyle01)
# self.start.setFocus()
self.start.setFont(fontOne)
self.start.setMinimumHeight(buttonMinHeight)
# self.start.setMaximumWidth(200)
self.start.setEnabled(True)
self.start.setCursor(QCursor(Qt.PointingHandCursor))
self.start.clicked.connect(self.started)
self.h2.addWidget(self.start)
self.button = QPushButton('Limpiar', self)
self.button.setStyleSheet(buttonStyle01)
self.button.setFont(fontOne)
self.button.setMinimumHeight(buttonMinHeight)
# self.button.setMaximumWidth(200)
self.button.setEnabled(True)
self.button.setCursor(QCursor(Qt.PointingHandCursor))
self.button.clicked.connect(self.clean)
self.h2.addWidget(self.button)
self.progress = QProgressBar(self)
self.progress.setFormat("")
self.progress.setStyleSheet(progressStyle)
self.progress.setFont(fontOne)
# self.progress.setMaximumWidth(800)
self.progress.setAlignment(Qt.AlignCenter)
self.progress.setValue(0)
self.progress.setMaximum(0)
self.progress.hide()
self.labelTwo = QLabel('', self)
self.labelTwo.setFont(fontThree)
self.labelTwo.setStyleSheet("color: ForestGreen")
self.labelTwo.setAlignment(Qt.AlignCenter)
# self.labelTwo.hide()
self.pixmap = QPixmap(pic)
self.pixmap = self.pixmap.scaled(50, 50, Qt.KeepAspectRatio,Qt.SmoothTransformation)
self.labelThree = QLabel('', self)
self.labelThree.setAlignment(Qt.AlignCenter)
# self.info.setIcon(QIcon(self.style.standardIcon(QStyle.SP_FileDialogInfoView)))