-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpdftools_utils.py
More file actions
74 lines (70 loc) · 2.21 KB
/
pdftools_utils.py
File metadata and controls
74 lines (70 loc) · 2.21 KB
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
"""
Helper utilities for PDFtools
"""
import pypdf
def ispdf(pathfile):
try:
with open(pathfile, "rb") as fh:
Reader = pypdf.PdfReader(fh)
return True # PDF file
except pypdf.utils.PdfReadError:
return False # not a PDF file
def getNumPages(pathfile):
N = 0
if ispdf(pathfile) and not isRestricted(pathfile):
with open(pathfile, "rb") as fh:
Reader = pypdf.PdfReader(fh)
N = len(Reader.pages)
return N
def pages(pageString, N):
'''
Convert page specification into a list of pages
pageString - comma separated string of pages and page ranges
N - total number of pages in the document
'''
s_l = [item.strip() for item in pageString.split(',')]
pageRange = list()
for item in s_l:
if '-' in item:
l = item.split('-')
if len(l) > 2:
print('More than 1 dash not allowed in page range')
continue
if (not l[0].isnumeric()) or (not l[1].isnumeric()):
print('Non-numeric page not allowed')
continue
be = int(l[0]) - 1 # zero-based
ed = int(l[1]) - 1
if be <= ed:
while be <= ed:
if be in range(0, N):
pageRange.append(be)
be += 1
else:
while be >= ed:
if be in range(0, N):
pageRange.append(be)
be -= 1
else:
if not item.isnumeric():
print('Non-numeric page not allowed')
continue
pg = int(item) - 1 # zero-based
if pg in range(0, N):
pageRange.append(pg)
return pageRange
def isRestricted(pathfile):
'''
Return true if file is not decryptable (eg. file is restricted).
'''
restricted = False
with open(pathfile, "rb") as fh:
Reader = pypdf.PdfReader(fh)
if Reader.is_encrypted:
try:
Reader.decrypt('')
except NotImplementedError:
restricted = True
except Exception:
restricted = True
return restricted