-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPrintManager.py
executable file
·2596 lines (2410 loc) · 93.1 KB
/
PrintManager.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
#!/usr/local/opt/[email protected]/bin/python3.12
import sys
import os
import subprocess
import json
from PyPDF2 import PdfReader, PdfWriter
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QDropEvent, QKeySequence, QPalette, QColor, QIcon, QPixmap, QBrush, QPainter, QFont, QCursor, QTextCursor, QDrag
from PyQt5.QtCore import *
from tnefparse.tnef import TNEF, TNEFAttachment, TNEFObject
from tnefparse.mapi import TNEFMAPI_Attribute
from unidecode import unidecode
import webbrowser
from libs.colordetector import *
from libs.crop_module import processFile
from libs.pdf_preview_module import pdf_preview_generator
from libs.image_grabber_module import *
from libs.remove_cropmarks_module import *
from libs.gui_crop2 import *
from libs.waifu_module import *
# SMART CROP - BROKEN NOW
version = '0.34'
# -more formats
# -added gs convert fonts to
# -added waifu convert
# -fixed close window crashes
import time
start_time = time.time()
info, name, size, extension, file_size, pages, price, colors, filepath = [],[],[],[],[],[],[],[],[]
mm = '0.3527777778'
office_ext = ['csv', 'db', 'odt', 'doc', 'gif', 'pcx', 'docx', 'dotx', 'fodp', 'fods', 'fodt', 'odb', 'odf', 'odg', 'odm', 'odp', 'ods', 'otg', 'otp', 'ots', 'ott', 'oxt', 'pptx', 'psw', 'sda', 'sdc', 'sdd', 'sdp', 'sdw', 'slk', 'smf', 'stc', 'std', 'sti', 'stw', 'sxc', 'sxg', 'sxi', 'sxm', 'sxw', 'uof', 'uop', 'uos', 'uot', 'vsd', 'vsdx', 'wdb', 'wps', 'wri', 'xls', 'xlsx', 'ppt', 'cdr']
image_ext = ['jpg', 'jpeg', 'png', 'tif', 'bmp']
next_ext = ['pdf','dat']
papers = ['A4', 'A5', 'A3', '480x320', '450x320', 'undefined']
username = os.path.expanduser("~")
# other os support
system = str(sys.platform)
if system == 'darwin':
sys_support = 'supported'
else:
sys_support = 'not supported'
# extract printer info as list for preferences only
def load_printers():
output = (subprocess.check_output(["/usr/bin/lpstat", "-a"]))
outputlist = (output.splitlines())
tolist = [] # novy list
for num in outputlist: # prochazeni listem
first, *middle, last = num.split()
tiskarna = str(first.decode())
tolist.append(tiskarna)
return (tolist)
# PREFERENCES BASIC
def load_preferences():
try:
with open('config.json', encoding='utf-8') as data_file:
json_pref = json.loads(data_file.read())
if json_pref[0][8] == username:
print ('saved pref. ok')
printers = json_pref[0][9]
default_pref = [json_pref[0][10],json_pref[0][11],json_pref[0][12],json_pref[0][13]]
else:
print ('other machine loading printers')
printers = load_printers()
except Exception as e:
print (e)
printers = load_printers()
json_pref = [0,0,0,0,0,0,0]
default_pref = ['eng',300,'OpenOffice',False]
return json_pref, printers, default_pref
def fix_filename(item, _format=None):
oldfilename = (os.path.basename(item))
dirname = (os.path.dirname(item) + '/')
if _format != None:
newfilename = _format + oldfilename
else:
newfilename = unidecode(oldfilename)
os.system('mv ' + "'" + dirname + oldfilename + "'" + ' ' + "'" + dirname + newfilename + "'")
return dirname + newfilename
def save_preferences(*settings):
print ('JSON save on exit')
preferences = []
for items in settings:
preferences.append(items)
with open('config.json', 'w', encoding='utf-8') as data_file:
json.dump(preferences, data_file)
startup = 1
return startup
def humansize(size):
filesize = ('%.1f' % float(size/1000000) + ' MB')
return filesize
def clear_table(self):
"""Vymaže všechny řádky v tabulce."""
self.table.setRowCount(0) # Nastaví počet řádků na 0
def open_printer(file):
file_path = '/private/etc/cups/ppd/' + file + '.ppd'
if os.path.exists(file_path):
print(['open', '-t', file_path])
# Použijte plnou cestu k příkazu open
subprocess.run(['/usr/bin/open', '-t', file_path])
else:
print(f"Soubor {file_path} neexistuje.")
def revealfile(list_path,reveal): #reveal and convert
if isinstance (list_path, list):
for items in list_path:
subprocess.call(['open', reveal, items])
else:
subprocess.call(['open', reveal, list_path])
def previewimage(original_file):
command = ["qlmanage", "-p", original_file]
subprocess.run(command)
return command
def mergefiles(list_path, save_dir):
base = os.path.basename(list_path[0])
file = os.path.splitext(base)
folder_path = os.path.dirname(list_path[0])
print(folder_path)
if folder_path == '/tmp':
folder_path = save_dir
outputfile = folder_path + '/' + file[0] + '_m.pdf'
# print (outputfile)
writer = PdfWriter()
for pdf in list_path:
reader = PdfReader(pdf)
writer.append(reader)
with open(outputfile, 'wb') as f:
writer.write(f)
return outputfile
def splitfiles(file):
outputfiles = []
pdf_file = open(file, 'rb')
pdf_reader = PdfReader(pdf_file)
pageNumbers = len(pdf_reader.pages)
head, ext = os.path.splitext(file)
outputfile = head + 's_'
for i in range(pageNumbers):
pdf_writer = PdfWriter()
pdf_writer.add_page(pdf_reader.pages[i])
outputpaths = outputfile + str(i + 1) + '.pdf'
with open(outputpaths, 'wb') as split_motive:
pdf_writer.write(split_motive)
outputfiles.append(outputpaths)
pdf_file.close()
return outputfiles
def resize_this_image(original_file, percent):
outputfiles = []
for item in original_file:
head, ext = os.path.splitext(item)
outputfile = head + '_' + str(percent) + ext
command = ["convert", item, "-resize", str(percent)+'%', outputfile]
subprocess.run(command)
outputfiles.append(outputfile)
return command, outputfiles
def crop_image(original_file, coordinates):
command = ["convert", original_file, "-crop", str(coordinates[2] - coordinates[0])+'x'+str(coordinates[3] - coordinates[1])+'+'+str(coordinates[0])+'+'+str(coordinates[1]), original_file]
print (command)
print (command)
subprocess.run(command)
return command
def pdf_cropper_x(pdf_input, coordinates, pages):
print(coordinates)
pdf = PdfReader(open(pdf_input, 'rb'))
outPdf = PdfWriter()
for i in range(pages):
page = pdf.pages[i]
page.mediaBox.upper_left = (coordinates[0], int(page.trim_box[3]) - coordinates[1])
page.mediaBox.lower_right = (coordinates[2], int(page.trim_box[3]) - coordinates[3])
page.trimbox.upper_left = (coordinates[0], int(page.trim_box[3]) - coordinates[1])
page.trimbox.lower_right = (coordinates[2], int(page.trim_box[3]) - coordinates[3])
outPdf.add_page(page)
with open(pdf_input + '_temp', 'wb') as outStream:
outPdf.write(outStream)
os.rename(pdf_input + '_temp', pdf_input)
def rotate_this_image(original_file, angle):
outputfiles = []
for item in original_file:
head, ext = os.path.splitext(item)
outputfile = head + ext
command = ["convert", item, "-rotate", str(angle), outputfile]
subprocess.run(command)
outputfiles.append(outputfile)
return command, outputfiles
def invert_this_image(original_file):
outputfiles = []
for item in original_file:
head, ext = os.path.splitext(item)
outputfile = head + ext
command = ["convert", item, "-channel", "RGB", "-negate", outputfile]
subprocess.run(command)
outputfiles.append(outputfile)
return command, outputfiles
def gray_this_file(original_file,filetype):
outputfiles = []
for item in original_file:
head, ext = os.path.splitext(item)
outputfile = head + '_gray' + ext
if filetype == 'pdf':
command = ["gs", "-sDEVICE=pdfwrite", "-dProcessColorModel=/DeviceGray", "-dColorConversionStrategy=/Gray", "-dPDFUseOldCMS=false", "-dNOPAUSE", "-dQUIET", "-dBATCH", "-sOutputFile="+outputfile, item]
else:
command = ["convert", item, "-colorspace", "Gray", outputfile]
subprocess.run(command)
outputfiles.append(outputfile)
return command, outputfiles
def compres_this_file(original_file,resolution):
outputfiles = []
for item in original_file:
head, ext = os.path.splitext(item)
outputfile = head + '_c' + ext
command = ["gs", "-sDEVICE=pdfwrite", "-dCompatibilityLevel=1.4", "-dPDFSETTINGS=/ebook", "-dNOPAUSE", "-dQUIET", "-dBATCH", "-sOutputFile="+outputfile, item]
subprocess.run(command)
outputfiles.append(outputfile)
return command, outputfiles
def raster_this_file(original_file,resolution):
outputfiles = []
for item in original_file:
head, ext = os.path.splitext(item)
outputfile = head + '_raster' + ext
command_gs = ["gs", "-dSAFER", "-dBATCH", "-dNOPAUSE", "-dNOCACHE", "-sDEVICE=pdfwrite", "-sColorConversionStrategy=/LeaveColorUnchanged", "-dAutoFilterColorImages=true", "-dAutoFilterGrayImages=true", "-dDownsampleMonoImages=true", "-dDownsampleGrayImages=true", "-dDownsampleColorImages=true", "-sOutputFile="+outputfile, original_file]
command = ["convert", "-density", str(resolution), "+antialias", str(item), str(outputfile)]
subprocess.run(command)
outputfiles.append(outputfile)
return command, outputfiles
def flaten_transpare_pdf(original_file,resolution):
outputfiles = []
for item in original_file:
head, ext = os.path.splitext(item)
outputfile = head + '_fl' + ext
command_gs = ["gs", "-dSAFER", "-dBATCH", "-dNOPAUSE", "-dNOCACHE", "-sDEVICE=pdfwrite", "-dCompatibilityLevel=1.3", "-sOutputFile="+outputfile, item]
subprocess.run(command_gs)
outputfiles.append(outputfile)
return command_gs, outputfiles
def fix_this_file(original_file,resolution):
outputfiles = []
for item in original_file:
head, ext = os.path.splitext(item)
outputfile = head + '_fixed' + ext
command_gs = ["gs", "-dSAFER", "-dBATCH", "-dNOPAUSE", "-dNOCACHE", "-sDEVICE=pdfwrite", "-dPDFSETTINGS=/prepress", "-sOutputFile="+outputfile, item]
subprocess.run(command_gs)
outputfiles.append(outputfile)
return command_gs, outputfiles
def convert_this_file(original_file,resolution):
outputfiles = []
for item in original_file:
head, ext = os.path.splitext(item)
outputfile = head + '.pdf'
command = ["convert", str(resolution), '-density', '300', str(item), str(outputfile)]
subprocess.run(command)
outputfiles.append(outputfile)
return command, outputfiles
def smart_cut_this_file(original_file, *args):
smartcut_files = []
outputfiles = []
dialog = InputDialog_SmartCut()
if dialog.exec():
n_images, tresh = dialog.getInputs()
for items in original_file:
outputfiles = processFile(items, n_images, tresh)
smartcut_files.append(outputfiles)
# merge lists inside lists
smartcut_files = [j for i in smartcut_files for j in i]
command = 'OK'
else:
dialog.close()
return command, smartcut_files
def get_boxes(input_file):
pdf_reader = PdfReader(input_file)
page = reader.pages[0]
pageNumbers = pdf_reader.getNumPages()
# input_file.close()
return pageNumbers
def find_fonts(obj, fnt):
if '/BaseFont' in obj:
fnt.add(obj['/BaseFont'])
for k in obj:
if hasattr(obj[k], 'keys'):
find_fonts(obj[k], fnt)
return fnt
def get_fonts(pdf_input):
font_ = []
fonts = set()
for page in pdf_input.pages:
obj = page.getObject()
f = find_fonts(obj['/Resources'], fonts)
for items in f:
head, sep, tail = items.partition('+')
font_.append(tail)
return font_
def file_info_new(inputs, file, *args):
_info = []
if file == 'pdf':
for item in inputs:
pdf_toread = PdfReader(open(item, "rb"))
pdf_ = pdf_toread.getDocumentInfo()
pdf_fixed = {key.strip('/'): item.strip() for key, item in pdf_.items()}
pdf_fixed.update( {'Filesize' : humansize(os.path.getsize(item))} )
pdf_fixed.update( {'Pages' : str(pdf_toread.getNumPages())} )
pdf_fixed.update( {'MediaBox' : get_pdf_size(pdf_toread.getPage(0).mediaBox)} )
pdf_fixed.update( {'CropBox' : get_pdf_size(pdf_toread.getPage(0).cropBox)} )
pdf_fixed.update( {'TrimBox' : get_pdf_size(pdf_toread.getPage(0).trimBox)} )
pdf_fixed.update( {'Fonts' : "\n".join(get_fonts(pdf_toread))} )
html_info = tablemaker(pdf_fixed)
_info.append(html_info)
else:
name_ = []
val_ = []
for item in inputs:
output = (subprocess.check_output(["mdls", item]))
pdf_info = (output.splitlines())
name_.append('Filesize')
val_.append(humansize(os.path.getsize(item)))
for num in pdf_info:
num = num.decode("utf-8")
name, *value = num.split('=')
value = ', '.join(value)
name = name.rstrip()
value = value.replace('"','')
value = value.lstrip()
name = name.replace('kMD','')
name = name.replace('FS','')
name = name[:24] + (name[24:] and '..')
name_.append(name)
val_.append(value)
tolist = dict(zip(name_, val_))
unwanted = ['', [], '(', '0', '(null)']
img_ = {k: v for k, v in tolist.items() if v not in unwanted}
# img_.update( {'Filesize' : humansize(os.path.getsize(item))} )
_info = tablemaker(img_)
return _info
def tablemaker (inputs):
html = "<table width=100% table cellspacing=0 style='border-collapse: collapse' border = \"0\" >"
html += '<style>table, td, th {font-size: 9px;border: none;padding-left: 2px;padding-right: 2px;ppadding-bottom: 4px;}</style>'
# fix this
inputs = {k.replace(u'D:', ' ') : v.replace(u'D:', ' ') for k, v in inputs.items()}
inputs = {k.replace(u"+01'00'", ' ') : v.replace(u"+01'00'", ' ') for k, v in inputs.items()}
inputs = {k.replace(u" +0000", ' ') : v.replace(u" +0000", ' ') for k, v in inputs.items()}
inputs = {k.replace(u"Item", ' ') : v.replace(u"Item", ' ') for k, v in inputs.items()}
inputs = {k.replace(u" 00:00:00", ' ') : v.replace(u" 00:00:00", ' ') for k, v in inputs.items()}
# print (inputs)
# for i in inputs:
# print (i)
# i = dt.datetime.strptime(dict[i],'%m/%d/%y').month
# alert['alert_date'] = datetime.strptime(alert['alert_date'], "%Y-%m-%d %H:%M:%S")
for dict_item in inputs:
html += '<tr>'
key_values = dict_item.split(',')
# print (key_values) # [1:]
html += '<th><p style="text-align:right;color: #7e7e7e;">' + str(key_values[0]) + '</p></th>'
# print (inputs[dict_item])
html += '<th><p style="text-align:left;font-weight: normal">' + inputs[dict_item] + '</p></th>'
html += '</tr>'
html += '</table>'
return html
def print_this_file(print_file, printer, lp_two_sided, orientation, copies, p_size, fit_to_size, collate, colors):
# https://www.cups.org/doc/options.html
# COLATE
# print ('XXXXX: ' + str(colors))
if collate == 1:
print ('collate ON')
collate = ('-o collate=true')
else:
print ('collate OFF')
collate = ('')
# COLORS
if colors == 'Auto':
colors = ('')
if colors == 'Color':
colors = ('-o ColorMode=Color')
if colors == 'Gray':
colors = ('-o ColorMode=GrayScale')
# _colors = ('-oColorModel=KGray')
# PAPER SHRINK
if fit_to_size == 1:
fit_to_size = ('-o fit-to-page')
else:
fit_to_size = ('')
# PAPER SIZE WIP
if p_size == 'A4':
_p_size = ('-o media=A4')
if p_size == 'A3':
_p_size = ('-o media=A3')
if p_size == 'A5':
_p_size = ('-o media=A5')
if p_size == '480x320':
_p_size = ('-o media=480x320')
if p_size == '450x320':
_p_size = ('-o media=450x320')
else:
_p_size = '-o media=Custom.' + p_size + 'mm'
# na canonu nefunguje pocet kopii... vyhodit -o sides=one-sided
if lp_two_sided == 1:
lp_two_sided_ = ('-o sides=two-sided')
if orientation == 1:
lp_two_sided_ = ('-o sides=two-sided-long-edge')
else:
lp_two_sided_ = ('-o sides=two-sided-short-edge')
else:
lp_two_sided_ = ('-o sides=one-sided')
for printitems in print_file:
command = ["lp", "-d", printer, printitems, "-n" + copies, lp_two_sided_, _p_size, fit_to_size, collate, colors]
# remove blank strings
command = [x for x in command if x]
subprocess.run(command)
try:
subprocess.run(["open", username + "/Library/Printers/" + str(printer) + ".app"])
except:
print ('printer not found')
return command
def get_pdf_size(pdf_input):
qsizedoc = (pdf_input)
width = (float(qsizedoc[2]) * float(mm))
height = (float(qsizedoc[3]) * float(mm))
page_size = (str(round(width)) + 'x' + str(round(height)) + ' mm')
return page_size
def getimageinfo (filename):
try:
output = (subprocess.check_output(["/usr/local/bin/identify", '-format', '%wx%hpx %m', filename]))
outputlist = (output.splitlines())
getimageinfo = []
for num in outputlist: # prochazeni listem
first, middle = num.split()
getimageinfo.append(str(first.decode()))
getimageinfo.append(str(middle.decode()))
error = 0
except Exception as e:
error = str(e)
getimageinfo = 0
return getimageinfo, error
for item in original_file:
head, ext = os.path.splitext(item)
outputfile = head + '_c' + ext
command = ["gs", "-sDEVICE=pdfwrite", "-dCompatibilityLevel=1.4", "-dPDFSETTINGS=/ebook", "-dNOPAUSE", "-dQUIET", "-dBATCH", "-sOutputFile="+outputfile, item]
subprocess.run(command)
outputfiles.append(outputfile)
return command, outputfiles
def append_blankpage(inputs, *args):
outputfiles = []
if isinstance(inputs, str): # Použijte isinstance pro kontrolu typu
inputs = [inputs]
for item in inputs:
with open(item, 'rb') as input_file:
pdf = PdfReader(input_file)
numPages = len(pdf.pages) # Získání počtu stránek pomocí len(pdf.pages)
if numPages % 2 == 1:
print('licha')
outPdf = PdfWriter() # Použijte PdfWriter
# Přidejte všechny stránky jednu po druhé
for page_number in range(numPages):
page = pdf.pages[page_number] # Získání stránky pomocí indexu
outPdf.add_page(page) # Přidání jednotlivé stránky
outPdf.add_blank_page() # Přidejte prázdnou stránku
outStream = open(item + '_temp', 'wb')
outPdf.write(outStream)
outStream.close()
os.rename(item + '_temp', item)
else:
print('suda all ok')
command = ['ok']
return command, outputfiles
# for items in inputs:
# pdf_in = open(items, 'rb')
# pdf_reader = PdfReader(pdf_in)
# pdf_writer = PdfFileWriter()
# numPages=pdf_reader.getNumPages()
# if numPages % 2 == 1:
# print ('je potreba pridat stranu')
# pdf_out = open(items + '_temp', 'wb')
# pdf_writer.write(pdf_out)
# pdf_writer.appendPagesFromReader(pdf_reader)
# pdf_writer.addBlankPage()
# pdf_out = open(items + '_temp', 'wb')
# # pdf_writer.write(pdf_out)
# pdf_out.close()
# pdf_in.close()
# os.rename(items + '_temp', items)
# outputfiles.append(items)
# command = ['XXXX']
# return command, outputfiles
# pdf_out = open(filepath + '_temp', 'wb')
# pdf_writer.write(pdf_out)
# pdf_out.close()
def pdf_parse(self, inputs, *args):
rows = []
if isinstance(inputs, str):
inputs = [inputs]
for item in inputs:
oldfilename = os.path.basename(item)
ext_file = os.path.splitext(oldfilename)
dirname = os.path.dirname(item) + '/'
try:
with open(item, mode='rb') as f:
pdf_input = PdfReader(f, strict=False)
if pdf_input.is_encrypted:
self.d_writer('File is encrypted...', 0, 'red')
continue # Pokračujte na další soubor, pokud je šifrovaný
# Opraveno na mediaBox
page_size = get_pdf_size(pdf_input.pages[0].mediabox)
pdf_pages = len(pdf_input.pages)
velikost = size_check(page_size)
name.append(ext_file[0])
size.append(size_check(page_size))
price.append(price_check(pdf_pages, velikost))
file_size.append(humansize(os.path.getsize(item)))
pages.append(int(pdf_pages))
filepath.append(item)
info.append('')
colors.append('')
extension.append(ext_file[1][1:].lower())
except Exception as e:
print(e)
err = QMessageBox()
err.setWindowTitle("Error")
err.setIcon(QMessageBox.Critical)
err.setText("Error")
err.setInformativeText(str(e))
err.exec_()
self.d_writer('Import error: ' + str(e), 1, 'red')
merged_list = list(zip(info, name, size, extension, file_size, pages, price, colors, filepath))
return merged_list
def pdf_update(self, inputs, index, *args):
rows = []
if isinstance(inputs, str): # Použijte isinstance pro kontrolu typu
inputs = [inputs]
for item in inputs:
oldfilename = os.path.basename(item)
ext_file = os.path.splitext(oldfilename)
dirname = os.path.dirname(item) + '/'
with open(item, mode='rb') as f:
pdf_input = PdfReader(f, strict=False)
if pdf_input.is_encrypted:
self.d_writer('File is encrypted...', 0, 'red')
break # Ukončete cyklus, pokud je soubor zašifrovaný
else:
try:
# Získání velikosti stránky a počtu stránek
page_size = get_pdf_size(pdf_input.pages[0].mediabox) # Použijte pdf_input.pages[0]
pdf_pages = len(pdf_input.pages) # Použijte len(pdf_input.pages)
velikost = size_check(page_size)
# Aktualizace informací
name[index] = ext_file[0]
size[index] = size_check(page_size)
price[index] = price_check(pdf_pages, velikost)
file_size[index] = humansize(os.path.getsize(item))
pages[index] = int(pdf_pages)
filepath[index] = item
info[index] = ''
colors[index] = ''
extension[index] = ext_file[1][1:].lower()
except Exception as e:
print(e)
err = QMessageBox()
err.setWindowTitle("Error")
err.setIcon(QMessageBox.Critical)
err.setText("Error")
err.setInformativeText(str(e))
err.exec_()
self.d_writer('Import error:' + str(e),1, 'red')
f.close()
merged_list = list(zip(info, name, size, extension, file_size, pages, price, colors, filepath))
return merged_list
def img_parse(self, inputs, *args):
rows = []
for item in inputs:
oldfilename = (os.path.basename(item))
filesize = humansize(os.path.getsize(item))
ext_file = os.path.splitext(oldfilename)
dirname = (os.path.dirname(item) + '/')
info.append('')
image_info, error = getimageinfo(item)
if image_info == 0:
self.d_writer('Import file failed...' , 0, 'red')
self.d_writer(error , 1, 'white')
break
name.append(ext_file[0])
size.append(str(image_info[0]))
extension.append(ext_file[1][1:].lower())
file_size.append(humansize(os.path.getsize(item)))
pages.append(1)
price.append('')
colors.append(str(image_info[1]))
filepath.append(item)
merged_list = list(zip(info, name, size, extension, file_size, pages, price, colors, filepath))
return merged_list
def update_img(self, inputs, index, *args):
rows = []
for item in inputs:
oldfilename = (os.path.basename(item))
filesize = humansize(os.path.getsize(item))
ext_file = os.path.splitext(oldfilename)
dirname = (os.path.dirname(item) + '/')
info[index] = ('')
image_info, error = getimageinfo(item)
if image_info == 0:
self.d_writer('Import file failed...' , 0, 'red')
self.d_writer(error , 1, 'white')
break
name[index] = ext_file[0]
size[index] = str(image_info[0])
extension[index] = ext_file[1][1:].lower()
file_size[index] = humansize(os.path.getsize(item))
pages[index] = 1
price[index] = ''
colors[index] = str(image_info[1])
filepath[index] = item
merged_list = list(zip(info, name, size, extension, file_size, pages, price, colors, filepath))
return merged_list
def remove_from_list(self, index, *args):
print (info)
del info[index]
del name[index]
del size[index]
del extension[index]
del file_size[index]
del pages[index]
del price[index]
del colors[index]
del filepath[index]
merged_list = list(zip(info, name, size, extension, file_size, pages, price, colors, filepath))
return merged_list
def size_check(page_size):
velikost = 0
if page_size == '210x297mm':
velikost = 'A4'
elif page_size == '420x297mm':
velikost = 'A3'
elif page_size == '148x210mm':
velikost = 'A5'
elif page_size == '420x594mm':
velikost = 'A2'
elif page_size == '594x841mm':
velikost = 'A1'
elif page_size == '841x1188mm':
velikost = 'A0'
else:
velikost = page_size
return velikost
def price_check(pages, velikost):
price = []
if velikost == 'A4':
if pages >= 50:
pricesum = (str(pages * 1.5) + ' Kč')
elif pages >= 20:
pricesum = (str(pages * 2) + ' Kč')
elif pages >= 0:
pricesum = (str(pages * 3) + ' Kč')
elif velikost == 'A3':
if pages >= 50:
pricesum = (str(pages * 2) + ' Kč')
elif pages >= 20:
pricesum = (str(pages * 3) + ' Kč')
elif pages >= 0:
pricesum = (str(pages * 4) + ' Kč')
else:
pricesum = '/'
return pricesum
def darkmode():
app.setStyle("Fusion")
palette = QPalette()
palette.setColor(QPalette.Window, QColor(53, 53, 53))
palette.setColor(QPalette.WindowText, Qt.white)
palette.setColor(QPalette.Base, QColor(25, 25, 25))
palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
palette.setColor(QPalette.ToolTipBase, Qt.white)
palette.setColor(QPalette.ToolTipText, Qt.white)
palette.setColor(QPalette.Text, Qt.white)
palette.setColor(QPalette.Button, QColor(53, 53, 53))
palette.setColor(QPalette.ButtonText, Qt.white)
palette.setColor(QPalette.BrightText, Qt.red)
palette.setColor(QPalette.Link, QColor(42, 130, 218))
palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
palette.setColor(QPalette.HighlightedText, Qt.black)
app.setStyleSheet('QPushButton:enabled {color: #ffffff;background-color:#2c2c2c;}QPushButton:disabled {color: #696969;background-color:#272727;}')
app.setPalette(palette)
class TableWidgetDragRows(QTableWidget):
def __init__(self, *args, **kwargs):
QTableWidget.__init__(self, *args, **kwargs)
self.setAcceptDrops(True)
self.setDragEnabled(True)
self.viewport().setAcceptDrops(True)
self.setDragDropOverwriteMode(False)
# self.setDropIndicatorShown(True)
self.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.setSelectionBehavior(QAbstractItemView.SelectRows)
# self.setDragDropMode(QAbstractItemView.InternalMove)
self.setFocusPolicy(Qt.NoFocus)
self.setSortingEnabled(True)
# print todoo
def dragEnterEvent(self, event):
print ('chytam')
jpg_file = "icons/jpg.png"
jpg_icon = QIcon()
jpg_icon.addPixmap(QPixmap(jpg_file))
# m = event.mimeData()
# print (m)
# if event.mimeData().hasUrls:
# event.accept()
# else:
# event.ignore()
# event.setDropAction(Qt.CopyAction)
def dragMoveEvent(self, event):
r = self.currentRow()
path = self.item(r,8).text()
print (path)
# file_url = QUrl(path).toLocalFile()
# mimeData = QMimeData()
# mimeData.setUrls(file_url)
# print (mimeData)
# if mimeData.hasUrls:
# print ('nejsem debil')
# else:
# print ('sem')
# print (self.currentItem().row().text())
# print (self.currentItem().text())
# m = event.mimeData().text()
# print (m)
# if path.mimeData().hasUrls:
# event.setDropAction(Qt.CopyAction)
event.accept()
print ('yay')
# else:
# event.ignore()
def dragLeaveEvent(self, event):
event.accept()
def dropEvent(self, event):
print ('drag back')
# for icons
class IconDelegate(QStyledItemDelegate):
def initStyleOption(self, option, index):
super(IconDelegate, self).initStyleOption(option, index)
if option.features & QStyleOptionViewItem.HasDecoration:
s = option.decorationSize
s.setWidth(option.rect.width())
option.decorationSize = s
class InputDialog_SmartCut(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.first = QSpinBox(self)
self.first.setRange(1, 50)
self.first.setValue(1)
self.second = QSpinBox(self)
self.second.setRange(1, 255)
self.second.setValue(220)
buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, self);
layout = QFormLayout(self)
layout.addRow("Number of images", self.first)
layout.addRow("Treshold", self.second)
layout.addWidget(buttonBox)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.reject)
def getInputs(self):
return (self.first.text(), self.second.text())
class InputDialog_waifu2x(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.imagetype = QComboBox()
self.imagetype.addItems(["photo", "cartoon"])
self.scale = QSpinBox(self)
self.scale.setRange(0, 2)
self.scale.setValue(2)
self.denoise = QSpinBox(self)
self.denoise.setRange(0, 4)
self.denoise.setValue(1)
buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, self);
layout = QFormLayout(self)
layout.addRow("Image type", self.imagetype)
layout.addRow("Scale", self.scale)
layout.addRow("Denoise", self.denoise)
layout.addWidget(buttonBox)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.reject)
def getInputs(self):
if self.imagetype.currentText() == "photo":
self.image_type = 'p'
else:
self.image_type = 'a'
return (self.image_type, self.scale.text(), self.denoise.text())
class InputDialog_PDFcut(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.multipage = QCheckBox(self)
self.multipage.setChecked(True)
self.multipage.toggled.connect(self.hide)
self.croppage_l = QLabel()
self.croppage_l.setText("Page used as cropbox for all pages")
self.croppage = QSpinBox(self)
self.croppage.setRange(1, 1000)
self.croppage.setValue(1)
self.croppage.setVisible(False)
self.croppage_l.setVisible(False)
self.margin = QSpinBox(self)
self.margin.setRange(-200, 200)
# self.margin.setValue(1)
buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, self);
self.layout = QFormLayout(self)
self.layout.addRow("Detect all pages cropboxes", self.multipage)
self.layout.addRow(self.croppage_l, self.croppage)
self.layout.addRow("Margin", self.margin)
self.layout.addWidget(buttonBox)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.reject)
def getInputs(self):
return (self.multipage.isChecked(), self.croppage.value(), self.margin.value())
def hide(self):
if self.multipage.isChecked():
self.croppage.setEnabled(False)
self.croppage.setVisible(False)
self.croppage_l.setVisible(False)
else:
self.croppage.setEnabled(True)
self.croppage.setVisible(True)
self.croppage_l.setVisible(True)
class PrefDialog(QDialog):
def __init__(self, prefs, parent=None):
super().__init__(parent)
self.setObjectName("Preferences")
print ('default_pref' + str(prefs))
self.layout = QFormLayout(self)
self.text_link = QLineEdit(prefs[0], self)
self.text_link.setMaxLength(3)
# resolution raster
self.res_box = QSpinBox(self)
self.res_box.setRange(50, 1200)
self.res_box.setValue(prefs[1])
# file parser
self.btn_convertor = QComboBox(self)
self.btn_convertor.addItem('OpenOffice')
self.btn_convertor.addItem('CloudConvert')
self.btn_convertor.setCurrentText(prefs[2])
# ontop
self.ontop = QCheckBox(self)
self.ontop.setChecked(prefs[3])
# self.btn_convertor.setObjectName("btn_conv")
# self.btn_convertor.activated[str].connect(self.color_box_change)
self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, self);
self.layout.addRow("OCR language", self.text_link)
self.layout.addRow("File convertor", self.btn_convertor)
self.layout.addRow("Rastering resolution (DPI)", self.res_box)
self.layout.addRow("Window always on top", self.ontop)
self.layout.addWidget(self.buttonBox)
self.buttonBox.accepted.connect(self.accept)
self.buttonBox.rejected.connect(self.reject)
self.resize(50, 200)
def getInputs(self):
self.destroy()
return self.text_link.text(), self.res_box.value(), self.btn_convertor.currentText(), self.ontop.isChecked()
class Window(QMainWindow):
def open_url(self):
url = 'http://github.com/devrosx/PrintManager/'
subprocess.run(['/usr/bin/open', url]) # Pouze pro macOS
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.setWindowTitle("PrintManager " + version)
if default_pref[3] == 1:
self.setWindowFlags(Qt.WindowStaysOnTopHint)
self.setAcceptDrops(True)
menubar = self.menuBar()
menubar.setNativeMenuBar(True)
file_menu = QMenu('File', self)
edit_menu = QMenu('Edit', self)
win_menu = QMenu('Windows', self)
about_menu = QMenu('About', self)
open_action = QAction("Open file", self)
printing_setting_menu = QAction("Printers", self)
printing_setting_menu.setShortcut('Ctrl+P')
printing_setting_menu.setCheckable(True)
printing_setting_menu.setChecked(True)
printing_setting_menu.triggered.connect(self.togglePrintWidget)
win_menu.addAction(printing_setting_menu)
# DEBUG PANEL
debug_setting_menu = QAction("Debug", self)
debug_setting_menu.setShortcut('Ctrl+D')
debug_setting_menu.setCheckable(True)
debug_setting_menu.setChecked(True)
debug_setting_menu.triggered.connect(self.toggleDebugWidget)
win_menu.addAction(debug_setting_menu)
# PREVIEW PANEL
printing_setting_menu = QAction("Preview panel", self)
printing_setting_menu.setShortcut('Ctrl+I')
printing_setting_menu.setCheckable(True)
printing_setting_menu.setChecked(False)
printing_setting_menu.triggered.connect(self.togglePreviewWidget)
win_menu.addAction(printing_setting_menu)
# EDIT PAGE
select_all = QAction("Select all", self)
select_all.setShortcut('Ctrl+A')
select_all.triggered.connect(self.select_all_action)
edit_menu.addAction(select_all)
rotate_90cw = QAction("Rotate 90cw", self)
rotate_90cw.setShortcut('Ctrl+R')
rotate_90cw.triggered.connect(lambda: self.rotator(angle=90))
edit_menu.addAction(rotate_90cw)
rotate_180 = QAction("Rotate 180", self)
rotate_180.setShortcut('Ctrl+Alt+Shift+R')
rotate_180.triggered.connect(lambda: self.rotator(angle=180))
edit_menu.addAction(rotate_180)
clear_all = QAction("Clear all files", self)
clear_all.setShortcut('Ctrl+X')
clear_all.triggered.connect(self.clear_table)
edit_menu.addAction(clear_all)
# PREVIEW
preview_menu = QAction("Preview", self)
preview_menu.setShortcut('F1')
preview_menu.triggered.connect(self.preview_window)
win_menu.addAction(preview_menu)
# PREFERENCES
pref_action = QAction("Preferences", self)
pref_action.triggered.connect(self.open_dialog)
pref_action.setShortcut('Ctrl+W')
file_menu.addAction(pref_action)
# GITHUB PAGE
url_action = QAction("PrintManager Github", self)
url_action.triggered.connect(self.open_url)
about_menu.addAction(url_action)
# OPEN
open_action.triggered.connect(self.openFileNamesDialog)
open_action.setShortcut('Ctrl+O')
file_menu.addAction(open_action)
close_action = QAction(' &Exit', self)