pdfreader 0.1.14__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. pdfreader/__init__.py +8 -0
  2. pdfreader/buffer.py +188 -0
  3. pdfreader/codecs/__init__.py +13 -0
  4. pdfreader/codecs/agl.py +4289 -0
  5. pdfreader/codecs/cmaps/Adobe-CNS1-0 +134 -0
  6. pdfreader/codecs/cmaps/Adobe-CNS1-3 +151 -0
  7. pdfreader/codecs/cmaps/Adobe-CNS1-4 +152 -0
  8. pdfreader/codecs/cmaps/Adobe-GB1-0 +109 -0
  9. pdfreader/codecs/cmaps/Adobe-GB1-2 +165 -0
  10. pdfreader/codecs/cmaps/Adobe-GB1-4 +195 -0
  11. pdfreader/codecs/cmaps/Adobe-Japan1-1 +111 -0
  12. pdfreader/codecs/cmaps/Adobe-Japan1-2 +113 -0
  13. pdfreader/codecs/cmaps/Adobe-Japan1-4 +138 -0
  14. pdfreader/codecs/cmaps/Adobe-Japan1-5 +157 -0
  15. pdfreader/codecs/cmaps/Adobe-Korea1-0 +114 -0
  16. pdfreader/codecs/cmaps/Adobe-Korea1-1 +149 -0
  17. pdfreader/codecs/cmaps/Adobe-Korea1-2 +149 -0
  18. pdfreader/codecs/cmaps/Identity-H +337 -0
  19. pdfreader/codecs/cmaps/README.md +1 -0
  20. pdfreader/codecs/codec.py +137 -0
  21. pdfreader/codecs/decoder.py +195 -0
  22. pdfreader/codecs/differences.py +75 -0
  23. pdfreader/codecs/macroman.py +69 -0
  24. pdfreader/codecs/pdfdoc.py +78 -0
  25. pdfreader/codecs/standard.py +50 -0
  26. pdfreader/codecs/tests.py +22 -0
  27. pdfreader/codecs/winansi.py +72 -0
  28. pdfreader/codecs/zapfdingbatsgl.py +205 -0
  29. pdfreader/constants.py +128 -0
  30. pdfreader/document.py +169 -0
  31. pdfreader/exceptions.py +12 -0
  32. pdfreader/filters/__init__.py +20 -0
  33. pdfreader/filters/ascii85.py +38 -0
  34. pdfreader/filters/asciihex.py +54 -0
  35. pdfreader/filters/ccittfax.py +554 -0
  36. pdfreader/filters/crypt.py +5 -0
  37. pdfreader/filters/dct.py +5 -0
  38. pdfreader/filters/flate.py +32 -0
  39. pdfreader/filters/jbig2.py +5 -0
  40. pdfreader/filters/jpx.py +5 -0
  41. pdfreader/filters/lzw.py +304 -0
  42. pdfreader/filters/predictors.py +33 -0
  43. pdfreader/filters/runlength.py +55 -0
  44. pdfreader/filters/test_ccittf_fax.py +144 -0
  45. pdfreader/filters/tests.py +22 -0
  46. pdfreader/parsers/__init__.py +4 -0
  47. pdfreader/parsers/base.py +741 -0
  48. pdfreader/parsers/cmap.py +268 -0
  49. pdfreader/parsers/content.py +88 -0
  50. pdfreader/parsers/document.py +627 -0
  51. pdfreader/parsers/inlineimage.py +73 -0
  52. pdfreader/parsers/objstm.py +16 -0
  53. pdfreader/parsers/tests.py +24 -0
  54. pdfreader/pillow.py +113 -0
  55. pdfreader/registry.py +48 -0
  56. pdfreader/securityhandler.py +333 -0
  57. pdfreader/tests.py +18 -0
  58. pdfreader/types/__init__.py +7 -0
  59. pdfreader/types/cmap.py +395 -0
  60. pdfreader/types/constants.py +235 -0
  61. pdfreader/types/content.py +92 -0
  62. pdfreader/types/filestructure.py +52 -0
  63. pdfreader/types/native.py +198 -0
  64. pdfreader/types/objects.py +523 -0
  65. pdfreader/types/tests.py +20 -0
  66. pdfreader/types/xref.py +165 -0
  67. pdfreader/utils.py +57 -0
  68. pdfreader/viewer/__init__.py +5 -0
  69. pdfreader/viewer/canvas.py +61 -0
  70. pdfreader/viewer/graphicsstate.py +99 -0
  71. pdfreader/viewer/pdfviewer.py +331 -0
  72. pdfreader/viewer/resources.py +64 -0
  73. pdfreader/viewer/simple.py +233 -0
  74. pdfreader/viewer/tests.py +20 -0
  75. pdfreader-0.1.14.dist-info/LICENSE +21 -0
  76. pdfreader-0.1.14.dist-info/METADATA +121 -0
  77. pdfreader-0.1.14.dist-info/RECORD +79 -0
  78. pdfreader-0.1.14.dist-info/WHEEL +5 -0
  79. pdfreader-0.1.14.dist-info/top_level.txt +1 -0
