Debian Codegraph @

tools/pdfscan.py

raw
1 #! /usr/bin/env python
2 #
3 # This tool is provided by dblatex (http://dblatex.sourceforge.net) and has
4 # the same copyright.
5 #
6 # It was initially developped to find out the fonts used and their size because
7 # as strange as it may seem, no obvious tool gives the font sizes used (pdffonts
8 # just lists the font objects of the PDF). The script can be improved to give
9 # more informations in a next release.
10 #
11 # To understand the PDF format, read:
12 # * The reference:
13 # http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/
14 # pdf_reference_1-7.pdf
15 #
16 # * A usefull introduction:
17 # http://www.adobe.com/content/dam/Adobe/en/technology/pdfs/
18 # PDF_Day_A_Look_Inside.pdf
19 #
20 #
21 from __future__ import print_function
22
23 import os
24 import sys
25 import traceback
26 import zlib
27 import re
28 import logging
29 import tempfile
30 import shutil
31 import struct
32 import codecs
33
34
35 class ErrorHandler:
36 def __init__(self):
37 self._dump_stack = False
38 self.rc = 0
39
40 def dump_stack(self, dump=True):
41 self._dump_stack = dump
42
43 def failure_track(self, msg, rc=1):
44 self.rc = rc
45 print((msg), file=sys.stderr)
46 if self._dump_stack:
47 traceback.print_exc()
48
49 def failed_exit(self, rc=1):
50 self.failure_track(msg, rc)
51 sys.exit(self.rc)
52
53 def pdfstring_is_list(data):
54 return (data and data[0] == "[" and data[-1] == "]")
55
56
57 class PDFResolver:
58 _resolver = None
59
60 @classmethod
61 def set_resolver(cls, resolver):
62 cls._resolver = resolver
63
64 @classmethod
65 def get_resolver(cls):
66 return cls._resolver
67
68
69 class PDFBaseObject:
70 _log = logging.getLogger("pdfscan.base")
71
72 def __init__(self):
73 pass
74 def debug(self, text):
75 self._log.debug(text)
76 def warning(self, text):
77 self._log.warning(text)
78 def error(self, text):
79 self._log.error(text)
80 def info(self, text):
81 self._log.info(text)
82
83
84 class PDFFile(PDFBaseObject):
85 """
86 Main object that parses the PDF file and extract the objects needed for
87 scanning.
88 """
89 _log = logging.getLogger("pdfscan.pdffile")
90
91 def __init__(self, stream_manager=None):
92 self._file = None
93 self.filesize = 0
94 self.startxref_pos = 0
95 self.trailer = None
96 self.xref_first = None
97 self.xref_table = {}
98 self.xref_objstm = {}
99 self.objstm_objects = {}
100 self.page_objects = []
101 self.pdfobjects = PDFObjectGroup()
102 self.stream_manager = stream_manager or StreamManager()
103 # Create an publish the object resolver
104 self.resolver = PDFObjectResolver(self)
105 PDFResolver.set_resolver(self.resolver)
106 # Create a global font manager
107 self.fontmgr = FontManager({})
108
109 # Detect the beginning of a PDF Object
110 self.re_objstart = re.compile(r"(\d+) (\d+) obj(.*$)", re.DOTALL)
111
112 def cleanup(self):
113 self.stream_manager.cleanup()
114
115 def load(self, filename):
116 self.filesize = os.path.getsize(filename)
117 self._file = open(filename, "rb")
118 self.read_xref()
119 self.build_final_xref()
120
121 def find_startxref(self, offset_trailer=160):
122 # Look for the first xref from the end
123 offset, data = self.filesize, ""
124 while not("startxref" in data) or offset == 0:
125 offset = max(0, offset - offset_trailer)
126 self._file.seek(offset)
127 data = self._file.read(offset_trailer) + data
128
129 m = re.search(r"\sstartxref\s+(\d+)\s+%%EOF", data, re.M)
130 if not(m):
131 self.error("Problem in PDF file: startxref not found")
132 return 0
133 self.startxref_pos = int(m.group(1))
134 return self.startxref_pos
135
136 def read_xref(self):
137 startxref = self.find_startxref()
138 xref = None
139
140 while startxref:
141 self._file.seek(startxref)
142 line = self._file.readline()
143 m = re.search(r"xref\s(.*)", line, re.M|re.DOTALL)
144 if (m):
145 found_xref = PDFXrefSection(self._file)
146 found_xref.read_table(m.group(1))
147 elif self.re_objstart.search(line):
148 self.info("Xref section not found. Try to load XRef object")
149 pdfobject, remain_line = self._parse_object(startxref)
150 found_xref = PDFXrefObject(pdfobject)
151
152 startxref = int(found_xref.trailer.get("/Prev", 0))
153
154 if xref: xref.set_older(found_xref)
155 xref = found_xref
156
157 self.xref_first = xref
158
159 def build_final_xref(self):
160 xref = self.xref_first
161 while xref:
162 self.trailer = xref.trailer
163 self.xref_table.update(xref.table)
164 self.xref_objstm.update(xref.objstm)
165 xref = xref.newer
166
167 def get_objstm(self, objstm_id):
168 return self.objstm_objects.get(objstm_id, None)
169
170 def create_objstm(self, pdfobject):
171 self.debug("Create objstm %s" % pdfobject.ident())
172 pdfobject.compute()
173 pdfobject.stream_decode()
174 self.pdfobjects.add_object(pdfobject)
175 objstm = PDFObjectStream(pdfobject)
176 self.objstm_objects[objstm.ident()] = objstm
177 return objstm
178
179 def xref_resolve_object(self, ident):
180 offset = self.xref_table.get(ident, 0)
181 if offset != 0:
182 #print "Object '%s' found at offset: %d" % (ident, offset)
183 pdfobject, remain_line = self._parse_object(offset)
184 return pdfobject
185
186 def xref_resolve(self, ident):
187 # Try to resolve a standard object
188 pdfobject = self.xref_resolve_object(ident)
189 if pdfobject:
190 return pdfobject
191
192 # Find the ObjStm infos that contains that object
193 objstm_data = self.xref_objstm.get(ident, 0)
194 if objstm_data == 0:
195 self.warning("ObjStm id for '%s' not found in xref table" % ident)
196 return None
197
198 # If the ObjStm itself is not resolved, resolve it first
199 objstm_id = "%d 0" % objstm_data[0]
200 object_idx = objstm_data[1]
201
202 objstm = self.get_objstm(objstm_id)
203 if not(objstm):
204 pdfobject = self.xref_resolve_object(objstm_id)
205 if pdfobject: objstm = self.create_objstm(pdfobject)
206 if not(objstm):
207 self.error("Object '%s' cannot be resolved: ObjStm '%s' not found" \
208 % (ident, objstm_id))
209 return None
210
211 # Ok, now get the object from the ObjStm
212 pdfobject = objstm.get_object(object_idx)
213
214 return pdfobject
215
216 def resolve_object(self, ident):
217 pdfobject = self.pdfobjects.get_object(ident)
218 if not(pdfobject):
219 #print "Try to resolve object '%s'" % ident
220 pdfobject = self.xref_resolve(ident)
221 if pdfobject:
222 self.pdfobjects.add_object(pdfobject)
223 return pdfobject
224
225 def get_object(self, ident):
226 ident = ident.replace(" R", "").strip()
227 pdfobject = self.resolver.get(ident)
228 if pdfobject:
229 pdfobject.link_to(self.resolver)
230 return pdfobject
231
232 def _parse_object(self, offset):
233 pdfobj = None
234 parsed_object = None
235 remain_line = ""
236
237 self._file.seek(offset)
238
239 while not(parsed_object):
240 line = self._file.readline()
241 if not(line):
242 break
243
244 while line:
245 if pdfobj:
246 fields = line.split("endobj", 1)
247 if len(fields) > 1:
248 if fields[0]:
249 pdfobj.append_string(fields[0])
250 pdfobj.compute()
251 remain_line = fields[1]
252 parsed_object = pdfobj
253 else:
254 pdfobj.append_string(line)
255 line = ""
256 else:
257 m = self.re_objstart.search(line)
258 if m:
259 number, revision = m.group(1), m.group(2)
260 pdfobj = PDFObject(number, revision,
261 stream_manager=self.stream_manager)
262 line = m.group(3)
263 else:
264 # drop the line
265 line = ""
266
267 return (parsed_object, remain_line)
268
269 def _expand_pages(self, page_kids):
270 # Iterations to make a list of unitary pages (/Page) from a list
271 # containing group of pages (/Pages). The iterations stop when all
272 # The objects in the list are replaced by unit pages and not
273 # intermediate page groups
274 page_list = page_kids
275 has_kid = len(page_list)
276 while has_kid:
277 newlist = []
278 has_kid = 0
279 for kid in page_list:
280 #print kid
281 kid.link_to(self.resolver)
282 if kid.get_type() == "/Pages":
283 kids = kid.descriptor.get("/Kids")
284 self.debug("Expand page list: %s -> %s" % (kid, kids))
285 has_kid += len(kids)
286 elif kid.get_type() == "/Page":
287 kids = [kid]
288 else:
289 self.error("%s: %s" % (kid, kid.descriptor.params))
290 self.error("%s: What's wrong? '%s'" % (kid, kid.get_type()))
291 kids = []
292 newlist = newlist + kids
293 page_list = newlist
294 return page_list
295
296 def load_pages(self):
297 root = self.trailer.get("/Root")
298 catalog = self.get_object(root)
299 pages = catalog.descriptor.get("/Pages")
300 page_count = int(pages.descriptor.get("/Count"))
301
302 self.info("Found %d pages" % page_count)
303 pages.link_to(self.resolver)
304 page_kids = pages.descriptor.get("/Kids")
305 self.page_objects = self._expand_pages(page_kids)
306 if len(self.page_objects) != page_count:
307 self.error("Unconsistent pages found: %d vs %d" % \
308 (len(self.page_objects), page_count))
309
310
311 class PDFObjectResolver:
312 def __init__(self, pdffile):
313 self.pdffile = pdffile
314
315 def get(self, ident, default=None):
316 pdfobject = self.pdffile.resolve_object(ident)
317 if not(pdfobject): pdfobject = default
318 return pdfobject
319
320
321 class PDFObjectGroup(PDFBaseObject):
322 """
323 Group of the PDF Objects contained in a file. This wrapper is a dictionnary
324 of the objects, and consolidates the links between the objects.
325 """
326 _log = logging.getLogger("pdfscan.pdffile")
327
328 def __init__(self):
329 self.pdfobjects = {}
330 self.objtypes = {}
331 self.unresolved = []
332
333 def count(self):
334 return len(self.pdfobjects.values())
335
336 def types(self):
337 return self.objtypes.keys()
338
339 def add_object(self, pdfobject):
340 self.pdfobjects[pdfobject.ident()] = pdfobject
341 objtype = pdfobject.get_type()
342 if not(objtype):
343 objtype = "misc"
344 lst = self.objtypes.get(objtype, [])
345 lst.append(pdfobject)
346 self.objtypes[objtype] = lst
347 self.unresolved.append(pdfobject)
348
349 def get_objects_by_type(self, objtype):
350 return self.objtypes.get(objtype, [])
351
352 def get_object(self, ident):
353 return self.pdfobjects.get(ident, None)
354
355 def link_objects(self):
356 self.debug("%d objects to resolve" % (len(self.unresolved)))
357 unresolved = []
358 for pdfobj in self.unresolved:
359 if pdfobj.link_to(self.pdfobjects):
360 unresolved.append(pdfobj)
361 self.unresolved = unresolved
362
363 def stream_decode(self):
364 for pdfobj in self.pdfobjects.values():
365 pdfobj.stream_decode()
366
367
368 class PDFPage:
369 def __init__(self, pdf, page, pagenum=0):
370 self.pagenum = pagenum
371 self.pdf = pdf
372 contents = page.descriptor.get("/Contents")
373 resources = page.descriptor.get("/Resources")
374
375 if (isinstance(resources, PDFDescriptor)):
376 rsc_descriptor = resources
377 else:
378 rsc_descriptor = resources.descriptor
379
380 rsc_descriptor.link_to(pdf.resolver)
381 font = rsc_descriptor.get("/Font")
382 if font:
383 font.link_to(pdf.resolver)
384 if (isinstance(font, PDFDescriptor)):
385 fontdict = font.infos()
386 else:
387 fontdict = font.descriptor.infos()
388 else:
389 fontdict = {}
390
391 if not(isinstance(contents, list)):
392 contents = [contents]
393
394 self.page = page
395 self.contents = contents
396 self.fontdict = fontdict
397 self.fontmgr = FontManager(fontdict, pdf.fontmgr)
398 self.streams = []
399
400 self.link_to(pdf.resolver)
401 self.load_streams()
402
403 def link_to(self, resolver):
404 for content in self.contents:
405 content.link_to(resolver)
406
407 def load_streams(self):
408 for content in self.contents:
409 stream = PDFContentStream(content, self.fontmgr)
410 self.streams.append(stream)
411
412 def find_fonts(self):
413 return self.fontmgr.get_used()
414
415
416 class PDFXrefSection(PDFBaseObject):
417 """
418 Section starting by 'xref' and followed by the 'trailer'. The xref data
419 contain information about how to access to objects in the file and is
420 therefore a crucial part of the object resolution.
421 """
422 _log = logging.getLogger("pdfscan.xref")
423
424 _re_desc = re.compile("(<<(?:(?<!<)<(?!<)|[^<>]|(?<!>)>(?!>))*>>)",
425 re.MULTILINE)
426
427 def __init__(self, fd):
428 self.trailer = None
429 self.table = {}
430 self.objstm = {}
431 self._file = fd
432 self.older = None
433 self.newer = None
434
435 def set_older(self, older):
436 self.older = older
437 older.newer = self
438
439 def _xref_fill_entry(self, fields, obj_id):
440 offset, revision, what = fields
441 if what == "n":
442 ident = "%d %d" % (obj_id, int(revision))
443 self.table[ident] = int(offset)
444
445 def read_table(self, linestart=""):
446 line = linestart.strip() or self._file.readline()
447 subsection = line.split()
448
449 while subsection[0] != "trailer":
450 start_ref = int(subsection[0])
451 object_count = int(subsection[1])
452 if len(subsection) == 5:
453 self._xref_fill_entry(subsection[2:], start_ref)
454 start_ref += 1
455 object_count -= 1
456
457 for i in range(object_count):
458 line = self._file.readline()
459 self._xref_fill_entry(line.split(), start_ref+i)
460
461 line = self._file.readline()
462 subsection = line.split()
463
464 #print len(self.table.values())
465
466 if subsection[0] == "trailer":
467 data = " ".join(subsection)
468
469 # Ensure we have a complete dictionnary
470 while not(">>" in data):
471 data += self._file.readline()
472
473 m = self._re_desc.search(data)
474 if not(m):
475 self.error("Problem in PDF file: cannot find valid trailer")
476 return
477 self.trailer = PDFDescriptor(string=m.group(1))
478 self.trailer.compute()
479
480
481 class PDFStreamHandler:
482 """
483 Core abstract class in charge to handle the stream of <pdfobject>
484 """
485 def __init__(self, pdfobject):
486 self.stream_object = pdfobject
487
488 def ident(self):
489 return self.stream_object.ident()
490 def debug(self, text):
491 self.stream_object.debug(text)
492 def warning(self, text):
493 self.stream_object.warning(text)
494 def error(self, text):
495 self.stream_object.error(text)
496 def info(self, text):
497 self.stream_object.info(text)
498
499 class PDFXrefObject(PDFStreamHandler):
500 """
501 A specific object that contains XRef entries in binary format. It is an
502 alternative to the xref section.
503 """
504 def __init__(self, pdfobject):
505 PDFStreamHandler.__init__(self, pdfobject)
506 self.trailer = pdfobject.descriptor
507 self.table = {}
508 self.objstm = {}
509 self.older = None
510 self.newer = None
511
512 if pdfobject.descriptor.get("/Type") != "/XRef":
513 self.error("Not an XRef object. Give up")
514 return
515
516 _format = pdfobject.descriptor.get("/W")
517 _format = _format.replace("[", "").replace("]", "")
518 self._format = [ int(f) for f in _format.split() ]
519
520 # An /XRef object must contains a stream
521 pdfobject.stream_decode()
522 self.data = pdfobject.stream_text()
523 self.read_table()
524
525 def set_older(self, older):
526 self.older = older
527 older.newer = self
528
529 def _xref_fill_entry(self, fields, obj_id):
530 offset, revision, what = fields
531 if what == "n":
532 ident = "%d %d" % (obj_id, int(revision))
533 self.table[ident] = int(offset)
534 self.debug("Record xref entry: '%s' @ %s" % (ident, offset))
535
536 def _xref_fill_objstm(self, fields, obj_id):
537 objstm_id, obj_index = fields
538 ident = "%d %d" % (obj_id, 0)
539 self.objstm[ident] = (objstm_id, obj_index)
540 self.debug("Record xref entry in objstm: '%s' @ %s" % \
541 (ident, fields))
542
543 def _int_of(self, string):
544 # Convert to int from bytes string that can be of any size
545 m = len(string)
546 d = 0
547 for i, c in enumerate(string):
548 d += (1 << (8*(m - i-1))) * struct.unpack("B", c)[0]
549 return d
550
551 def read_table(self, linestart=""):
552 data = self.data
553 fields = 3 * [0]
554 entry_size = sum(self._format)
555 # TODO: use /Index
556 obj_id = 0
557
558 while data:
559 first = 0
560 last = 0
561 for i in range(3):
562 last += self._format[i]
563 fields[i] = self._int_of(data[first:last])
564 first = last
565
566 data = data[entry_size:]
567
568 if fields[0] == 1:
569 self._xref_fill_entry(fields[1:3] + ["n"], obj_id)
570 elif fields[0] == 2:
571 self._xref_fill_objstm(fields[1:3], obj_id)
572
573 obj_id += 1
574
575
576 class PDFObjectStream(PDFStreamHandler):
577 """
578 A PDF Object Stream contains in its stream some compressed PDF objects.
579 This class works on a PDF object stream to build the containded PDF objects.
580 """
581 def __init__(self, pdfobject):
582 PDFStreamHandler.__init__(self, pdfobject)
583 self._pdfobjects = []
584
585 def pdfobjects(self):
586 if not(self._pdfobjects):
587 self.compute()
588 return self._pdfobjects
589
590 def _getinfo(self, what):
591 return self.stream_object.descriptor.get(what)
592
593 def get_object(self, idx):
594 if not(self._pdfobjects):
595 self.compute()
596 if idx < 0 or idx >= len(self._pdfobjects):
597 return None
598 return self._pdfobjects[idx]
599
600 def parse_object_list(self, data):
601 values = data.split()
602 objlist = []
603
604 for i in range(0, len(values), 2):
605 # The pair is ('object number', byte_offset)
606 objlist.append((values[i], int(values[i+1])))
607 self.objlist = objlist
608 return objlist
609
610 def compute(self):
611 _type = self._getinfo("/Type")
612 if _type != "/ObjStm":
613 self.error("Cannot read object stream: Invalid type '%s'" % _type)
614 return
615
616 nb_objects = int(self._getinfo("/N"))
617 objlist_b = int(self._getinfo("/First"))
618 stream = self.stream_object.stream_cache
619
620 objlist = self.parse_object_list(stream.read(objlist_b))
621
622 if len(objlist) != nb_objects:
623 self.warning("Error in parsing the Stream Object: found %d"\
624 "objects instead of %d" % (len(objlist), nb_object))
625
626 # List Terminator
627 objlist.append(("",-1))
628
629 bytes_read = 0
630 for i in range(len(objlist)-1):
631 # In ObjectStream, a PDF object revision is always '0'
632 number, revision = objlist[i][0], "0"
633
634 # The size of the object data is given by the position of the next
635 objsize = objlist[i+1][1] - bytes_read
636 if objsize >= 0:
637 data = stream.read(objsize)
638 else:
639 data = stream.read()
640 bytes_read += len(data)
641 self.debug("Object[%d] in stream: '%s' has %d bytes" % \
642 (i, number, objsize))
643
644 # Build the PDF Object from stream data
645 pdfobj = PDFObject(number, revision)
646 pdfobj.append_string(data)
647 pdfobj.compute()
648 self._pdfobjects.append(pdfobj)
649
650 stream.close()
651
652
653 class PDFObject:
654 """
655 A PDF Object contains the data between the 'obj ... 'endobj' tags.
656 It has a unique identifier given by the (number,revision) pair.
657 The data contained by a PDF object can be dictionnaries (descriptors),
658 stream contents and other stuff.
659 """
660 # Extract a dictionnary '<<...>>' leaf (does not contain another dict)
661 _re_desc = re.compile("(<<(?:(?<!<)<(?!<)|[^<>]|(?<!>)>(?!>))*>>)",
662 re.MULTILINE)
663
664 def __init__(self, number, revision, stream_manager=None):
665 self.string = ""
666 self.number = number
667 self.revision = revision
668 self.descriptors = []
669 self.descriptor = None
670 self.data = ""
671 self.stream = None
672 self.outfile = ""
673 self.stream_manager = stream_manager or StreamManager()
674 self._log = logging.getLogger("pdfscan.pdfobject")
675 self.debug("New Object")
676 self.re_desc = self._re_desc
677
678 def debug(self, text):
679 self._log.debug(self.logstr(text))
680 def warning(self, text):
681 self._log.warning(self.logstr(text))
682 def error(self, text):
683 self._log.error(self.logstr(text))
684 def info(self, text):
685 self._log.info(self.logstr(text))
686
687 def ident(self):
688 return "%s %s" % (self.number, self.revision)
689
690 def __repr__(self):
691 return "(%s R)" % self.ident()
692
693 def __int__(self):
694 return int(self.data)
695
696 def logstr(self, text):
697 return "Object [%s %s]: %s" % (self.number,self.revision,text)
698
699 def append_string(self, string):
700 self.string = self.string + string
701
702 def compute(self):
703 string = self.string
704
705 s = re.split(r"stream\s", string, re.MULTILINE)
706 if len(s) > 1:
707 self.debug("Contains stream")
708 self.stream = s[1].strip()
709
710 string = s[0]
711
712 # Iterate to build all the nested dictionnaries/descriptors,
713 # from the deepest to the main one
714 self.descriptors = []
715 while True:
716 descs = self.re_desc.findall(string)
717 if not(descs):
718 break
719 for desc_str in descs:
720 desc = PDFDescriptor(string=desc_str)
721 string = string.replace(desc_str,
722 "{descriptor(%d)}" % len(self.descriptors))
723 self.descriptors.append(desc)
724
725 self.debug("Found %d descriptors" % len(self.descriptors))
726
727 for descobj in self.descriptors:
728 descobj.compute(descriptors=self.descriptors)
729
730 if self.descriptors:
731 self.descriptor = self.descriptors[-1]
732 else:
733 self.descriptor = PDFDescriptor()
734
735 self.data = re.sub(r"{descriptor\(\d+\)}", "",
736 string, flags=re.MULTILINE).strip()
737 self.debug("Data: '%s'" % self.data)
738
739 def stream_decode(self):
740 if not(self.stream):
741 return
742 self.debug("Try to decode stream...")
743
744 # Consolidate stream buffer from the /Length information
745 stream_size = int(self.descriptor.get("/Length"))
746 self.stream = self.stream[0:stream_size]
747
748 # Put the stream in a cache
749 self.stream_cache = self.stream_manager.cache(number=self.number,
750 revision=self.revision)
751
752 method = self.descriptor.get("/Filter")
753 if method == "/FlateDecode":
754 method = "zlib"
755 elif method == "/DCTDecode":
756 # This is JPEG. Just dump it
757 self.warning("this is a JPEG stream")
758 method = ""
759 elif method != "":
760 self.error("don't know how to decode stream with filter '%s'" \
761 % method)
762 return
763
764 self.stream_cache.write(self.stream, compress_type=method)
765
766 def stream_text(self):
767 if not(self.stream):
768 return ""
769 data = self.stream_cache.read()
770 self.stream_cache.close()
771 return data
772
773 def get_type(self):
774 _type = self.descriptor.get("/Type")
775 if _type:
776 return _type
777 if self.stream:
778 return "stream"
779 if pdfstring_is_list(self.data):
780 return "list"
781 if self.descriptor.is_name_tree_node():
782 return "name tree"
783
784 def link_to(self, pdfobjects):
785 self.debug("Link objects")
786 for desc in self.descriptors:
787 desc.link_to(pdfobjects)
788
789 if pdfstring_is_list(self.data):
790 pass
791
792
793 class PDFDescriptor:
794 """
795 Contains the data between the << ... >> brackets in PDF objects. It is
796 a dictionnary that can contain other descriptors/dictionnaries.
797 """
798 # Unique identifier for these objects
799 _id = 0
800
801 # Detect the dictionnary fields covering these cases:
802 # <<
803 # /Type /Page : the value is another keyword
804 # /Contents 5 0 R : the value is a string up next keyword
805 # /Resources 4 0 R
806 # /MediaBox [0 0 595.276 841.89] : the value is an array
807 # /Parent 12 0 R
808 # >>
809 _re_dict = re.compile(r"/\w+\s*/[^/\s]+|/\w+\s*\[[^\]]*\]|/\w+\s*[^/]+")
810
811 # Extract a dictionnary keyword
812 _re_key = re.compile(r"(/[^ \({/\[<]*)")
813
814 # Extract the substituted descriptors
815 _re_descobj = re.compile(r"{descriptor\((\d+)\)}")
816
817 # Find the PDF object references
818 _re_objref = re.compile(r"(\d+ \d+ R)")
819
820 def __init__(self, string=""):
821 self._ident = self._get_ident()
822 self.string = string
823 self.params = {}
824 self._log = logging.getLogger("pdfscan.descriptor")
825
826 self.re_dict = self._re_dict
827 self.re_key = self._re_key
828 self.re_descobj = self._re_descobj
829 self.re_objref = self._re_objref
830
831 def _get_ident(self):
832 _id = PDFDescriptor._id
833 PDFDescriptor._id += 1
834 return _id
835
836 def ident(self):
837 return self._ident
838
839 def debug(self, text):
840 self._log.debug("Descriptor [%d]: %s" % (self._ident, text))
841 def error(self, text):
842 self._log.error("Descriptor [%d]: %s" % (self._ident, text))
843 def info(self, text):
844 self._log.info("Descriptor [%d]: %s" % (self._ident, text))
845 def warning(self, text):
846 self._log.warning("Descriptor [%d]: %s" % (self._ident, text))
847
848 def __repr__(self):
849 return "desc[%d]" % self._ident
850
851 def normalize_fields(self, string):
852 string = string.replace(">>", "")
853 string = string.replace("<<", "")
854 string = string.replace("\n", " ")
855 fields = self.re_dict.findall(string)
856 fields = [ f.strip() for f in fields if (f and f.strip()) ]
857 return fields
858
859 def compute(self, descriptors=None):
860 lines = self.normalize_fields(self.string)
861 for line in lines:
862 m = self.re_key.match(line)
863 if not(m):
864 continue
865 param = m.group(1)
866 value = line.replace(param, "").strip()
867 m = self.re_descobj.match(value)
868 if m and descriptors:
869 value = descriptors[int(m.group(1))]
870 self.params[param] = value
871
872 self.debug(self.params)
873
874 def get(self, param, default=""):
875 return self.params.get(param, default)
876
877 def values(self):
878 return self.params.values()
879
880 def keys(self):
881 return self.params.keys()
882
883 def infos(self):
884 return self.params
885
886 def is_name_tree_node(self):
887 if self.get("/Limits") or self.get("/Names") or self.get("/Kid"):
888 return True
889 else:
890 return False
891
892 def link_to(self, pdfobjects):
893 unresolved = 0
894 for param, value in self.params.items():
895 # Point to something else than a string? Skip it
896 if not(isinstance(value, str)):
897 continue
898
899 objects = []
900 objrefs = self.re_objref.findall(value)
901 value2 = value
902 #print value, objrefs
903 for objref in objrefs:
904 o = pdfobjects.get(objref.replace(" R", ""), None)
905 # If the object is missing, keep the reference for another trial
906 if not(o):
907 self.warning("Object '%s' not resolved" % objref)
908 unresolved += 1
909 o = objref
910 objects.append(o)
911 value2 = value2.replace(objref, "", 1)
912
913 if not(objects):
914 continue
915
916 if pdfstring_is_list(value):
917 if (value2[1:-1].strip()):
918 #print value2, objects
919 self.warning("Problem: cannot substitute objects: '%s'" \
920 % value)
921 else:
922 self.params[param] = objects
923 self.debug("Substitute %s: %s" % (param, objects))
924 else:
925 if value2.strip() or len(objects) > 1:
926 self.warning("Problem: cannot substitute object" % value)
927 else:
928 self.params[param] = objects[0]
929 self.debug("Substitute %s: %s" % (param, objects[0]))
930
931 return unresolved
932
933
934 class StreamManager(PDFBaseObject):
935 CACHE_REFRESH = 1
936 CACHE_REMANENT = 2
937 CACHE_TMPDIR = 4
938 CACHE_DELONCLOSE = 8
939
940 _log = logging.getLogger("pdfscan.pdffile")
941
942 def __init__(self, cache_method="file", cache_dirname="", flags=0):
943 self.cache_method = cache_method
944 self.cache_format = "pdfstream.%(number)s.%(revision)s"
945 self.cache_dirname = cache_dirname
946 self.cache_files = []
947 self.flags = flags
948 # Don't want to remove something in a user directory
949 if cache_dirname: self.flags = self.flags | self.CACHE_REMANENT
950
951 def cleanup(self):
952 if (self.cache_method != "file"):
953 return
954
955 if (self.flags & self.CACHE_REMANENT):
956 if (self.flags & self.CACHE_TMPDIR):
957 self.warning("'%s' not removed" % (self.cache_dirname))
958 return
959
960 if (self.flags & self.CACHE_TMPDIR):
961 self.debug("Remove cache directory '%s'" % (self.cache_dirname))
962 shutil.rmtree(self.cache_dirname)
963 else:
964 for fname in self.cache_files:
965 print("shutil.remove(", fname)
966
967 def cache(self, **kwargs):
968 if self.cache_method == "file":
969 return self.cache_file(kwargs)
970 else:
971 return self.cache_memory(kwargs)
972
973 def cache_file(self, kwargs):
974 if not(self.cache_dirname):
975 self.cache_dirname = tempfile.mkdtemp()
976 self.flags = self.flags | self.CACHE_TMPDIR | self.CACHE_DELONCLOSE
977
978 if not(os.path.exists(self.cache_dirname)):
979 os.mkdir(self.cache_dirname)
980
981 cache_path = os.path.join(self.cache_dirname,
982 self.cache_format % kwargs)
983 stream_cache = StreamCacheFile(cache_path, flags=self.flags)
984 self.cache_files.append(cache_path)
985 return stream_cache
986
987 def cache_memory(self, kwargs):
988 stream_cache = StreamCacheMemory(flags=self.flags)
989 return stream_cache
990
991
992 class StreamCache:
993 def __init__(self, outfile, flags=0):
994 self.flags = flags
995
996 def decompress(self, data, compress_type):
997 if not(compress_type):
998 return data
999 if compress_type == "zlib":
1000 return zlib.decompress(data)
1001
1002 class StreamCacheFile(StreamCache):
1003 def __init__(self, outfile, flags=0):
1004 self.flags = flags
1005 self.outfile = outfile
1006 self._file = None
1007
1008 def write(self, data, compress_type=""):
1009 if ((self.flags & StreamManager.CACHE_REFRESH)
1010 or not(os.path.exists(self.outfile))):
1011 data = self.decompress(data, compress_type)
1012 f = open(self.outfile, "w")
1013 f.write(data)
1014 f.close()
1015
1016 def read(self, size=-1):
1017 if not(self._file):
1018 self._file = open(self.outfile)
1019 if size >= 0:
1020 data = self._file.read(size)
1021 else:
1022 data = self._file.read()
1023 return data
1024
1025 def close(self):
1026 if (self._file):
1027 self._file.close()
1028 if (not(self.flags & StreamManager.CACHE_REMANENT) and \
1029 (self.flags & StreamManager.CACHE_DELONCLOSE)):
1030 os.remove(self.outfile)
1031
1032 class StreamCacheMemory(StreamCache):
1033 def __init__(self, flags=0):
1034 self.flags = flags
1035 self._buffer = ""
1036 self._read_pos = 0
1037
1038 def write(self, data, compress_type=""):
1039 self._buffer += self.decompress(data, compress_type)
1040
1041 def read(self, size=-1):
1042 remain = len(self._buffer)-self._read_pos
1043 if size >= 0:
1044 size = min(size, remain)
1045 else:
1046 size = remain
1047 _buf = self._buffer[self._read_pos:self._read_pos+size]
1048 self._read_pos += size
1049 return _buf
1050
1051 def close(self):
1052 if (self.flags & StreamManager.CACHE_DELONCLOSE):
1053 del self._buffer
1054 self._buffer = None
1055
1056
1057
1058 def extract_string_objects(data, re_pattern, replace_fmt,
1059 delims=None, object_cls=None, object_id=0,
1060 **kwargs):
1061
1062 if isinstance(re_pattern, str):
1063 strings_found = re.findall(re_pattern, data, re.M|re.DOTALL)
1064 else:
1065 strings_found = re_pattern.findall(data)
1066
1067 #print strings_found
1068 strings_objects = []
1069 for i, to in enumerate(strings_found):
1070 repl = replace_fmt % (i+object_id)
1071 if delims:
1072 to = delims[0] + to + delims[1]
1073 repl = delims[0] + repl + delims[1]
1074 data = data.replace(to, repl, 1)
1075 if object_cls:
1076 strings_objects.append(object_cls(to, **kwargs))
1077 else:
1078 strings_objects.append(to)
1079 return (strings_objects, data)
1080
1081
1082 class PDFContentStream(PDFStreamHandler):
1083 """
1084 Data between the 'stream ... endstream' tags in a PDF object used as
1085 content (and not as image or object storage).
1086 """
1087 def __init__(self, pdfobject, fontmgr=None):
1088 PDFStreamHandler.__init__(self, pdfobject)
1089 self.data = ""
1090 self.qnode_root = None
1091 self.textobjects = None
1092 self.fontmgr = fontmgr or FontManager({})
1093 pdfobject.stream_decode()
1094 self.extract_textobjects(pdfobject.stream_text())
1095 self.make_graph_tree()
1096
1097 def extract_textobjects(self, data):
1098 fields = re.split(r"((?<=\s)BT(?=\s)|(?<=\s)ET(?=\s))", data)
1099
1100 start_text = False
1101 textdata = ""
1102 textobject = None
1103 textobjects = []
1104
1105 for field in fields:
1106 if field == "BT":
1107 start_text = True
1108 textdata = ""
1109 elif field == "ET":
1110 textobject = PDFTextObject(textdata, fontmgr=self.fontmgr)
1111 data = data.replace(textdata,
1112 " textobj(%d) " % len(textobjects), 1)
1113 textobjects.append(textobject)
1114 start_text = False
1115 elif start_text:
1116 textdata += field
1117
1118 self.debug("Found %d textobjects" % len(textobjects))
1119 self.textobjects = textobjects
1120 self.data = data
1121
1122 def make_graph_tree(self):
1123 graph_stacks = re.split(r"(q\s|\sQ)", self.data)
1124
1125 self.qnode_root = GraphState()
1126 qnode = self.qnode_root
1127 for field in graph_stacks:
1128 if "q" in field:
1129 qnode = qnode.push(GraphState())
1130 elif "Q" in field:
1131 qnode = qnode.pop()
1132 elif field.strip():
1133 qnode.set_data(field)
1134 qnode.fill_textobjects(self.textobjects)
1135
1136 def dump(self):
1137 self.qnode_root.dump()
1138
1139
1140
1141 class PDFMatrix(PDFBaseObject):
1142 """
1143 | a b 0 |
1144 Tm = | c d 0 |
1145 | e f 1 |
1146
1147 [x , y , 1] = [x1, y1, 1] x Tm1
1148 [x1, y1, 1] = [x2, y2, 1] x Tm2
1149
1150 => [x , y , 1] = [x2, y2, 1] x Tm2 x Tm1
1151
1152 """
1153 IDENT = [1, 0, 0, 1, 0, 0]
1154
1155 def __init__(self, vector):
1156 self.vector = vector
1157
1158 def tx(self):
1159 return self.vector[4]
1160
1161 def ty(self):
1162 return self.vector[5]
1163
1164 def scale(self):
1165 a, b, c, d, e, f = self.vector
1166 # Horizontal orientation
1167 if (abs(a) == abs(d) and b == 0 and c == 0):
1168 return abs(a)
1169 # vertical orientation
1170 if (abs(b) == abs(c) and a == 0 and d == 0):
1171 return abs(b)
1172 # Always return the first even if something is weird
1173 self.warning("Cannot interpret Tm matrix scale: %s" % self)
1174 return a
1175
1176 def __str__(self):
1177 return str(self.vector)
1178
1179 def __len__(self):
1180 return len(self.vector)
1181
1182 def __mul__(self, vector):
1183 a, b, c, d, e, f = self.vector
1184 if len(vector) == 6:
1185 ar, br, cr, dr, er, fr = vector.vector
1186 a2 = a * ar + b * cr + 0 * er
1187 b2 = a * br + b * dr + 0 * fr
1188 c2 = c * ar + d * cr + 0 * er
1189 d2 = c * br + d * dr + 0 * fr
1190 e2 = e * ar + f * cr + 1 * er
1191 f2 = e * br + f * dr + 1 * fr
1192
1193 m = PDFMatrix([a2,b2,c2,d2,e2,f2])
1194 return m
1195 else:
1196 x, y = vector[0:2]
1197 x2 = a * x + c * y + e
1198 y2 = b * x + d * y + f
1199 return [x2, y2, 1]
1200
1201
1202 class GraphState:
1203 """
1204 Graphic state starts with 'q' and ends with 'Q' in content stream.
1205 It can contain other graphic states and/or text objects.
1206 """
1207 def __init__(self):
1208 self._parent = None
1209 self._children = []
1210 self._level = 0
1211 self._data = ""
1212 self.textobjects = []
1213 self.matrix = PDFMatrix(PDFMatrix.IDENT)
1214
1215 def level(self):
1216 return self._level
1217
1218 def set_parent(self, qnode):
1219 self._parent = qnode
1220 self._level = qnode.level()+1
1221
1222 def push(self, qnode):
1223 self._children.append(qnode)
1224 qnode.set_parent(self)
1225 return qnode
1226
1227 def pop(self):
1228 qnode = self._parent
1229 return qnode
1230
1231 def set_data(self, data, textobjects=None):
1232 self._data = data
1233 if textobjects:
1234 self.fill_textobjects(textobjects)
1235 self.extract_matrix()
1236
1237 def fill_textobjects(self, textobjects):
1238 #print self._data #***
1239 tos = re.findall(r" (textobj\(\d+\))", self._data)
1240 for to in tos:
1241 m = re.match(r"textobj\((\d+)\)", to)
1242 if m:
1243 textobject = textobjects[int(m.group(1))]
1244 textobject.set_graphstate(self)
1245 self.textobjects.append(textobject)
1246
1247 self._data = re.sub(r" textobj\(\d+\)", "",
1248 self._data, flags=re.MULTILINE).strip()
1249
1250 def extract_matrix(self):
1251 m = re.search("("+6*"[^\s]+\s+"+"cm"+")", self._data)
1252 if m:
1253 vector = [ float(v) for v in m.group(1).split()[0:6] ]
1254 self.matrix = PDFMatrix(vector)
1255
1256 def dump(self):
1257 s = self._level * " " + "q '" + self._data + "'"
1258 print(s)
1259 for q in self._children:
1260 q.dump()
1261 s = self._level * " " + "Q"
1262 print(s)
1263
1264
1265 class PDFTextObject:
1266 """
1267 Data between the 'BT' and 'ET' tokens found in content streams.
1268 """
1269 _font_op_pattern = r"/[^\s]+\s+[^\s]+\s+Tf"
1270
1271 # Detect a 'Tf', 'Tm', 'Tj', 'TJ', Td, TD operator sequence in a text object
1272 # To use only when strings are extracted and replaced by their reference
1273 _re_seq = re.compile("(" + _font_op_pattern + "|"+\
1274 6*r"[^\s]+\s+"+"Tm"+"|"+\
1275 r"\(textcontent\{\d+\}\)\s*Tj|"+\
1276 r"\[[^\]]*\]\s*TJ|"+\
1277 r"[^\s]+\s+[^\s]+\s+T[dD])", re.MULTILINE)
1278
1279 # Find a font setup operator, like '/F10 9.47 Tf'
1280 _re_font = re.compile("("+_font_op_pattern+")", re.MULTILINE)
1281
1282 # Find a sequence '(...\(...\)...) Tj'
1283 _re_text_show1 = re.compile(r"(\((?:" + "[^()]" + "|" +\
1284 r"(?<=\\)\(" + "|" +\
1285 r"(?<=\\)\)" + ")*\)\s*Tj)", re.M)
1286
1287 # Find a sequence '[...\[...\]...] TJ'
1288 _re_text_show2 = re.compile(r"\[((?:" + "[^\[\]]" + "|" +\
1289 r"(?<=\\)\[" + "|" +\
1290 r"(?<=\\)\]" + ")*)\]\s*TJ", re.M)
1291
1292 def __init__(self, data, fontmgr=None):
1293 self.data = data
1294 self.matrix = PDFMatrix(PDFMatrix.IDENT)
1295 self.fontmgr = fontmgr or FontManager({})
1296 self.qnode = None
1297 self.strings = []
1298 self.textsegments = []
1299 self.textlines = []
1300 self.extract_strings()
1301 self.extract_matrix()
1302 self.parse_data()
1303
1304 def set_graphstate(self, gs):
1305 self.qnode = gs
1306
1307 def set_fontmanager(self, fontmgr):
1308 self.fontmgr = fontmgr
1309
1310 def matrix_absolute(self):
1311 # The textobject matrix change is the last one, so on the full left
1312 m = self.matrix
1313
1314 # We climb the graph stack from the deepest (newer) to the upper
1315 # (oldest) node so:
1316 # Absolute Matrix = Newest (m) x ... x Oldest (qnode.matrix)
1317 qnode = self.qnode
1318 while qnode:
1319 m = m * qnode.matrix
1320 qnode = qnode.pop()
1321 return m
1322
1323 def extract_matrix(self):
1324 m = re.search("("+6*r"[^\s]+\s+"+"Tm"+")", self.data)
1325 if m:
1326 vector = [ float(v) for v in m.group(1).split()[0:6] ]
1327 self.matrix = PDFMatrix(vector)
1328
1329 def extract_strings(self):
1330 #print self.data
1331 objects, data = extract_string_objects(self.data, self._re_text_show1,
1332 "(textcontent{%d}) Tj")
1333 self.strings = objects
1334 objects, data = extract_string_objects(data, self._re_text_show2,
1335 "textcontent{%d}",
1336 delims=["[","]"],
1337 object_id=len(self.strings))
1338 #print data
1339 self.strings += objects
1340 self.data = data
1341
1342 def _newline(self):
1343 linerow = []
1344 self.textlines.append(linerow)
1345 return linerow
1346
1347 def get_font(self, font, size, scale):
1348 return self.fontmgr.get_font(font, float(size)*scale)
1349
1350 def parse_data(self):
1351 linerow = self._newline()
1352 textline = PDFTextSegment("", PDFMatrix(PDFMatrix.IDENT))
1353 linerow.append(textline)
1354
1355 # Find the operator sequences
1356 operators = self._re_seq.findall(self.data)
1357
1358 font, size = "", 1
1359 last_key = ""
1360
1361 for tx in operators:
1362 fields = tx.split()
1363 key = fields[-1]
1364
1365 # Found a font setup, memorize the fontname and fontsize base
1366 if key == "Tf":
1367 font = fields[0]
1368 size = fields[1]
1369 # Found the matrix setup, memorize it
1370 elif key == "Tm":
1371 vector = [ float(c) for c in fields[0:6]]
1372 self.matrix = PDFMatrix(vector)
1373 # Found a text positionning
1374 elif key in ("Td", "TD"):
1375 tx, ty = [ float(c) for c in fields[0:2]]
1376 matrix = PDFMatrix([1, 0, 0, 1, tx, ty])
1377 textline = PDFTextSegment("", matrix)
1378 self.textsegments.append(textline)
1379 if matrix.ty() != 0:
1380 linerow = self._newline()
1381 linerow.append(textline)
1382 # When text is shown, the current font/size setup applies and is
1383 # then recorded
1384 elif "Tj" in key or "TJ" in key:
1385 m = re.search(r"textcontent\{(\d+)\}", tx)
1386 text_string = self.strings[int(m.group(1))]
1387 scale = self.matrix.scale()
1388 #print font, size, scale #*****
1389 pdffont = self.get_font(font, size, scale)
1390 text_shown = PDFTextShow(text_string, pdffont)
1391 textline.add_text_show(text_shown)
1392 last_key = key
1393
1394 class PDFTextSegment:
1395 """
1396 A text segment is a portion of text related to a text position operator 'Td'
1397 or 'TD'. It contains all the texts shown related to this position, signaled
1398 with the 'Tj' and 'TJ' tokens
1399 """
1400 def __init__(self, data, matrix):
1401 self.matrix = matrix
1402 self.data = data
1403 self.strings = None
1404 self.text_shown = []
1405
1406 def __str__(self):
1407 s = ""
1408 for o in self.text_shown:
1409 s += str(o)
1410 return s
1411
1412 def text(self):
1413 s = " ".join([o.text() for o in self.text_shown])
1414 return s
1415
1416 def set_strings(self, strings):
1417 self.strings = strings
1418
1419 def add_text_show(self, text_shown):
1420 self.text_shown.append(text_shown)
1421
1422
1423 class PDFTextShow:
1424 """
1425 Data between the '( )' of the 'Tj' operator or '[ ]' of the 'TJ' operator
1426 that is intended to be shown.
1427 """
1428 _re_textascii = re.compile(r"\(((?:[^)]|(?<=\\)\))*)\)", re.M)
1429 _re_textunicode = re.compile(r"<([^>]+)>", re.M)
1430 _codec_handler_installed = {}
1431
1432 def __init__(self, data, font):
1433 self.data = data
1434 self.font = font
1435 self.encode = codecs.getencoder("latin1")
1436 if not(self._codec_handler_installed):
1437 codecs.register_error("substitute", PDFTextShow._encode_subs)
1438 self._codec_handler_installed["substitute"] = PDFTextShow._encode_subs
1439
1440 def __str__(self):
1441 return self.data.replace("\n", " ")
1442
1443 def text(self):
1444 textdata = self._re_textascii.findall(self.data)
1445 textdata = "".join(textdata).replace(r"\(", "(").replace(r"\)", ")")
1446 if textdata:
1447 return textdata
1448 if (self.font.tounicode):
1449 textdata = self._re_textunicode.findall(self.data)
1450 s = u" ".join(self.font.tounicode.decode(textdata))
1451 return self.encode(s, "substitute")[0]
1452 else:
1453 return ""
1454
1455 def get_font(self):
1456 return self.font
1457
1458 @classmethod
1459 def _encode_subs(cls, exc):
1460 if not isinstance(exc, UnicodeEncodeError):
1461 return u""
1462 l = []
1463 for c in exc.object[exc.start:exc.end]:
1464 l.append(u"&#x%x;" % ord(c))
1465 return (u"".join(l), exc.end)
1466
1467
1468 class PDFFont:
1469 def __init__(self, fontobject, fontsize, tounicode=None):
1470 self.fontobject = fontobject
1471 self.fontsize = fontsize
1472 self.tounicode = tounicode
1473
1474 def key(self):
1475 key = "%s/%6.2f" % (self.name(), self.size())
1476 return key
1477
1478 def __cmp__(self, other):
1479 a = (cmp(self.name(), other.name()) or
1480 cmp(self.size(), other.size()))
1481 return a
1482
1483 def name(self):
1484 return self.fontobject.descriptor.get("/BaseFont")
1485
1486 def size(self):
1487 return self.fontsize
1488
1489 class FontManager:
1490 def __init__(self, fontdict, global_fontmgr=None):
1491 self.fontdict = fontdict
1492 self.fontused = {}
1493 self.tounicode = {}
1494 self.global_fontmgr = global_fontmgr
1495 self.resolver = PDFResolver.get_resolver()
1496
1497 def get_pdffont(self, fontobj, fontsize):
1498 key = fontobj.descriptor.get("/BaseFont")+"/"+"%6.2f" % fontsize
1499 if key in self.fontused:
1500 return self.fontused.get(key)
1501 elif self.global_fontmgr:
1502 pdffont = self.global_fontmgr.get_pdffont(fontobj, fontsize)
1503 self.fontused[key] = pdffont
1504 else:
1505 pdffont = self._make_pdffont(fontobj, fontsize)
1506 self.fontused[key] = pdffont
1507 return pdffont
1508
1509 def _make_pdffont(self, fontobj, fontsize):
1510 fontobj.link_to(self.resolver)
1511 pdfobject = fontobj.descriptor.get("/ToUnicode")
1512 if pdfobject:
1513 pdfobject.link_to(self.resolver)
1514 tuc = self._get_tounicode(pdfobject)
1515 else:
1516 tuc = None
1517 pdffont = PDFFont(fontobj, fontsize, tuc)
1518 return pdffont
1519
1520 def _get_tounicode(self, pdfobject):
1521 key = pdfobject.ident()
1522 if key in self.tounicode:
1523 tuc = self.tounicode.get(key)
1524 else:
1525 tuc = ToUnicode(pdfobject)
1526 self.tounicode[key] = tuc
1527 return tuc
1528
1529 def get_font(self, fontref, size):
1530 fontobj = self.fontdict.get(fontref)
1531 if not(fontobj):
1532 return None
1533 return self.get_pdffont(fontobj, size)
1534
1535 def get_used(self):
1536 return self.fontused.values()
1537
1538
1539 class ToUnicode(PDFStreamHandler):
1540 """
1541 Handle the /ToUnicode CMap object found in a font, in order to be able to
1542 translate the text content to readable text
1543 """
1544 _re_token = re.compile("(" + \
1545 r"(?:\d+\s+(?:begincodespacerange|beginbfchar|beginbfrange))" + "|"\
1546 "(?:endcodespacerange|endbfchar|endbfrange)" + \
1547 ")", re.M)
1548
1549 def __init__(self, pdfobject):
1550 PDFStreamHandler.__init__(self, pdfobject)
1551 self.charmaps = []
1552 pdfobject.stream_decode()
1553 self.data = pdfobject.stream_text()
1554 self.parse_cmap(self.data)
1555 self.debug("Create a ToUnicode object for '%s'" % pdfobject.ident())
1556
1557 def parse_cmap(self, data):
1558 flds = self._re_token.split(data)
1559
1560 bfchar = None
1561 bfrange = None
1562 for fld in flds:
1563 if "begincodespacerange" in fld:
1564 # TODO
1565 pass
1566 elif "beginbfchar" in fld:
1567 n = int(fld.split()[0])
1568 bfchar = BfRange(n)
1569 elif "beginbfrange" in fld:
1570 n = int(fld.split()[0])
1571 bfrange = BfRange(n)
1572 elif "endcodespacerange" in fld:
1573 pass
1574 elif "endbfchar" in fld:
1575 self.add_bfrange(bfchar)
1576 bfchar = None
1577 elif "endbfrange" in fld:
1578 self.add_bfrange(bfrange)
1579 bfrange = None
1580 elif bfchar:
1581 fld = re.sub(r"<\s+", "<", fld)
1582 fld = re.sub(r"\s+>", ">", fld)
1583 data = fld.split()
1584 for i in range(0, len(data), 2):
1585 bfchar.add_mapstr(data[i], data[i], data[i+1])
1586 elif bfrange:
1587 fld = re.sub(r"<\s+", "<", fld)
1588 fld = re.sub(r"\s+>", ">", fld)
1589 data = fld.split()
1590 for i in range(0, len(data), 3):
1591 bfrange.add_mapstr(data[i], data[i+1], data[i+2])
1592
1593 def add_bfrange(self, bfrange):
1594 self.charmaps.extend(bfrange.charmaps)
1595 self.charmaps.sort()
1596
1597 def get_uccode(self, bfchar):
1598 mustbe_in_next = False
1599 for m in self.charmaps:
1600 if bfchar >= m.bffirst:
1601 if bfchar <= m.bflast:
1602 return m.uccode + (bfchar - m.bffirst)
1603 else:
1604 mustbe_in_next = True
1605 elif mustbe_in_next:
1606 return 0
1607 return 0
1608
1609 def decode_string(self, data):
1610 ul = []
1611 for i in range(0, len(data), 4):
1612 s = data[i:i+4]
1613 #print s
1614 ul.append(unichr(self.get_uccode(int(s,16))))
1615 return u"".join(ul)
1616
1617 def decode(self, data):
1618 if isinstance(data, list):
1619 return [self.decode_string(s) for s in data]
1620 else:
1621 return self.decode_string(data)
1622
1623
1624 class CharMap:
1625 def __init__(self, bffirst, bflast, uccode):
1626 self.bffirst = bffirst
1627 self.bflast = bflast
1628 self.uccode = uccode
1629
1630 def __cmp__(self, other):
1631 return cmp(self.bffirst, other.bffirst)
1632
1633 class BfRange:
1634 def __init__(self, entry_count):
1635 self.entry_count = entry_count
1636 self.charmaps = []
1637
1638 def add_mapstr(self, bffirst_str, bflast_str, ucfirst_str):
1639 # Take strings like <045D>
1640 bffirst = int(bffirst_str[1:-1], 16)
1641 bflast = int(bflast_str[1:-1], 16)
1642 ucfirst = int(ucfirst_str[1:-1], 16)
1643 self.charmaps.append(CharMap(bffirst, bflast, ucfirst))
1644
1645
1646 #
1647 # Starting from here is the command stuff
1648 #
1649 #
1650 import textwrap
1651
1652 class BasicCmd:
1653 def __init__(self):
1654 pass
1655 def setup_parser(self, parser):
1656 return True
1657 def help(self, cmd):
1658 if self.__doc__:
1659 return self.__doc__
1660 else:
1661 return None
1662
1663 class PageLayoutCmd(BasicCmd):
1664 """
1665 Show the position and fonts used for each text line contained by a page
1666 """
1667 def __init__(self, scanner):
1668 self.scanner = scanner
1669 layout_fmt = "%5s %5s | %5s %5s | %8s | "
1670 self.padding = layout_fmt % (" "," "," "," "," ")
1671 self.headline = layout_fmt % (5*"_",5*"_",5*"_",5*"_",8*"_")
1672 self.header = layout_fmt % ("dX","dY","X","Y","FONTS")
1673 self.width = 90
1674 self.show_matrix = False
1675 self.raw_text = False
1676 self.pt_factor = 1
1677
1678 def setup_parser(self, parser):
1679 parser.add_argument("-w", "--width",
1680 help="Width of the printed layout information")
1681 parser.add_argument("-m", "--show-matrix", action="store_true",
1682 help="Print absolute Transformation Matrix for each textobject")
1683 parser.add_argument("-r", "--raw-text", action="store_true",
1684 help="Print the raw text contained by textobjects")
1685
1686 def run(self, parser, args):
1687 if args.width:
1688 self.width = int(args.width)
1689 if args.show_matrix:
1690 self.show_matrix = True
1691 if args.raw_text:
1692 self.raw_text = True
1693
1694 for pg in self.scanner.page_groups:
1695 self.print_page_layout(pg)
1696
1697 def print_page_layout(self, pdf_pages):
1698 for page in pdf_pages:
1699 fonts_used = page.find_fonts()
1700 fonts_used.sort()
1701 print("\nPage %d fonts used:" % page.pagenum)
1702 for i, font in enumerate(fonts_used):
1703 print("[%d] %-40s %6.2f pt" % (i, font.name(),
1704 self.pt_factor*font.size()))
1705
1706 print("\nPage %d layout:" % page.pagenum)
1707 content_stream = page.streams[0]
1708 xp, yp = 0., 0.
1709 print(self.header)
1710 print(self.headline)
1711 for textobject in content_stream.textobjects:
1712 xp, yp = self._print_textobject_layout(textobject, xp, yp,
1713 fonts_used)
1714
1715 def _print_textobject_layout(self, textobject, xp, yp, fonts_used):
1716 wraplen = self.width - len(self.padding)
1717
1718 m2 = textobject.matrix_absolute()
1719
1720 for line in textobject.textlines:
1721 # Track the fonts used per line
1722 font_line = []
1723 for seg in line:
1724 for text_shown in seg.text_shown:
1725 font = text_shown.get_font()
1726 if not(font):
1727 continue
1728 idx = fonts_used.index(font)
1729 if not(idx in font_line):
1730 font_line.append(idx)
1731
1732 m2 = line[0].matrix * m2
1733 if self.show_matrix: print("%s" % m2)
1734
1735 x, y = m2.tx(), m2.ty()
1736 x, y = float(x/72), float(y/72)
1737 dx, dy = x - xp, y - yp
1738 info = "%5.2f %5.2f | %5.2f %5.2f | %8s | " % \
1739 (dx, dy, x, y, font_line)
1740 if self.raw_text:
1741 text = "".join([str(s) for s in line])
1742 else:
1743 text = "".join([s.text() for s in line])
1744 textw = textwrap.wrap(text, wraplen)
1745
1746 if textw:
1747 print("%s%s" % (info, textw[0]))
1748 for txt in textw[1:]:
1749 print("%s%s" % (self.padding, txt))
1750
1751 xp, yp = x, y
1752 for l in line[1:]:
1753 m2 = l.matrix * m2
1754
1755 return (xp, yp)
1756
1757 class PageObjectCmd(BasicCmd):
1758 """
1759 List the PDF objects used per page
1760 """
1761 def __init__(self, scanner):
1762 self.scanner = scanner
1763
1764 def run(self, parser, args):
1765 page_first = 1
1766 for i, page in enumerate(self.scanner.pdf.page_objects):
1767 page_num = i+page_first
1768 contents = page.descriptor.get("/Contents")
1769 resources = page.descriptor.get("/Resources")
1770 print("Page %d %s: contents: %s, resources: %s" % \
1771 (page_num, page, contents, resources))
1772 print()
1773
1774 class PdfObjectCmd(BasicCmd):
1775 """
1776 Scan data on the PDF objects of the PDF File
1777 """
1778 def __init__(self, scanner):
1779 self.scanner = scanner
1780
1781 def setup_parser(self, parser):
1782 group = parser.add_mutually_exclusive_group()
1783 group.add_argument("-list", "--list-loaded", action="store_true",
1784 help="List the object loaded by the scanner")
1785 group.add_argument("-dict", "--dictionnary",
1786 metavar="'<number> <generation>'",
1787 help="Show the dictionnary of the object specified by its "\
1788 "reference '<number> <generation>'")
1789 group.add_argument("-dump", "--dump-stream", nargs=2,
1790 metavar=("'<number> <generation>'","OUTFILE"),
1791 help="Write the stream content of the object specified by its "\
1792 "reference '<number> <generation>'")
1793
1794 def run(self, parser, args):
1795 if args.list_loaded:
1796 self.list_pdfobjects()
1797 elif args.dictionnary:
1798 ident = self._sanitize_objref(args.dictionnary)
1799 if not(ident): return
1800 self.show_dictionnary(ident)
1801 elif args.dump_stream:
1802 ident = self._sanitize_objref(args.dump_stream[0])
1803 if not(ident): return
1804 self.dump_stream(ident, args.dump_stream[1])
1805
1806 def _sanitize_objref(self, ident):
1807 flds = ident.split()
1808 if len(flds) != 2:
1809 print("Invalid object reference: must be in the form "\
1810 "'number generation'")
1811 return ""
1812 else:
1813 return "%s %s" % (flds[0], flds[1])
1814
1815 def show_dictionnary(self, ident):
1816 pdfobject = self.scanner.pdf.get_object(ident)
1817 if not(pdfobject):
1818 print("PDF Object '%s' not found" % ident)
1819 return
1820 if pdfobject.stream:
1821 print("PDF Object '%s' has a stream. Its dictionnary:" % ident)
1822 else:
1823 print("PDF Object '%s' dictionnary:" % ident)
1824 self._print_dictionnary(pdfobject.descriptor)
1825
1826 def _print_dictionnary(self, descriptor, level=1):
1827 indent = " "*level
1828 print("%s<<" % indent)
1829 for p, v in descriptor.infos().items():
1830 if isinstance(v, PDFDescriptor):
1831 print("%s%s:" % (indent, p))
1832 self._print_dictionnary(v, level=level+1)
1833 else:
1834 print("%s%s: %s" % (indent, p, v))
1835 print("%s>>" % indent)
1836
1837 def list_pdfobjects(self):
1838 pdfobjects = self.scanner.pdf.pdfobjects
1839 print("Found %s PDFObjects" % pdfobjects.count())
1840 print("Found the following PDFObject types:")
1841 types = pdfobjects.types()
1842 types.sort()
1843 total = 0
1844 for typ in types:
1845 n_type = len(pdfobjects.get_objects_by_type(typ))
1846 print(" %20s: %5d objects" % (typ, n_type))
1847 total = total + n_type
1848 print(" %20s: %5d objects" % ("TOTAL", total))
1849
1850 def dump_stream(self, ident, outfile):
1851 pdfobject = self.scanner.pdf.get_object(ident)
1852 if not(pdfobject):
1853 print("PDF Object '%s' not found" % ident)
1854 return
1855 if not(pdfobject.stream):
1856 print("PDF Object '%s' has no stream. Give up." % ident)
1857 return
1858 pdfobject.stream_decode()
1859 f = open(outfile, "wb")
1860 f.write(pdfobject.stream_text())
1861 f.close()
1862 print("PDF Object '%s' stream written to file %s" % (ident, outfile))
1863
1864
1865
1866 class PageFontCmd(BasicCmd):
1867 def __init__(self, scanner):
1868 self.scanner = scanner
1869 self.header_fmt = "%4s %-40s %s"
1870 self.pt_factor = 1
1871 self.font_unit = "pt"
1872
1873 def help(self, cmd):
1874 if cmd == "font_summary":
1875 _help = "List the fonts used and their size in the specified pages"
1876 else:
1877 _help = "List the fonts used and their size for each page"
1878 return _help
1879
1880 def setup_parser(self, parser):
1881 parser.add_argument("-pt", "--point-type",
1882 help="Point type to use: 'dtp' (default), 'tex'")
1883
1884 def run(self, parser, args):
1885 if args.point_type == "tex":
1886 self.pt_factor = 72.27/72
1887 self.font_unit = "pt tex"
1888
1889 if args.name == "font_summary":
1890 self.print_font_summary()
1891 else:
1892 self.print_font_page()
1893
1894 def print_font_page(self):
1895 for pg in self.scanner.page_groups:
1896 self.print_fonts_in_pages(pg)
1897
1898 def print_fonts_in_pages(self, pdf_pages, show=True):
1899 if show:
1900 print(self.header_fmt % ("PAGE", "FONT", "SIZE"))
1901 print(self.header_fmt % (4*"-", 40*"-", 10*"-"))
1902
1903 for page in pdf_pages:
1904 fonts_used = page.find_fonts()
1905 fonts_used.sort()
1906 for font in fonts_used:
1907 if show:
1908 print("%4d %-40s %6.2f %s" % (page.pagenum, font.name(),
1909 self.pt_factor * font.size(), self.font_unit))
1910 if show: print(self.header_fmt % (4*"-", 40*"-", 10*"-"))
1911
1912 def print_font_summary(self):
1913 pages = []
1914 for pg in self.scanner.page_groups:
1915 if not(pg):
1916 continue
1917 s = "%d" % (pg[0].pagenum)
1918 if len(pg) > 1:
1919 s += "-%d" % (pg[-1].pagenum)
1920 pages.append(s)
1921
1922 print("\nFonts used in pages %s:" % (",".join(pages)))
1923 fonts_used = self.scanner.pdf.fontmgr.get_used()
1924 fonts_used.sort()
1925 for font in fonts_used:
1926 print("%-40s %6.2f %s" % \
1927 (font.name(), self.pt_factor*font.size(), self.font_unit))
1928
1929
1930 class PDFScannerCommand:
1931 def __init__(self):
1932 self._commands = [
1933 ("page_object", PageObjectCmd),
1934 ("page_font", PageFontCmd),
1935 ("page_layout", PageLayoutCmd),
1936 ("font_summary", PageFontCmd),
1937 ("pdfobject", PdfObjectCmd)
1938 ]
1939 self.commands_to_run = []
1940 self.pdf = None
1941 self.page_ranges = []
1942 self.page_groups = []
1943 self.fonts_used = {}
1944
1945 def commands(self):
1946 return [c[0] for c in self._commands]
1947
1948 def setup_options(self, parser):
1949 parser.add_argument("-p", "--pages", action="append",
1950 help="Page range in the form '<first>[-[<last>]]'")
1951 parser.add_argument("-v", "--verbose", action="append",
1952 help="Verbose mode in the form '[group:]level' with level "\
1953 "in 'debug', 'info', 'warning', 'error' and "\
1954 "group in 'pdffile', 'pdfobject', 'descriptor'")
1955 parser.add_argument("-c", "--cache-stream-dir",
1956 help="Directory where to store the decompressed stream")
1957 parser.add_argument("-m", "--no-cache-stream", action="store_true",
1958 help="No stream cache on disk used: leave streams in memory")
1959 parser.add_argument("-d", "--cache-remanent", action="store_true",
1960 help="Equivalent to -fremanent")
1961 parser.add_argument("-f", "--cache-flags",
1962 help="Comma separated list of stream cache setup options: "\
1963 "'remanent' and/or 'refresh'")
1964
1965 def setup_parser(self, parser):
1966 self.setup_options(parser)
1967
1968 if not(self._commands):
1969 return
1970 partial = True
1971 subparsers = parser.add_subparsers() #title=title)
1972 clsused = []
1973 cmdobjs = []
1974 for cmd, cls in self._commands:
1975 # Don't duplicate objects used for several commands
1976 if cls in clsused:
1977 cmdobj = cmdobjs[clsused.index(cls)]
1978 else:
1979 cmdobj = cls(self)
1980 cmdobjs.append(cmdobj)
1981 clsused.append(cls)
1982 kwargs = {}
1983 if cmdobj.help(cmd):
1984 kwargs["help"] = cmdobj.help(cmd)
1985 p = subparsers.add_parser(cmd, **kwargs)
1986 partial = cmdobj.setup_parser(p) or partial
1987 p.set_defaults(run=cmdobj.run, name=cmd)
1988 return partial
1989
1990 def prepare(self, parser, options, argslist, pdffile):
1991 self.options = options
1992 # Sort the commands in the right order
1993 cmds = [ args.name for args in argslist ]
1994 self.commands_to_run = []
1995 for cmd in self.commands():
1996 if cmd in cmds:
1997 i = cmds.index(cmd)
1998 self.commands_to_run.append(argslist[i])
1999
2000 log_groups = self._option_group_loglevels()
2001 self.logger_setup(log_groups)
2002
2003 self.page_ranges = self._option_page_ranges()
2004
2005 stream_manager = self._option_cache_setup()
2006 self.pdf = PDFFile(stream_manager=stream_manager)
2007
2008 def cleanup(self):
2009 if self.pdf:
2010 self.pdf.cleanup()
2011
2012 def run(self, parser, options, argslist, pdffile):
2013 self.prepare(parser, options, argslist, pdffile)
2014 self.pdf.load(pdffile)
2015 self.pdf.load_pages()
2016 self._build_pages()
2017 for args in self.commands_to_run:
2018 args.run(parser, args)
2019
2020 def _build_pages(self):
2021 page_count = len(self.pdf.page_objects)
2022 for page_range in self.page_ranges:
2023 page_first, page_last = self._page_range(page_range, page_count)
2024 page_objects = self.pdf.page_objects[page_first-1:page_last]
2025
2026 pdf_pages = self._build_pages_from_objects(page_objects, page_first)
2027 self.page_groups.append(pdf_pages)
2028
2029 def _build_pages_from_objects(self, page_objects, page_first):
2030 pdf_pages = []
2031 for i, pg in enumerate(page_objects):
2032 pagenum = i+page_first
2033 page = PDFPage(self.pdf, pg, pagenum)
2034 pdf_pages.append(page)
2035 return pdf_pages
2036
2037 def _page_range(self, page_range, max_range):
2038 if not(page_range): page_range = [1, max_range]
2039 if page_range[0] == 0: page_range[0] = 1
2040 if page_range[1] == 0 or page_range[1] > max_range:
2041 page_range[1] = max_range
2042 return page_range
2043
2044 def _option_page_ranges(self):
2045 page_ranges = []
2046 if not(self.options.pages):
2047 page_ranges.append([0, 0])
2048 return page_ranges
2049
2050 for page_range in self.options.pages:
2051 p1, p2 = (page_range + "-x").split("-")[0:2]
2052 if not(p2):
2053 p2 = 0
2054 elif (p2 == "x"):
2055 p2 = p1
2056 page_ranges.append([int(p1), int(p2)])
2057
2058 return page_ranges
2059
2060 def _option_group_loglevels(self):
2061 verbose = self.options.verbose
2062 log_groups = {"pdffile": "info",
2063 "pdfobject": "info",
2064 "descriptor": "error",
2065 "base": "info"}
2066
2067 log_levels = ("debug", "info", "warning", "error")
2068
2069 if not(verbose):
2070 return log_groups
2071
2072 groups = log_groups.keys()
2073 for verbose_opt in verbose:
2074 group, level = ("all:" + verbose_opt).split(":")[-2:]
2075 if not(level in log_levels):
2076 print("Invalid verbose level: '%s'" % level)
2077 continue
2078 if group == "all":
2079 for group in groups:
2080 log_groups[group] = level
2081 elif group in groups:
2082 log_groups[group] = level
2083 else:
2084 print("Invalid verbose group: '%s'" % group)
2085 continue
2086 return log_groups
2087
2088 def _option_cache_setup(self):
2089 cache_in_memory = self.options.no_cache_stream
2090 cache_dirname = self.options.cache_stream_dir
2091 cache_flags = self.options.cache_flags
2092
2093 if self.options.cache_remanent:
2094 if cache_flags:
2095 cache_flags += ",remanent"
2096 else:
2097 cache_flags = "remanent"
2098
2099 flags = 0
2100 if cache_flags:
2101 cache_flags = cache_flags.split(",")
2102 for cflag in cache_flags:
2103 if cflag == "remanent":
2104 flags = flags | StreamManager.CACHE_REMANENT
2105 elif cflag == "refresh":
2106 flags = flags | StreamManager.CACHE_REFRESH
2107
2108 if cache_in_memory:
2109 mgr = StreamManager(cache_method="memory")
2110 elif cache_dirname:
2111 cache_dirname = os.path.realpath(cache_dirname)
2112 if not(os.path.exists(cache_dirname)):
2113 print("Invalid cache dir: '%s'. Temporary dir used instead" % \
2114 cache_dirname)
2115 return None
2116 mgr = StreamManager(cache_method="file",
2117 cache_dirname=cache_dirname,
2118 flags=flags)
2119 else:
2120 mgr = StreamManager(flags=flags)
2121
2122 return mgr
2123
2124 def logger_setup(self, log_groups):
2125 loglevels = { "error": logging.ERROR,
2126 "warning": logging.WARNING,
2127 "info": logging.INFO,
2128 "debug": logging.DEBUG }
2129
2130 console = logging.StreamHandler()
2131 fmt = logging.Formatter("%(message)s")
2132 console.setFormatter(fmt)
2133
2134 for group, level in log_groups.items():
2135 log = logging.getLogger("pdfscan.%s" % group)
2136 log.setLevel(loglevels.get(level, logging.INFO)-1)
2137 log.addHandler(console)
2138
2139
2140 def main():
2141 from argparse import ArgumentParser
2142 parser = ArgumentParser(description='Scan information from a PDF file')
2143 parser.add_argument("-D", "--dump-stack", action="store_true",
2144 help="Dump error stack (debug purpose)")
2145
2146 scanner = PDFScannerCommand()
2147 scanner.setup_parser(parser)
2148
2149 options, remain_args = parser.parse_known_args()
2150
2151 argslist = []
2152 remain_args = sys.argv[1:]
2153 while len(remain_args) > 1:
2154 args, remain_args = parser.parse_known_args(remain_args)
2155 args.remain_args = remain_args
2156 argslist.append(args)
2157
2158 if not(remain_args) or remain_args[0] in scanner.commands():
2159 print("Missing the PDF File")
2160 parser.parse_args(["-h"])
2161
2162 error = ErrorHandler()
2163 if options.dump_stack: error.dump_stack()
2164
2165 try:
2166 pdffile = remain_args[0]
2167 scanner.run(parser, options, argslist, pdffile)
2168 except Exception as e:
2169 error.failure_track("Error: '%s'" % (e))
2170
2171 scanner.cleanup()
2172 sys.exit(error.rc)
2173
2174 if __name__ == "__main__":
2175 main()