-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cropper.py
425 lines (364 loc) · 16.2 KB
/
Cropper.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
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Design.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
from PyPDF2 import PdfWriter, PdfReader
from PyPDF2 import PdfMerger
from pathlib import Path
import functools
import glob, sys, fitz
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(890, 769)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout_2 = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout_2.setObjectName("gridLayout_2")
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint)
self.gridLayout.setObjectName("gridLayout")
self.Import = QtWidgets.QPushButton(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.Import.sizePolicy().hasHeightForWidth())
self.Import.setSizePolicy(sizePolicy)
self.Import.setMinimumSize(QtCore.QSize(100, 40))
self.Import.setMaximumSize(QtCore.QSize(16777215, 40))
self.Import.setObjectName("Import")
self.gridLayout.addWidget(self.Import, 1, 3, 1, 1)
self.label = QtWidgets.QLabel(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
self.label.setScaledContents(True)
self.label.setObjectName("label")
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.verticalLayout.addWidget(self.label)
self.gridLayout.addLayout(self.verticalLayout, 2, 0, 1, 4)
self.Crop = QtWidgets.QPushButton(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.Crop.sizePolicy().hasHeightForWidth())
self.Crop.setSizePolicy(sizePolicy)
self.Crop.setObjectName("Crop")
self.gridLayout.addWidget(self.Crop, 3, 1, 1, 1)
self.Right = QtWidgets.QPushButton(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.Right.sizePolicy().hasHeightForWidth())
self.Right.setSizePolicy(sizePolicy)
self.Right.setObjectName("Right")
self.gridLayout.addWidget(self.Right, 3, 3, 1, 1)
self.Left = QtWidgets.QPushButton(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.Left.sizePolicy().hasHeightForWidth())
self.Left.setSizePolicy(sizePolicy)
self.Left.setObjectName("Left")
self.gridLayout.addWidget(self.Left, 3, 0, 1, 1)
self.Reset = QtWidgets.QPushButton(self.centralwidget)
self.Reset.setObjectName("Reset")
self.gridLayout.addWidget(self.Reset, 3, 2, 1, 1)
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.lineEdit.sizePolicy().hasHeightForWidth())
self.lineEdit.setSizePolicy(sizePolicy)
self.lineEdit.setObjectName("lineEdit")
self.gridLayout.addWidget(self.lineEdit, 1, 0, 1, 3)
self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.Import.clicked.connect(self.import_clicked)
self.Right.clicked.connect(self.right_clicked)
self.Left.clicked.connect(self.left_clicked)
self.Crop.clicked.connect(self.crop_clicked)
self.Reset.clicked.connect(self.reset_clicked)
self.labelcount = 1
Page.init()
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.Import.setText(_translate("MainWindow", "Import"))
self.Crop.setText(_translate("MainWindow", "Crop"))
self.Right.setText(_translate("MainWindow", ">"))
self.Left.setText(_translate("MainWindow", "<"))
self.Reset.setText(_translate("MainWindow", "Reset"))
def reset_clicked(self):
self.resetVertical()
self.newLabelVertical()
Page.init()
def crop_clicked(self):
if(not Page.valid):
self.resetVertical()
self.newLabelVertical()
self.label.setText("File not imported!")
return
if(Page.cropped <= 0):
print("Not cropped!")
return
try:
self.newBlank()
except Exception as e:
print(e)
print("newBlank error")
try:
self.mergeBlank()
self.refresh_page(0)
except Exception as e:
print(e)
print("mergeBlank error")
def resetVertical(self):
try:
while (self.verticalLayout.count()>0):
item = self.verticalLayout.itemAt(0)
widget = item.widget()
widget.deleteLater()
self.verticalLayout.removeWidget(widget)
self.labelcount = 0
except:
print("reset fail!")
def newLabelVertical(self):
try:
self.label = QtWidgets.QLabel(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
self.label.setScaledContents(True)
self.labelcount += 1
self.label.setObjectName("%i" % self.labelcount)
self.label.labelIndex = self.labelcount
self.verticalLayout.addWidget(self.label)
self.label.mousePressEvent = functools.partial(self.getPos, source_object=self.label)
except:
print("new label fail")
def refresh_page(self,count):
try:
if(Page.valid):
index = self.checkValidPage(count)
self.resetVertical()
self.newLabelVertical()
self.label.setPixmap(QtGui.QPixmap("data/%i.png" % index))
Page.currentPage = index
Page.cropped = 0
self.label.adjustSize()
except:
print("refresh fail")
def checkValidPage(self, count):
index = Page.currentPage
index += count
if(index< 0):
index = 0
if(index == Page.maxPage()):
index = Page.maxPage() - 1
return index
def right_clicked(self):
self.refresh_page(1)
def left_clicked(self):
self.refresh_page(-1)
def convertToImage(self, fromPath, toPath):
Page.doc = fitz.open(fromPath) # open document
zoom_x = 2.0 # horizontal zoom
zoom_y = 2.0 # vertical zoom
mat = fitz.Matrix(zoom_x, zoom_y) # zoom factor 2 in each dimension
for page in Page.doc: # iterate through the pages
pix = page.get_pixmap(matrix=mat) # render page to an image
pix.save(toPath + "%i.png" % page.number) # store image as a PNG
Page.height.append(page.mediabox[3])
def import_clicked(self):
try:
Page.name = self.lineEdit.text()
try:
self.convertToImage(Page.name + ".pdf","data/")
except:
self.label.setText("File not found!")
Page.valid = False
self.label.adjustSize()
return
try:
Page.currentPage = 0
Page.valid = True
self.refresh_page(0)
except:
self.label.setText("PDF not converted to image or converting error.")
Page.valid = False
self.label.adjustSize()
return
except:
print("fail")
def getPos(self , event, source_object=None):
try:
labelIndex = int(source_object.objectName())
if(Page.valid):
positionABS = event.pos().y()
positionPer = positionABS/self.label.height()
self.crop(positionPer,labelIndex-1)
except Exception as e:
print(e)
print("Crop error!")
try:
self.convertToImage("data/temp.pdf","data/cropped")
except Exception as e:
print(e)
print("Convert after crop error!")
try:
self.resetVertical()
for i in range(Page.cropped + 1):
self.newLabelVertical()
self.label.setPixmap(QtGui.QPixmap("data/cropped%i.png" % i))
self.label.adjustSize()
except Exception as e:
print(e)
print("Display after crop error!")
def crop(self, position, labelIndex):
try:
writer = PdfWriter()
if(Page.cropped == 0):
reader1 = PdfReader(Page.name + ".pdf")
reader2 = PdfReader(Page.name + ".pdf")
page1 = reader1.pages[Page.currentPage]
page2 = reader2.pages[Page.currentPage]
else:
reader1 = PdfReader("data/temp.pdf")
reader2 = PdfReader("data/temp.pdf")
page1 = reader1.pages[labelIndex]
page2 = reader2.pages[labelIndex]
if(Page.cropped != 0):
reader = PdfReader("data/temp.pdf")
for i in range(0,len(reader1.pages)):
if(i < labelIndex):
page = reader.pages[i]
writer.add_page(page)
else:
break
if(page1.mediabox.bottom == 0):
page1.mediabox.lower_right = (
page1.mediabox.right,
float(page1.mediabox.top) * (1-position),
)
else:
newPos = float(page1.mediabox.bottom) + (float(page1.mediabox.top) - float(page1.mediabox.bottom))* (1-position)
page1.mediabox.lower_right = (
page1.mediabox.right,
newPos,
)
writer.add_page(page1)
if(page2.mediabox.bottom == 0):
page2.mediabox.upper_right = (
page2.mediabox.right,
float(page2.mediabox.top) * (1-position),
)
else:
page2.mediabox.upper_right = (
page2.mediabox.right,
newPos,
)
writer.add_page(page2)
if(Page.cropped != 0):
reader = PdfReader("data/temp.pdf")
for i in range(labelIndex+1,len(reader1.pages)):
page = reader.pages[i]
writer.add_page(page)
Page.cropped += 1
with open("data/temp.pdf", "wb") as fp:
writer.write(fp)
except Exception as e:
print(e)
print("crop error!")
def newBlank(self):
merger = PdfMerger()
input1 = open("data/temp.pdf", "rb")
input2 = open("data/blank.pdf", "rb")
for i in range(Page.cropped + 1):
merger.append(fileobj=input1, pages=(i, i+1))
# insert the first page of input2 into the output beginning after the second page
merger.append(fileobj=input2)
output = open("data/tempBlank.pdf", "wb")
merger.write(output)
output = open("result/"+ Page.name +str(Page.currentPage)+"_sep.pdf", "wb")
merger.write(output)
def mergeBlank(self):
from PyPDF2 import PageObject
import os
from PyPDF2 import PdfFileReader, PdfFileWriter
#Open the files that have to be merged
pdf1File = open('data/tempBlank.pdf', 'rb')
#Read the files that you have opened
pdf1Reader = PdfFileReader(pdf1File)
#Make a list of all pages
pages = []
for pageNum in range(pdf1Reader.numPages):
pageObj = pdf1Reader.getPage(pageNum)
pages.append(pageObj)
#Calculate width and height for final output page
width = pages[0].mediaBox.getWidth()
height = pages[0].mediaBox.getHeight() + pages[1].mediaBox.getHeight()
prvHeight = 0
#Create blank page to merge all pages in one page
merged_page = PageObject.createBlankPage(None, width, height)
writer = PdfFileWriter()
#Loop through all pages and merge / add them to blank page
y =0
for page in range(len(pages)):
y+=1
if y%2!=0:
x=float(pages[page].mediaBox.getHeight())
if(page != 0):
x += Page.height[Page.currentPage] - float(prvHeight)
merged_page.mergeScaledTranslatedPage(pages[page], 1,0, x)
else:
merged_page.mergeScaledTranslatedPage(pages[page], 1,0, x)
merged_page.mergePage(pages[page+1])
if y%2==0:
writer.addPage(merged_page)
width = pages[page].mediaBox.getWidth()
try:
prvHeight = pages[page-1].mediaBox[1]
height = pages[page+1].mediaBox.getHeight() + pages[page+2].mediaBox.getHeight()
merged_page = PageObject.createBlankPage(None, width, height)
except:
pass
y=0
#Create final file with one page
with open('result/'+Page.name+str(Page.currentPage)+'_merge.pdf', 'wb') as f:
writer.write(f)
class Page(object):
def __init__(self):
pass
@classmethod
def maxPage(self):
return len(Page.doc)
@classmethod
def init(self):
Page.valid = False
Page.doc = None
Page.cropped = 0
Page.currentPage = None
Page.height = []
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())