pdfreader/constants.py ADDED
@@ -0,0 +1,128 @@
1
+ DEFAULT_ENCODING = "latin-1"
2
+
3
+ NULL = b'\x00'
4
+ TAB = b'\x09'
5
+ LF = b'\x0a' # \n
6
+ FF = b'\x0c'
7
+ CR = b'\x0d' # \r
8
+ SP = b'\x20'
9
+
10
+ DELIMITERS = (b'(', b')', b'<', b'>', b'[', b']', b'{', b'}', b'/', b'%')
11
+ WHITESPACES = (NULL, TAB, LF, FF, CR, SP)
12
+
13
+ WHITESPACE_CODES = [ord(c) for c in WHITESPACES]
14
+
15
+ EOL = (CR + LF, LF + CR, CR, LF)
16
+
17
+ TYPE_BOOL = "bool"
18
+ TYPE_INT = "int"
19
+ TYPE_REAL = "real"
20
+ TYPE_INSTRUCTION = "instruction"
21
+ TYPE_STRING = "string"
22
+ TYPE_HEXSTRING = "hexstring"
23
+ TYPE_ARRAY = "array"
24
+ TYPE_DICT = "dict"
25
+ TYPE_COMMENT = "comment"
26
+ TYPE_NAME = "name"
27
+ TYPE_STREAM = "stream"
28
+ TYPE_NULL = "null"
29
+
30
+ # String Escaped Chars
31
+ # \n | LINE FEED (0Ah) (LF)
32
+ # \r | CARRIAGE RETURN (0Dh) (CR)
33
+ # \t | HORIZONTAL TAB (09h) (HT)
34
+ # \b | BACKSPACE (08h) (BS)
35
+ # \f | FORM FEED (FF)
36
+ # \( | LEFT PARENTHESIS (28h)
37
+ # \) | RIGHT PARENTHESIS (29h)
38
+ # \\ | REVERSE SOLIDUS (5Ch) (Backslash)
39
+ # \ddd | Character code ddd (octal)
40
+
41
+ STRING_ESCAPED = {b'n': b"\n",
42
+ b'r': b"\r",
43
+ b't': b"\t",
44
+ b'b': b"\x08",
45
+ b'f': b"\x0c",
46
+ b'(': b"(",
47
+ b')': b")",
48
+ b'\\':b"\\"}
49
+
50
+ ESCAPED_CHARS = {"\n": "\\n",
51
+ "\r": "\\r",
52
+ "\t": "\\t",
53
+ "\x08": "\\b",
54
+ "\x0c": "\\f",
55
+ "(": "\\(",
56
+ ")": "\\)",
57
+ "\\": "\\\\"}
58
+
59
+ # maps predefined cmap name to character collection
60
+ predefined_cmap_names = {
61
+ # Chinese (simplified)
62
+ 'GB-EUK-H': 'Adobe-GB1-0',
63
+ 'GB-EUK-V': 'Adobe-GB1-0',
64
+ 'GBpc-EUK-H': 'Adobe-GB1-0',
65
+ 'GBpc-EUK-V': 'Adobe-GB1-0',
66
+ 'GBK-EUK-H': 'Adobe-GB1-2',
67
+ 'GBKp-EUK-V': 'Adobe-GB1-2',
68
+ 'GBK2K-EUK-H': 'Adobe-GB1-4',
69
+ 'GBK2K-EUK-V': 'Adobe-GB1-4',
70
+ 'UniGB-UCS2-H': 'Adobe-GB1-4',
71
+ 'UniGB-UCS2-V': 'Adobe-GB1-4',
72
+ 'UniGB-UTF16-H': 'Adobe-GB1-4',
73
+ 'UniGB-UTF16-V': 'Adobe-GB1-4',
74
+ # Chinese (traditional)
75
+ 'B5pc-H': 'Adobe-CNS1-0',
76
+ 'B5pc-V': 'Adobe-CNS1-0',
77
+ 'HKscs-B5-H': 'Adobe-CNS1-3',
78
+ 'HKscs-B5-V': 'Adobe-CNS1-3',
79
+ 'ETen-B5-H': 'Adobe-CNS1-0',
80
+ 'ETen-B5-V': 'Adobe-CNS1-0',
81
+ 'ETenms-B5-H': 'Adobe-CNS1-0',
82
+ 'ETenms-B5-V': 'Adobe-CNS1-0',
83
+ 'CNS-EUC-H': 'Adobe-CNS1-0',
84
+ 'CNS-EUC-V': 'Adobe-CNS1-0',
85
+ 'UniCNS-UCS2-H': 'Adobe-CNS1-3',
86
+ 'UniCNS-UCS2-V': 'Adobe-CNS1-3',
87
+ 'UniCNS-UTF16-H': 'Adobe-CNS1-4',
88
+ 'UniCNS-UTF16-V': 'Adobe-CNS1-4',
89
+ # Japanese
90
+ '83pv-RKSJ-H': 'Adobe-Japan1-1',
91
+ '83pv-RKSJ-V': 'Adobe-Japan1-1',
92
+ '90ms-RKSJ-H': 'Adobe-Japan1-2',
93
+ '90ms-RKSJ-V': 'Adobe-Japan1-2',
94
+ '90msp-RKSJ-H': 'Adobe-Japan1-2',
95
+ '90msp-RKSJ-V': 'Adobe-Japan1-2',
96
+ '90pv-RKSJ-H': 'Adobe-Japan1-1',
97
+ '90pv-RKSJ-V': 'Adobe-Japan1-1',
98
+ 'Add-RKSJ-H': 'Adobe-Japan1-1',
99
+ 'Add-RKSJ-V': 'Adobe-Japan1-1',
100
+ 'EUC-H': 'Adobe-Japan1-1',
101
+ 'EUC-V': 'Adobe-Japan1-1',
102
+ 'Ext-RKSJ-H': 'Adobe-Japan1-2',
103
+ 'Ext-RKSJ-V': 'Adobe-Japan1-2',
104
+ 'H': 'Adobe-Japan1-1',
105
+ 'V': 'Adobe-Japan1-1',
106
+ 'UniJIS-UCS2-H': 'Adobe-Japan1-4',
107
+ 'UniJIS-UCS2-V': 'Adobe-Japan1-4',
108
+ 'UniJIS-UCS2-HW-H': 'Adobe-Japan1-4',
109
+ 'UniJIS-UCS2-HW-V': 'Adobe-Japan1-4',
110
+ 'UniJIS-UTF16-H': 'Adobe-Japan1-5',
111
+ 'UniJIS-UTF16-V': 'Adobe-Japan1-5',
112
+ # Korean
113
+ 'KSC-EUC-H': 'Adobe-Korea1-0',
114
+ 'KSC-EUC-V': 'Adobe-Korea1-0',
115
+ 'KSCms-UHC-H': 'Adobe-Korea1-1',
116
+ 'KSCms-UHC-V': 'Adobe-Korea1-1',
117
+ 'KSCms-UHC-HW-H': 'Adobe-Korea1-1',
118
+ 'KSCms-UHC-HW-V': 'Adobe-Korea1-1',
119
+ 'KSCpc-EUC-H': 'Adobe-Korea1-0',
120
+ 'KSCpc-EUC-V': 'Adobe-Korea1-0',
121
+ 'UniKS-UCS2-H': 'Adobe-Korea1-1',
122
+ 'UniKS-UCS2-V': 'Adobe-Korea1-1',
123
+ 'UniKS-UTF16-H': 'Adobe-Korea1-2',
124
+ 'UniKS-UTF16-V': 'Adobe-Korea1-2',
125
+ # Generic
126
+ 'Identity-H': 'Identity-H',
127
+ 'Identity-V': 'Identity-H'
128
+ }
pdfreader/document.py ADDED
@@ -0,0 +1,169 @@
1
+ import logging
2
+ log = logging.getLogger(__name__)
3
+
4
+ from .registry import Registry
5
+ from .parsers import RegistryPDFParser
6
+ from .securityhandler import security_handler_factory
7
+ from .types import IndirectObject, Stream, Array, Dictionary, IndirectReference, obj_factory
8
+ from .utils import cached_property, from_pdf_datetime
9
+
10
+
11
+ class PDFDocument(object):
12
+ """
13
+ Represents PDF document structure
14
+
15
+ :param fobj: file-like object: binary file descriptor, BytesIO stream etc.
16
+ :param password: Optional. Password to access PDF content. Defaults to the empty string.
17
+
18
+ """
19
+ #: contains PDF file header data
20
+ header = None
21
+ #: contains PDF file trailer data
22
+ trailer = None
23
+ #: references to document's Catalog instance
24
+ root = None
25
+
26
+ def __init__(self, fobj, password=''):
27
+ """ Constructor method
28
+ """
29
+
30
+ self.registry = Registry()
31
+
32
+ self.parser = RegistryPDFParser(fobj, self.registry)
33
+ self.header = self.parser.header
34
+ self.trailer = self.parser.trailer
35
+
36
+ if self.encrypt and self.encrypt.Filter != "Standard":
37
+ raise ValueError("Unsupported encryption handler {}".format(self.encrypt.Filter))
38
+
39
+ if self.encrypt:
40
+ sec_handler = security_handler_factory(self.trailer.id, self.encrypt, password)
41
+ self.parser.set_security_handler(sec_handler)
42
+
43
+ self.root = self.obj_by_ref(self.trailer.root)
44
+
45
+ def __enter__(self):
46
+ return self
47
+
48
+ def __exit__(self, type, value, traceback):
49
+ return
50
+
51
+ @cached_property
52
+ def encrypt(self):
53
+ """
54
+ Document's Encrypt dictionary (if present)
55
+
56
+ :return: dict or None
57
+ """
58
+ res = None
59
+ obj = self.trailer.encrypt
60
+ if obj:
61
+ res = self.locate_encrypt_by_ref(obj) if isinstance(obj, IndirectReference) else obj
62
+ return res
63
+
64
+ def build(self, obj, visited=None, lazy=True):
65
+ """
66
+ Resolves all indirect references for the object.
67
+
68
+ :param obj: an object from the document
69
+ :type obj: one of supported PDF types
70
+
71
+ :param lazy: don't resolve subsequent indirect references if True (default).
72
+ :type lazy: bool
73
+
74
+ :param visited: Shouldn't be used. Internal param containing already resolved objects
75
+ to not fall into infinite loops
76
+ """
77
+ log.debug("Buliding {}".format(obj))
78
+ if visited is None:
79
+ visited = []
80
+
81
+ on_return = None
82
+ if isinstance(obj, IndirectReference):
83
+ if obj not in visited:
84
+ visited.append(obj)
85
+ on_return = visited.pop
86
+ obj = self.obj_by_ref(obj)
87
+
88
+ # resolve subsequent references for Arrays, Dictionaries and Streams
89
+ if isinstance(obj, Array):
90
+ obj = [self.build(o, visited, lazy) for o in obj]
91
+ elif isinstance(obj, Dictionary):
92
+ if not lazy:
93
+ obj = {k: self.build(o, visited, lazy) for k, o in obj.items()}
94
+ obj = obj_factory(self, obj)
95
+ elif isinstance(obj, Stream):
96
+ if not lazy:
97
+ obj.dictionary = {k: (self.build(o, visited, lazy)) for k, o in obj.dictionary.items()}
98
+ obj = obj_factory(self, obj)
99
+ elif isinstance(obj, IndirectObject):
100
+ # normally this shouldn't happen, but ponentially we can build it
101
+ log.warning("Attempt to build an indirect object. Possibly a bug.")
102
+ obj = self.build(obj.val, visited, lazy)
103
+
104
+ if on_return:
105
+ on_return()
106
+ return obj
107
+
108
+ def locate_object(self, num, gen):
109
+ return self.parser.locate_object(num, gen)
110
+
111
+ def obj_by_ref(self, objref):
112
+ obj = self.parser.locate_object(objref.num, objref.gen)
113
+ return obj_factory(self, obj)
114
+
115
+ def locate_encrypt_by_ref(self, objref):
116
+ """ Locates Encrypt object by ref from a stream-style xref.
117
+ In some cases for encrypted files this reference is missing from Xref table
118
+ but the indirect object comes right before the xref stream.
119
+ """
120
+ obj = self.parser.locate_object_in_registry(objref.num, objref.gen) \
121
+ or self.parser.locate_object_by_xref(objref.num, objref.gen) \
122
+ or self.parser.locate_backwards_from_trailer(objref.num, objref.gen) \
123
+ or self.parser.locate_object(objref.num, objref.gen)
124
+
125
+ return obj_factory(self, obj)
126
+
127
+ def deep_obj_by_ref(self, obj, maxdepth=100):
128
+ counter = maxdepth
129
+ while isinstance(obj, IndirectObject) and counter:
130
+ obj = self.obj_by_ref(obj)
131
+ counter -= 1
132
+
133
+ if isinstance(obj, IndirectObject):
134
+ raise ValueError("Max reference depth exceeded")
135
+ return obj
136
+
137
+ def pages(self):
138
+ """
139
+ Yields document pages one by one.
140
+
141
+ :return: :class:`~pdfreader.types.objects.Page` generator.
142
+ """
143
+ return self.root.Pages.pages()
144
+
145
+ @property
146
+ def metadata(self):
147
+ """
148
+ Returns document metadata from file's trailer info dict
149
+
150
+ :return: dict, if metadata exists `None` otherwise.
151
+ """
152
+ res = None
153
+ info = self.trailer.info
154
+ if info:
155
+ res = self.locate_object(info.num, info.gen)
156
+ for k, v in res.items():
157
+ if isinstance(v, bytes):
158
+ try:
159
+ res[k] = v.decode()
160
+ if k in ('CreationDate', 'ModDate'):
161
+ res[k] = from_pdf_datetime(res[k])
162
+ except (UnicodeDecodeError, ValueError, TypeError):
163
+ pass
164
+ return res
165
+
166
+
167
+ if __name__ == "__main__":
168
+ import doctest
169
+ doctest.testmod()
@@ -0,0 +1,12 @@
1
+
2
+
3
+ class ParserException(Exception):
4
+ pass
5
+
6
+
7
+ class TokenNotFound(ParserException):
8
+ pass
9
+
10
+
11
+ class EOFException(Exception):
12
+ pass
@@ -0,0 +1,20 @@
1
+ from itertools import product, chain
2
+
3
+ from . import ascii85, asciihex, flate, lzw, runlength, ccittfax, dct, jbig2, jpx, crypt
4
+
5
+ decoders = (ascii85, asciihex, flate, lzw, runlength, ccittfax, dct, jbig2, jpx, crypt)
6
+
7
+ decoders_by_name = dict(chain.from_iterable(list(product(m.filter_names, [m])) for m in decoders))
8
+
9
+
10
+ def apply_filter(name, binary, params=None):
11
+ decoder = decoders_by_name.get(name)
12
+ if decoder is None:
13
+ raise NotImplementedError(decoder)
14
+ return decoder.decode(binary, params or {})
15
+
16
+ # Not implemented:
17
+ # - dct
18
+ # - jbig2
19
+ # - jpx
20
+ # - crypt
@@ -0,0 +1,38 @@
1
+ import logging
2
+ log = logging.getLogger(__name__)
3
+
4
+ from base64 import a85decode
5
+
6
+ from ..constants import WHITESPACES
7
+
8
+ filter_names = ('ASCII85Decode', 'A85')
9
+
10
+
11
+ def decode(data, *_):
12
+ """
13
+ >>> from base64 import a85encode
14
+ >>> data = a85encode(b'sample data') + b'~>'
15
+ >>> decode(data)
16
+ b'sample data'
17
+
18
+ >>> data = b"BROKEN_STREAM"
19
+ >>> decode(data)
20
+ b''
21
+ """
22
+ # filter whitespaces
23
+ ws = b''.join(WHITESPACES)
24
+ data = bytes([n for n in data if n not in ws])
25
+ try:
26
+ if data.endswith(b'~>'):
27
+ res = a85decode(data[:-2])
28
+ else:
29
+ raise ValueError("EOD ~> expected")
30
+ except (TypeError, ValueError):
31
+ log.exception("Skipping broken stream")
32
+ res = b''
33
+ return res
34
+
35
+
36
+ if __name__ == "__main__":
37
+ import doctest
38
+ doctest.testmod()
@@ -0,0 +1,54 @@
1
+ import logging
2
+ log = logging.getLogger(__name__)
3
+
4
+ from ..constants import WHITESPACES, DEFAULT_ENCODING
5
+
6
+
7
+ filter_names = ('ASCIIHexDecode', 'AHx')
8
+
9
+
10
+ def decode(data, *_):
11
+ """
12
+ >>> data = b"646174612073616d706c65>"
13
+ >>> decode(data)
14
+ b'data sample'
15
+
16
+ >>> data = b"64617461207 3616d\\n706c65>"
17
+ >>> decode(data)
18
+ b'data sample'
19
+
20
+ >>> data = b"64617461207 3616d\\n706c652>"
21
+ >>> decode(data)
22
+ b'data sample '
23
+
24
+ >>> data = b"BROKEN_STREAM>"
25
+ >>> decode(data)
26
+ b''
27
+ """
28
+ buffer = b""
29
+ res = b""
30
+ try:
31
+ for i in range(0, len(data)):
32
+ c = data[i:i + 1]
33
+ if c in WHITESPACES:
34
+ continue
35
+ elif c == b">":
36
+ break
37
+ buffer += c
38
+ if len(buffer) > 1:
39
+ res += bytes.fromhex(buffer.decode(DEFAULT_ENCODING))
40
+ buffer = b""
41
+
42
+ if buffer:
43
+ if len(buffer) == 1:
44
+ buffer += b"0"
45
+ res += bytes.fromhex(buffer.decode(DEFAULT_ENCODING))
46
+ except ValueError:
47
+ # invalid characters on stream
48
+ log.exception("Skipping broken stream")
49
+ return res
50
+
51
+
52
+ if __name__ == "__main__":
53
+ import doctest
54
+ doctest.testmod()