-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpdfRead.py
76 lines (67 loc) · 2.79 KB
/
pdfRead.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
import PyPDF2
import os
from PIL import Image
import sys
import cv2
import pytesseract
currentFolder = os.path.dirname(sys.argv[1])
os.chdir(currentFolder)
pdf = open(str(sys.argv[1]) , 'rb')
reader = PyPDF2.PdfFileReader(pdf)
pages = reader.getNumPages()
def imagetoText(img):
text = pytesseract.image_to_string(img)
text_file = open(img +'.txt','w')
n = text_file.write(text)
text_file.close()
for i in range(pages):
page = reader.getPage(i)
temp = page.extractText()
x = os.path.join(currentFolder, "sample.txt")
with open(x, "a") as file_object:
file_object.write(temp)
if '/XObject' in page['/Resources'].keys():
if'/Im1'in page['/Resources']['/XObject']:
xObject = page['/Resources']['/XObject']['/Im1'].getObject
else:
#theres still some issues here
xObject = page['/Resources']['/XObject'].getObject()
for obj in xObject:
if xObject[obj]['/Subtype'] == '/Image':
size = (xObject[obj]['/Width'], xObject[obj]['/Height'])
data = xObject[obj].getData()
if xObject[obj]['/ColorSpace'] == '/DeviceRGB':
mode = "RGB"
else:
mode = "P"
if '/Filter' in xObject[obj]:
if xObject[obj]['/Filter'] == '/FlateDecode':
img = Image.frombytes(mode,size,data)
x = os.path.join(currentFolder,obj[1:] + ".png")
img.save(x)
imagetoText(x)
elif xObject[obj]['/Filter'] == '/DCTDecode':
img = open(obj[1:] + ".jpg", "wb")
img.write(data)
img.close()
x = os.path.join(currentFolder,obj[1:] + ".jpg")
imagetoText(x)
elif xObject[obj]['/Filter'] == '/JPXDecode':
img = open(obj[1:] + ".jp2", "wb")
img.write(data)
img.close()
x = os.path.join(currentFolder,obj[1:] + ".jp2")
imagetoText(x)
elif xObject[obj]['/Filter'] == '/CCITTFaxDecode':
img = open(obj[1:] + ".tiff", "wb")
img.write(data)
img.close()
x = os.path.join(currentFolder,obj[1:] + ".tiff")
imagetoText(x)
else:
img = Image.frombytes(mode, size, data)
img.save(obj[1:] + ".png")
x = os.path.join(currentFolder,obj[1:] + ".png")
imagetoText(x)
else:
print("No image found.")