I updated the PDF Booklet project and removed Python 2 dependencies so that it will run under Ubuntu 22.04.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3099 lines
127 KiB

2 years ago
  1. # -*- coding: utf-8 -*-
  2. #
  3. # vim: sw=4:expandtab:foldmethod=marker
  4. #
  5. # Copyright (c) 2006, Mathieu Fenniak
  6. # Copyright (c) 2007, Ashish Kulkarni <kulkarni.ashish@gmail.com>
  7. #
  8. # All rights reserved.
  9. #
  10. # Redistribution and use in source and binary forms, with or without
  11. # modification, are permitted provided that the following conditions are
  12. # met:
  13. #
  14. # * Redistributions of source code must retain the above copyright notice,
  15. # this list of conditions and the following disclaimer.
  16. # * Redistributions in binary form must reproduce the above copyright notice,
  17. # this list of conditions and the following disclaimer in the documentation
  18. # and/or other materials provided with the distribution.
  19. # * The name of the author may not be used to endorse or promote products
  20. # derived from this software without specific prior written permission.
  21. #
  22. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  23. # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  24. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  25. # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  26. # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  27. # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  28. # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  29. # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  30. # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  31. # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  32. # POSSIBILITY OF SUCH DAMAGE.
  33. """
  34. A pure-Python PDF library with an increasing number of capabilities.
  35. See README for links to FAQ, documentation, homepage, etc.
  36. """
  37. __author__ = "Mathieu Fenniak"
  38. __author_email__ = "biziqe@mathieu.fenniak.net"
  39. __maintainer__ = "Phaseit, Inc."
  40. __maintainer_email = "PyPDF2@phaseit.net"
  41. import string
  42. import math
  43. import struct
  44. import sys
  45. import uuid
  46. from sys import version_info
  47. if version_info < ( 3, 0 ):
  48. from cStringIO import StringIO
  49. else:
  50. from io import StringIO
  51. if version_info < ( 3, 0 ):
  52. BytesIO = StringIO
  53. else:
  54. from io import BytesIO
  55. from . import filters
  56. from . import utils
  57. import warnings
  58. import codecs
  59. from .generic import *
  60. from .utils import readNonWhitespace, readUntilWhitespace, ConvertFunctionsToVirtualList
  61. from .utils import isString, b_, u_, ord_, chr_, str_, formatWarning
  62. if version_info < ( 2, 4 ):
  63. from sets import ImmutableSet as frozenset
  64. if version_info < ( 2, 5 ):
  65. from md5 import md5
  66. else:
  67. from hashlib import md5
  68. import uuid
  69. class PdfFileWriter(object):
  70. """
  71. This class supports writing PDF files out, given pages produced by another
  72. class (typically :class:`PdfFileReader<PdfFileReader>`).
  73. """
  74. def __init__(self):
  75. self._header = b_("%PDF-1.3")
  76. self._objects = [] # array of indirect objects
  77. # The root of our page tree node.
  78. pages = DictionaryObject()
  79. pages.update({
  80. NameObject("/Type"): NameObject("/Pages"),
  81. NameObject("/Count"): NumberObject(0),
  82. NameObject("/Kids"): ArrayObject(),
  83. })
  84. self._pages = self._addObject(pages)
  85. # info object
  86. info = DictionaryObject()
  87. info.update({
  88. NameObject("/Producer"): createStringObject(codecs.BOM_UTF16_BE + u_("PyPDF2").encode('utf-16be'))
  89. })
  90. self._info = self._addObject(info)
  91. # root object
  92. root = DictionaryObject()
  93. root.update({
  94. NameObject("/Type"): NameObject("/Catalog"),
  95. NameObject("/Pages"): self._pages,
  96. })
  97. self._root = None
  98. self._root_object = root
  99. def _addObject(self, obj):
  100. self._objects.append(obj)
  101. return IndirectObject(len(self._objects), 0, self)
  102. def getObject(self, ido):
  103. if ido.pdf != self:
  104. raise ValueError("pdf must be self")
  105. return self._objects[ido.idnum - 1]
  106. def _addPage(self, page, action):
  107. assert page["/Type"] == "/Page"
  108. page[NameObject("/Parent")] = self._pages
  109. page = self._addObject(page)
  110. pages = self.getObject(self._pages)
  111. action(pages["/Kids"], page)
  112. pages[NameObject("/Count")] = NumberObject(pages["/Count"] + 1)
  113. def addPage(self, page):
  114. """
  115. Adds a page to this PDF file. The page is usually acquired from a
  116. :class:`PdfFileReader<PdfFileReader>` instance.
  117. :param PageObject page: The page to add to the document. Should be
  118. an instance of :class:`PageObject<PyPDF2.pdf.PageObject>`
  119. """
  120. self._addPage(page, list.append)
  121. def insertPage(self, page, index=0):
  122. """
  123. Insert a page in this PDF file. The page is usually acquired from a
  124. :class:`PdfFileReader<PdfFileReader>` instance.
  125. :param PageObject page: The page to add to the document. This
  126. argument should be an instance of :class:`PageObject<pdf.PageObject>`.
  127. :param int index: Position at which the page will be inserted.
  128. """
  129. self._addPage(page, lambda l, p: l.insert(index, p))
  130. def getPage(self, pageNumber):
  131. """
  132. Retrieves a page by number from this PDF file.
  133. :param int pageNumber: The page number to retrieve
  134. (pages begin at zero)
  135. :return: the page at the index given by *pageNumber*
  136. :rtype: :class:`PageObject<pdf.PageObject>`
  137. """
  138. pages = self.getObject(self._pages)
  139. # XXX: crude hack
  140. return pages["/Kids"][pageNumber].getObject()
  141. def getNumPages(self):
  142. """
  143. :return: the number of pages.
  144. :rtype: int
  145. """
  146. pages = self.getObject(self._pages)
  147. return int(pages[NameObject("/Count")])
  148. def addBlankPage(self, width=None, height=None):
  149. """
  150. Appends a blank page to this PDF file and returns it. If no page size
  151. is specified, use the size of the last page.
  152. :param float width: The width of the new page expressed in default user
  153. space units.
  154. :param float height: The height of the new page expressed in default
  155. user space units.
  156. :return: the newly appended page
  157. :rtype: :class:`PageObject<PyPDF2.pdf.PageObject>`
  158. :raises PageSizeNotDefinedError: if width and height are not defined
  159. and previous page does not exist.
  160. """
  161. page = PageObject.createBlankPage(self, width, height)
  162. self.addPage(page)
  163. return page
  164. def insertBlankPage(self, width=None, height=None, index=0):
  165. """
  166. Inserts a blank page to this PDF file and returns it. If no page size
  167. is specified, use the size of the last page.
  168. :param float width: The width of the new page expressed in default user
  169. space units.
  170. :param float height: The height of the new page expressed in default
  171. user space units.
  172. :param int index: Position to add the page.
  173. :return: the newly appended page
  174. :rtype: :class:`PageObject<PyPDF2.pdf.PageObject>`
  175. :raises PageSizeNotDefinedError: if width and height are not defined
  176. and previous page does not exist.
  177. """
  178. if width is None or height is None and \
  179. (self.getNumPages() - 1) >= index:
  180. oldpage = self.getPage(index)
  181. width = oldpage.mediaBox.getWidth()
  182. height = oldpage.mediaBox.getHeight()
  183. page = PageObject.createBlankPage(self, width, height)
  184. self.insertPage(page, index)
  185. return page
  186. def addJS(self, javascript):
  187. """
  188. Add Javascript which will launch upon opening this PDF.
  189. :param str javascript: Your Javascript.
  190. >>> output.addJS("this.print({bUI:true,bSilent:false,bShrinkToFit:true});")
  191. # Example: This will launch the print window when the PDF is opened.
  192. """
  193. js = DictionaryObject()
  194. js.update({
  195. NameObject("/Type"): NameObject("/Action"),
  196. NameObject("/S"): NameObject("/JavaScript"),
  197. NameObject("/JS"): NameObject("(%s)" % javascript)
  198. })
  199. js_indirect_object = self._addObject(js)
  200. # We need a name for parameterized javascript in the pdf file, but it can be anything.
  201. js_string_name = str(uuid.uuid4())
  202. js_name_tree = DictionaryObject()
  203. js_name_tree.update({
  204. NameObject("/JavaScript"): DictionaryObject({
  205. NameObject("/Names"): ArrayObject([createStringObject(js_string_name), js_indirect_object])
  206. })
  207. })
  208. self._addObject(js_name_tree)
  209. self._root_object.update({
  210. NameObject("/OpenAction"): js_indirect_object,
  211. NameObject("/Names"): js_name_tree
  212. })
  213. def addAttachment(self, fname, fdata):
  214. """
  215. Embed a file inside the PDF.
  216. :param str fname: The filename to display.
  217. :param str fdata: The data in the file.
  218. Reference:
  219. https://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/PDF32000_2008.pdf
  220. Section 7.11.3
  221. """
  222. # We need 3 entries:
  223. # * The file's data
  224. # * The /Filespec entry
  225. # * The file's name, which goes in the Catalog
  226. # The entry for the file
  227. """ Sample:
  228. 8 0 obj
  229. <<
  230. /Length 12
  231. /Type /EmbeddedFile
  232. >>
  233. stream
  234. Hello world!
  235. endstream
  236. endobj
  237. """
  238. file_entry = DecodedStreamObject()
  239. file_entry.setData(fdata)
  240. file_entry.update({
  241. NameObject("/Type"): NameObject("/EmbeddedFile")
  242. })
  243. # The Filespec entry
  244. """ Sample:
  245. 7 0 obj
  246. <<
  247. /Type /Filespec
  248. /F (hello.txt)
  249. /EF << /F 8 0 R >>
  250. >>
  251. """
  252. efEntry = DictionaryObject()
  253. efEntry.update({ NameObject("/F"):file_entry })
  254. filespec = DictionaryObject()
  255. filespec.update({
  256. NameObject("/Type"): NameObject("/Filespec"),
  257. NameObject("/F"): createStringObject(fname), # Perhaps also try TextStringObject
  258. NameObject("/EF"): efEntry
  259. })
  260. # Then create the entry for the root, as it needs a reference to the Filespec
  261. """ Sample:
  262. 1 0 obj
  263. <<
  264. /Type /Catalog
  265. /Outlines 2 0 R
  266. /Pages 3 0 R
  267. /Names << /EmbeddedFiles << /Names [(hello.txt) 7 0 R] >> >>
  268. >>
  269. endobj
  270. """
  271. embeddedFilesNamesDictionary = DictionaryObject()
  272. embeddedFilesNamesDictionary.update({
  273. NameObject("/Names"): ArrayObject([createStringObject(fname), filespec])
  274. })
  275. embeddedFilesDictionary = DictionaryObject()
  276. embeddedFilesDictionary.update({
  277. NameObject("/EmbeddedFiles"): embeddedFilesNamesDictionary
  278. })
  279. # Update the root
  280. self._root_object.update({
  281. NameObject("/Names"): embeddedFilesDictionary
  282. })
  283. def appendPagesFromReader(self, reader, after_page_append=None):
  284. """
  285. Copy pages from reader to writer. Includes an optional callback parameter
  286. which is invoked after pages are appended to the writer.
  287. :param reader: a PdfFileReader object from which to copy page
  288. annotations to this writer object. The writer's annots
  289. will then be updated
  290. :callback after_page_append (function): Callback function that is invoked after
  291. each page is appended to the writer. Callback signature:
  292. :param writer_pageref (PDF page reference): Reference to the page
  293. appended to the writer.
  294. """
  295. # Get page count from writer and reader
  296. reader_num_pages = reader.getNumPages()
  297. writer_num_pages = self.getNumPages()
  298. # Copy pages from reader to writer
  299. for rpagenum in range(0, reader_num_pages):
  300. reader_page = reader.getPage(rpagenum)
  301. self.addPage(reader_page)
  302. writer_page = self.getPage(writer_num_pages+rpagenum)
  303. # Trigger callback, pass writer page as parameter
  304. if callable(after_page_append): after_page_append(writer_page)
  305. def updatePageFormFieldValues(self, page, fields):
  306. '''
  307. Update the form field values for a given page from a fields dictionary.
  308. Copy field texts and values from fields to page.
  309. :param page: Page reference from PDF writer where the annotations
  310. and field data will be updated.
  311. :param fields: a Python dictionary of field names (/T) and text
  312. values (/V)
  313. '''
  314. # Iterate through pages, update field values
  315. for j in range(0, len(page['/Annots'])):
  316. writer_annot = page['/Annots'][j].getObject()
  317. for field in fields:
  318. if writer_annot.get('/T') == field:
  319. writer_annot.update({
  320. NameObject("/V"): TextStringObject(fields[field])
  321. })
  322. def cloneReaderDocumentRoot(self, reader):
  323. '''
  324. Copy the reader document root to the writer.
  325. :param reader: PdfFileReader from the document root should be copied.
  326. :callback after_page_append
  327. '''
  328. self._root_object = reader.trailer['/Root']
  329. def cloneDocumentFromReader(self, reader, after_page_append=None):
  330. '''
  331. Create a copy (clone) of a document from a PDF file reader
  332. :param reader: PDF file reader instance from which the clone
  333. should be created.
  334. :callback after_page_append (function): Callback function that is invoked after
  335. each page is appended to the writer. Signature includes a reference to the
  336. appended page (delegates to appendPagesFromReader). Callback signature:
  337. :param writer_pageref (PDF page reference): Reference to the page just
  338. appended to the document.
  339. '''
  340. self.cloneReaderDocumentRoot(reader)
  341. self.appendPagesFromReader(reader, after_page_append)
  342. def encrypt(self, user_pwd, owner_pwd = None, use_128bit = True):
  343. """
  344. Encrypt this PDF file with the PDF Standard encryption handler.
  345. :param str user_pwd: The "user password", which allows for opening
  346. and reading the PDF file with the restrictions provided.
  347. :param str owner_pwd: The "owner password", which allows for
  348. opening the PDF files without any restrictions. By default,
  349. the owner password is the same as the user password.
  350. :param bool use_128bit: flag as to whether to use 128bit
  351. encryption. When false, 40bit encryption will be used. By default,
  352. this flag is on.
  353. """
  354. import time, random
  355. if owner_pwd == None:
  356. owner_pwd = user_pwd
  357. if use_128bit:
  358. V = 2
  359. rev = 3
  360. keylen = int(128 / 8)
  361. else:
  362. V = 1
  363. rev = 2
  364. keylen = int(40 / 8)
  365. # permit everything:
  366. P = -1
  367. O = ByteStringObject(_alg33(owner_pwd, user_pwd, rev, keylen))
  368. ID_1 = ByteStringObject(md5(b_(repr(time.time()))).digest())
  369. ID_2 = ByteStringObject(md5(b_(repr(random.random()))).digest())
  370. self._ID = ArrayObject((ID_1, ID_2))
  371. if rev == 2:
  372. U, key = _alg34(user_pwd, O, P, ID_1)
  373. else:
  374. assert rev == 3
  375. U, key = _alg35(user_pwd, rev, keylen, O, P, ID_1, False)
  376. encrypt = DictionaryObject()
  377. encrypt[NameObject("/Filter")] = NameObject("/Standard")
  378. encrypt[NameObject("/V")] = NumberObject(V)
  379. if V == 2:
  380. encrypt[NameObject("/Length")] = NumberObject(keylen * 8)
  381. encrypt[NameObject("/R")] = NumberObject(rev)
  382. encrypt[NameObject("/O")] = ByteStringObject(O)
  383. encrypt[NameObject("/U")] = ByteStringObject(U)
  384. encrypt[NameObject("/P")] = NumberObject(P)
  385. self._encrypt = self._addObject(encrypt)
  386. self._encrypt_key = key
  387. def write(self, stream):
  388. """
  389. Writes the collection of pages added to this object out as a PDF file.
  390. :param stream: An object to write the file to. The object must support
  391. the write method and the tell method, similar to a file object.
  392. """
  393. if hasattr(stream, 'mode') and 'b' not in stream.mode:
  394. warnings.warn("File <%s> to write to is not in binary mode. It may not be written to correctly." % stream.name)
  395. debug = False
  396. import struct
  397. if not self._root:
  398. self._root = self._addObject(self._root_object)
  399. externalReferenceMap = {}
  400. # PDF objects sometimes have circular references to their /Page objects
  401. # inside their object tree (for example, annotations). Those will be
  402. # indirect references to objects that we've recreated in this PDF. To
  403. # address this problem, PageObject's store their original object
  404. # reference number, and we add it to the external reference map before
  405. # we sweep for indirect references. This forces self-page-referencing
  406. # trees to reference the correct new object location, rather than
  407. # copying in a new copy of the page object.
  408. for objIndex in range(len(self._objects)):
  409. obj = self._objects[objIndex]
  410. if isinstance(obj, PageObject) and obj.indirectRef != None:
  411. data = obj.indirectRef
  412. if data.pdf not in externalReferenceMap:
  413. externalReferenceMap[data.pdf] = {}
  414. if data.generation not in externalReferenceMap[data.pdf]:
  415. externalReferenceMap[data.pdf][data.generation] = {}
  416. externalReferenceMap[data.pdf][data.generation][data.idnum] = IndirectObject(objIndex + 1, 0, self)
  417. self.stack = []
  418. if debug: print(("ERM:", externalReferenceMap, "root:", self._root))
  419. self._sweepIndirectReferences(externalReferenceMap, self._root)
  420. del self.stack
  421. # Begin writing:
  422. object_positions = []
  423. stream.write(self._header + b_("\n"))
  424. for i in range(len(self._objects)):
  425. idnum = (i + 1)
  426. obj = self._objects[i]
  427. object_positions.append(stream.tell())
  428. stream.write(b_(str(idnum) + " 0 obj\n"))
  429. key = None
  430. if hasattr(self, "_encrypt") and idnum != self._encrypt.idnum:
  431. pack1 = struct.pack("<i", i + 1)[:3]
  432. pack2 = struct.pack("<i", 0)[:2]
  433. key = self._encrypt_key + pack1 + pack2
  434. assert len(key) == (len(self._encrypt_key) + 5)
  435. md5_hash = md5(key).digest()
  436. key = md5_hash[:min(16, len(self._encrypt_key) + 5)]
  437. obj.writeToStream(stream, key)
  438. stream.write(b_("\nendobj\n"))
  439. # xref table
  440. xref_location = stream.tell()
  441. stream.write(b_("xref\n"))
  442. stream.write(b_("0 %s\n" % (len(self._objects) + 1)))
  443. stream.write(b_("%010d %05d f \n" % (0, 65535)))
  444. for offset in object_positions:
  445. stream.write(b_("%010d %05d n \n" % (offset, 0)))
  446. # trailer
  447. stream.write(b_("trailer\n"))
  448. trailer = DictionaryObject()
  449. trailer.update({
  450. NameObject("/Size"): NumberObject(len(self._objects) + 1),
  451. NameObject("/Root"): self._root,
  452. NameObject("/Info"): self._info,
  453. })
  454. if hasattr(self, "_ID"):
  455. trailer[NameObject("/ID")] = self._ID
  456. if hasattr(self, "_encrypt"):
  457. trailer[NameObject("/Encrypt")] = self._encrypt
  458. trailer.writeToStream(stream, None)
  459. # eof
  460. stream.write(b_("\nstartxref\n%s\n%%%%EOF\n" % (xref_location)))
  461. def addMetadata(self, infos):
  462. """
  463. Add custom metadata to the output.
  464. :param dict infos: a Python dictionary where each key is a field
  465. and each value is your new metadata.
  466. """
  467. args = {}
  468. for key, value in list(infos.items()):
  469. args[NameObject(key)] = createStringObject(value)
  470. self.getObject(self._info).update(args)
  471. def _sweepIndirectReferences(self, externMap, data):
  472. debug = False
  473. if debug: print((data, "TYPE", data.__class__.__name__))
  474. if isinstance(data, DictionaryObject):
  475. for key, value in list(data.items()):
  476. origvalue = value
  477. value = self._sweepIndirectReferences(externMap, value)
  478. if isinstance(value, StreamObject):
  479. # a dictionary value is a stream. streams must be indirect
  480. # objects, so we need to change this value.
  481. value = self._addObject(value)
  482. data[key] = value
  483. return data
  484. elif isinstance(data, ArrayObject):
  485. for i in range(len(data)):
  486. value = self._sweepIndirectReferences(externMap, data[i])
  487. if isinstance(value, StreamObject):
  488. # an array value is a stream. streams must be indirect
  489. # objects, so we need to change this value
  490. value = self._addObject(value)
  491. data[i] = value
  492. return data
  493. elif isinstance(data, IndirectObject):
  494. # internal indirect references are fine
  495. if data.pdf == self:
  496. if data.idnum in self.stack:
  497. return data
  498. else:
  499. self.stack.append(data.idnum)
  500. realdata = self.getObject(data)
  501. self._sweepIndirectReferences(externMap, realdata)
  502. return data
  503. else:
  504. newobj = externMap.get(data.pdf, {}).get(data.generation, {}).get(data.idnum, None)
  505. if newobj == None:
  506. newobj = data.pdf.getObject(data)
  507. self._objects.append(None) # placeholder
  508. idnum = len(self._objects)
  509. newobj_ido = IndirectObject(idnum, 0, self)
  510. if data.pdf not in externMap:
  511. externMap[data.pdf] = {}
  512. if data.generation not in externMap[data.pdf]:
  513. externMap[data.pdf][data.generation] = {}
  514. externMap[data.pdf][data.generation][data.idnum] = newobj_ido
  515. newobj = self._sweepIndirectReferences(externMap, newobj)
  516. self._objects[idnum-1] = newobj
  517. return newobj_ido
  518. return newobj
  519. else:
  520. return data
  521. def getReference(self, obj):
  522. idnum = self._objects.index(obj) + 1
  523. ref = IndirectObject(idnum, 0, self)
  524. assert ref.getObject() == obj
  525. return ref
  526. def getOutlineRoot(self):
  527. if '/Outlines' in self._root_object:
  528. outline = self._root_object['/Outlines']
  529. idnum = self._objects.index(outline) + 1
  530. outlineRef = IndirectObject(idnum, 0, self)
  531. assert outlineRef.getObject() == outline
  532. else:
  533. outline = TreeObject()
  534. outline.update({ })
  535. outlineRef = self._addObject(outline)
  536. self._root_object[NameObject('/Outlines')] = outlineRef
  537. return outline
  538. def getNamedDestRoot(self):
  539. if '/Names' in self._root_object and isinstance(self._root_object['/Names'], DictionaryObject):
  540. names = self._root_object['/Names']
  541. idnum = self._objects.index(names) + 1
  542. namesRef = IndirectObject(idnum, 0, self)
  543. assert namesRef.getObject() == names
  544. if '/Dests' in names and isinstance(names['/Dests'], DictionaryObject):
  545. dests = names['/Dests']
  546. idnum = self._objects.index(dests) + 1
  547. destsRef = IndirectObject(idnum, 0, self)
  548. assert destsRef.getObject() == dests
  549. if '/Names' in dests:
  550. nd = dests['/Names']
  551. else:
  552. nd = ArrayObject()
  553. dests[NameObject('/Names')] = nd
  554. else:
  555. dests = DictionaryObject()
  556. destsRef = self._addObject(dests)
  557. names[NameObject('/Dests')] = destsRef
  558. nd = ArrayObject()
  559. dests[NameObject('/Names')] = nd
  560. else:
  561. names = DictionaryObject()
  562. namesRef = self._addObject(names)
  563. self._root_object[NameObject('/Names')] = namesRef
  564. dests = DictionaryObject()
  565. destsRef = self._addObject(dests)
  566. names[NameObject('/Dests')] = destsRef
  567. nd = ArrayObject()
  568. dests[NameObject('/Names')] = nd
  569. return nd
  570. def addBookmarkDestination(self, dest, parent=None):
  571. destRef = self._addObject(dest)
  572. outlineRef = self.getOutlineRoot()
  573. if parent == None:
  574. parent = outlineRef
  575. parent = parent.getObject()
  576. #print parent.__class__.__name__
  577. parent.addChild(destRef, self)
  578. return destRef
  579. def addBookmarkDict(self, bookmark, parent=None):
  580. bookmarkObj = TreeObject()
  581. for k, v in list(bookmark.items()):
  582. bookmarkObj[NameObject(str(k))] = v
  583. bookmarkObj.update(bookmark)
  584. if '/A' in bookmark:
  585. action = DictionaryObject()
  586. for k, v in list(bookmark['/A'].items()):
  587. action[NameObject(str(k))] = v
  588. actionRef = self._addObject(action)
  589. bookmarkObj[NameObject('/A')] = actionRef
  590. bookmarkRef = self._addObject(bookmarkObj)
  591. outlineRef = self.getOutlineRoot()
  592. if parent == None:
  593. parent = outlineRef
  594. parent = parent.getObject()
  595. parent.addChild(bookmarkRef, self)
  596. return bookmarkRef
  597. def addBookmark(self, title, pagenum, parent=None, color=None, bold=False, italic=False, fit='/Fit', *args):
  598. """
  599. Add a bookmark to this PDF file.
  600. :param str title: Title to use for this bookmark.
  601. :param int pagenum: Page number this bookmark will point to.
  602. :param parent: A reference to a parent bookmark to create nested
  603. bookmarks.
  604. :param tuple color: Color of the bookmark as a red, green, blue tuple
  605. from 0.0 to 1.0
  606. :param bool bold: Bookmark is bold
  607. :param bool italic: Bookmark is italic
  608. :param str fit: The fit of the destination page. See
  609. :meth:`addLink()<addLink>` for details.
  610. """
  611. pageRef = self.getObject(self._pages)['/Kids'][pagenum]
  612. action = DictionaryObject()
  613. zoomArgs = []
  614. for a in args:
  615. if a is not None:
  616. zoomArgs.append(NumberObject(a))
  617. else:
  618. zoomArgs.append(NullObject())
  619. dest = Destination(NameObject("/"+title + " bookmark"), pageRef, NameObject(fit), *zoomArgs)
  620. destArray = dest.getDestArray()
  621. action.update({
  622. NameObject('/D') : destArray,
  623. NameObject('/S') : NameObject('/GoTo')
  624. })
  625. actionRef = self._addObject(action)
  626. outlineRef = self.getOutlineRoot()
  627. if parent == None:
  628. parent = outlineRef
  629. bookmark = TreeObject()
  630. bookmark.update({
  631. NameObject('/A'): actionRef,
  632. NameObject('/Title'): createStringObject(title),
  633. })
  634. if color is not None:
  635. bookmark.update({NameObject('/C'): ArrayObject([FloatObject(c) for c in color])})
  636. format = 0
  637. if italic:
  638. format += 1
  639. if bold:
  640. format += 2
  641. if format:
  642. bookmark.update({NameObject('/F'): NumberObject(format)})
  643. bookmarkRef = self._addObject(bookmark)
  644. parent = parent.getObject()
  645. parent.addChild(bookmarkRef, self)
  646. return bookmarkRef
  647. def addNamedDestinationObject(self, dest):
  648. destRef = self._addObject(dest)
  649. nd = self.getNamedDestRoot()
  650. nd.extend([dest['/Title'], destRef])
  651. return destRef
  652. def addNamedDestination(self, title, pagenum):
  653. pageRef = self.getObject(self._pages)['/Kids'][pagenum]
  654. dest = DictionaryObject()
  655. dest.update({
  656. NameObject('/D') : ArrayObject([pageRef, NameObject('/FitH'), NumberObject(826)]),
  657. NameObject('/S') : NameObject('/GoTo')
  658. })
  659. destRef = self._addObject(dest)
  660. nd = self.getNamedDestRoot()
  661. nd.extend([title, destRef])
  662. return destRef
  663. def removeLinks(self):
  664. """
  665. Removes links and annotations from this output.
  666. """
  667. pages = self.getObject(self._pages)['/Kids']
  668. for page in pages:
  669. pageRef = self.getObject(page)
  670. if "/Annots" in pageRef:
  671. del pageRef['/Annots']
  672. def removeImages(self, ignoreByteStringObject=False):
  673. """
  674. Removes images from this output.
  675. :param bool ignoreByteStringObject: optional parameter
  676. to ignore ByteString Objects.
  677. """
  678. pages = self.getObject(self._pages)['/Kids']
  679. for j in range(len(pages)):
  680. page = pages[j]
  681. pageRef = self.getObject(page)
  682. content = pageRef['/Contents'].getObject()
  683. if not isinstance(content, ContentStream):
  684. content = ContentStream(content, pageRef)
  685. _operations = []
  686. seq_graphics = False
  687. for operands, operator in content.operations:
  688. if operator == b_('Tj'):
  689. text = operands[0]
  690. if ignoreByteStringObject:
  691. if not isinstance(text, TextStringObject):
  692. operands[0] = TextStringObject()
  693. elif operator == b_("'"):
  694. text = operands[0]
  695. if ignoreByteStringObject:
  696. if not isinstance(text, TextStringObject):
  697. operands[0] = TextStringObject()
  698. elif operator == b_('"'):
  699. text = operands[2]
  700. if ignoreByteStringObject:
  701. if not isinstance(text, TextStringObject):
  702. operands[2] = TextStringObject()
  703. elif operator == b_("TJ"):
  704. for i in range(len(operands[0])):
  705. if ignoreByteStringObject:
  706. if not isinstance(operands[0][i], TextStringObject):
  707. operands[0][i] = TextStringObject()
  708. if operator == b_('q'):
  709. seq_graphics = True
  710. if operator == b_('Q'):
  711. seq_graphics = False
  712. if seq_graphics:
  713. if operator in [b_('cm'), b_('w'), b_('J'), b_('j'), b_('M'), b_('d'), b_('ri'), b_('i'),
  714. b_('gs'), b_('W'), b_('b'), b_('s'), b_('S'), b_('f'), b_('F'), b_('n'), b_('m'), b_('l'),
  715. b_('c'), b_('v'), b_('y'), b_('h'), b_('B'), b_('Do'), b_('sh')]:
  716. continue
  717. if operator == b_('re'):
  718. continue
  719. _operations.append((operands, operator))
  720. content.operations = _operations
  721. pageRef.__setitem__(NameObject('/Contents'), content)
  722. def removeText(self, ignoreByteStringObject=False):
  723. """
  724. Removes images from this output.
  725. :param bool ignoreByteStringObject: optional parameter
  726. to ignore ByteString Objects.
  727. """
  728. pages = self.getObject(self._pages)['/Kids']
  729. for j in range(len(pages)):
  730. page = pages[j]
  731. pageRef = self.getObject(page)
  732. content = pageRef['/Contents'].getObject()
  733. if not isinstance(content, ContentStream):
  734. content = ContentStream(content, pageRef)
  735. for operands,operator in content.operations:
  736. if operator == b_('Tj'):
  737. text = operands[0]
  738. if not ignoreByteStringObject:
  739. if isinstance(text, TextStringObject):
  740. operands[0] = TextStringObject()
  741. else:
  742. if isinstance(text, TextStringObject) or \
  743. isinstance(text, ByteStringObject):
  744. operands[0] = TextStringObject()
  745. elif operator == b_("'"):
  746. text = operands[0]
  747. if not ignoreByteStringObject:
  748. if isinstance(text, TextStringObject):
  749. operands[0] = TextStringObject()
  750. else:
  751. if isinstance(text, TextStringObject) or \
  752. isinstance(text, ByteStringObject):
  753. operands[0] = TextStringObject()
  754. elif operator == b_('"'):
  755. text = operands[2]
  756. if not ignoreByteStringObject:
  757. if isinstance(text, TextStringObject):
  758. operands[2] = TextStringObject()
  759. else:
  760. if isinstance(text, TextStringObject) or \
  761. isinstance(text, ByteStringObject):
  762. operands[2] = TextStringObject()
  763. elif operator == b_("TJ"):
  764. for i in range(len(operands[0])):
  765. if not ignoreByteStringObject:
  766. if isinstance(operands[0][i], TextStringObject):
  767. operands[0][i] = TextStringObject()
  768. else:
  769. if isinstance(operands[0][i], TextStringObject) or \
  770. isinstance(operands[0][i], ByteStringObject):
  771. operands[0][i] = TextStringObject()
  772. pageRef.__setitem__(NameObject('/Contents'), content)
  773. def addLink(self, pagenum, pagedest, rect, border=None, fit='/Fit', *args):
  774. """
  775. Add an internal link from a rectangular area to the specified page.
  776. :param int pagenum: index of the page on which to place the link.
  777. :param int pagedest: index of the page to which the link should go.
  778. :param rect: :class:`RectangleObject<PyPDF2.generic.RectangleObject>` or array of four
  779. integers specifying the clickable rectangular area
  780. ``[xLL, yLL, xUR, yUR]``, or string in the form ``"[ xLL yLL xUR yUR ]"``.
  781. :param border: if provided, an array describing border-drawing
  782. properties. See the PDF spec for details. No border will be
  783. drawn if this argument is omitted.
  784. :param str fit: Page fit or 'zoom' option (see below). Additional arguments may need
  785. to be supplied. Passing ``None`` will be read as a null value for that coordinate.
  786. Valid zoom arguments (see Table 8.2 of the PDF 1.7 reference for details):
  787. /Fit No additional arguments
  788. /XYZ [left] [top] [zoomFactor]
  789. /FitH [top]
  790. /FitV [left]
  791. /FitR [left] [bottom] [right] [top]
  792. /FitB No additional arguments
  793. /FitBH [top]
  794. /FitBV [left]
  795. """
  796. pageLink = self.getObject(self._pages)['/Kids'][pagenum]
  797. pageDest = self.getObject(self._pages)['/Kids'][pagedest] #TODO: switch for external link
  798. pageRef = self.getObject(pageLink)
  799. if border is not None:
  800. borderArr = [NameObject(n) for n in border[:3]]
  801. if len(border) == 4:
  802. dashPattern = ArrayObject([NameObject(n) for n in border[3]])
  803. borderArr.append(dashPattern)
  804. else:
  805. borderArr = [NumberObject(0)] * 3
  806. if isString(rect):
  807. rect = NameObject(rect)
  808. elif isinstance(rect, RectangleObject):
  809. pass
  810. else:
  811. rect = RectangleObject(rect)
  812. zoomArgs = []
  813. for a in args:
  814. if a is not None:
  815. zoomArgs.append(NumberObject(a))
  816. else:
  817. zoomArgs.append(NullObject())
  818. dest = Destination(NameObject("/LinkName"), pageDest, NameObject(fit), *zoomArgs) #TODO: create a better name for the link
  819. destArray = dest.getDestArray()
  820. lnk = DictionaryObject()
  821. lnk.update({
  822. NameObject('/Type'): NameObject('/Annot'),
  823. NameObject('/Subtype'): NameObject('/Link'),
  824. NameObject('/P'): pageLink,
  825. NameObject('/Rect'): rect,
  826. NameObject('/Border'): ArrayObject(borderArr),
  827. NameObject('/Dest'): destArray
  828. })
  829. lnkRef = self._addObject(lnk)
  830. if "/Annots" in pageRef:
  831. pageRef['/Annots'].append(lnkRef)
  832. else:
  833. pageRef[NameObject('/Annots')] = ArrayObject([lnkRef])
  834. _valid_layouts = ['/NoLayout', '/SinglePage', '/OneColumn', '/TwoColumnLeft', '/TwoColumnRight', '/TwoPageLeft', '/TwoPageRight']
  835. def getPageLayout(self):
  836. """
  837. Get the page layout.
  838. See :meth:`setPageLayout()<PdfFileWriter.setPageLayout>` for a description of valid layouts.
  839. :return: Page layout currently being used.
  840. :rtype: str, None if not specified
  841. """
  842. try:
  843. return self._root_object['/PageLayout']
  844. except KeyError:
  845. return None
  846. def setPageLayout(self, layout):
  847. """
  848. Set the page layout
  849. :param str layout: The page layout to be used
  850. Valid layouts are:
  851. /NoLayout Layout explicitly not specified
  852. /SinglePage Show one page at a time
  853. /OneColumn Show one column at a time
  854. /TwoColumnLeft Show pages in two columns, odd-numbered pages on the left
  855. /TwoColumnRight Show pages in two columns, odd-numbered pages on the right
  856. /TwoPageLeft Show two pages at a time, odd-numbered pages on the left
  857. /TwoPageRight Show two pages at a time, odd-numbered pages on the right
  858. """
  859. if not isinstance(layout, NameObject):
  860. if layout not in self._valid_layouts:
  861. warnings.warn("Layout should be one of: {}".format(', '.join(self._valid_layouts)))
  862. layout = NameObject(layout)
  863. self._root_object.update({NameObject('/PageLayout'): layout})
  864. pageLayout = property(getPageLayout, setPageLayout)
  865. """Read and write property accessing the :meth:`getPageLayout()<PdfFileWriter.getPageLayout>`
  866. and :meth:`setPageLayout()<PdfFileWriter.setPageLayout>` methods."""
  867. _valid_modes = ['/UseNone', '/UseOutlines', '/UseThumbs', '/FullScreen', '/UseOC', '/UseAttachments']
  868. def getPageMode(self):
  869. """
  870. Get the page mode.
  871. See :meth:`setPageMode()<PdfFileWriter.setPageMode>` for a description
  872. of valid modes.
  873. :return: Page mode currently being used.
  874. :rtype: str, None if not specified
  875. """
  876. try:
  877. return self._root_object['/PageMode']
  878. except KeyError:
  879. return None
  880. def setPageMode(self, mode):
  881. """
  882. Set the page mode.
  883. :param str mode: The page mode to use.
  884. Valid modes are:
  885. /UseNone Do not show outlines or thumbnails panels
  886. /UseOutlines Show outlines (aka bookmarks) panel
  887. /UseThumbs Show page thumbnails panel
  888. /FullScreen Fullscreen view
  889. /UseOC Show Optional Content Group (OCG) panel
  890. /UseAttachments Show attachments panel
  891. """
  892. if not isinstance(mode, NameObject):
  893. if mode not in self._valid_modes:
  894. warnings.warn("Mode should be one of: {}".format(', '.join(self._valid_modes)))
  895. mode = NameObject(mode)
  896. self._root_object.update({NameObject('/PageMode'): mode})
  897. pageMode = property(getPageMode, setPageMode)
  898. """Read and write property accessing the :meth:`getPageMode()<PdfFileWriter.getPageMode>`
  899. and :meth:`setPageMode()<PdfFileWriter.setPageMode>` methods."""
  900. class PdfFileReader(object):
  901. """
  902. Initializes a PdfFileReader object. This operation can take some time, as
  903. the PDF stream's cross-reference tables are read into memory.
  904. :param stream: A File object or an object that supports the standard read
  905. and seek methods similar to a File object. Could also be a
  906. string representing a path to a PDF file.
  907. :param bool strict: Determines whether user should be warned of all
  908. problems and also causes some correctable problems to be fatal.
  909. Defaults to ``True``.
  910. :param warndest: Destination for logging warnings (defaults to
  911. ``sys.stderr``).
  912. :param bool overwriteWarnings: Determines whether to override Python's
  913. ``warnings.py`` module with a custom implementation (defaults to
  914. ``True``).
  915. """
  916. def __init__(self, stream, strict=True, warndest = None, overwriteWarnings = True):
  917. if overwriteWarnings:
  918. # have to dynamically override the default showwarning since there are no
  919. # public methods that specify the 'file' parameter
  920. def _showwarning(message, category, filename, lineno, file=warndest, line=None):
  921. if file is None:
  922. file = sys.stderr
  923. try:
  924. file.write(formatWarning(message, category, filename, lineno, line))
  925. except IOError:
  926. pass
  927. warnings.showwarning = _showwarning
  928. self.strict = strict
  929. self.flattenedPages = None
  930. self.resolvedObjects = {}
  931. self.xrefIndex = 0
  932. self._pageId2Num = None # map page IndirectRef number to Page Number
  933. if hasattr(stream, 'mode') and 'b' not in stream.mode:
  934. warnings.warn("PdfFileReader stream/file object is not in binary mode. It may not be read correctly.", utils.PdfReadWarning)
  935. if isString(stream):
  936. fileobj = open(stream, 'rb')
  937. stream = BytesIO(b_(fileobj.read()))
  938. fileobj.close()
  939. self.read(stream)
  940. self.stream = stream
  941. self._override_encryption = False
  942. def getDocumentInfo(self):
  943. """
  944. Retrieves the PDF file's document information dictionary, if it exists.
  945. Note that some PDF files use metadata streams instead of docinfo
  946. dictionaries, and these metadata streams will not be accessed by this
  947. function.
  948. :return: the document information of this PDF file
  949. :rtype: :class:`DocumentInformation<pdf.DocumentInformation>` or ``None`` if none exists.
  950. """
  951. if "/Info" not in self.trailer:
  952. return None
  953. obj = self.trailer['/Info']
  954. retval = DocumentInformation()
  955. retval.update(obj)
  956. return retval
  957. documentInfo = property(lambda self: self.getDocumentInfo(), None, None)
  958. """Read-only property that accesses the :meth:`getDocumentInfo()<PdfFileReader.getDocumentInfo>` function."""
  959. def getXmpMetadata(self):
  960. """
  961. Retrieves XMP (Extensible Metadata Platform) data from the PDF document
  962. root.
  963. :return: a :class:`XmpInformation<xmp.XmpInformation>`
  964. instance that can be used to access XMP metadata from the document.
  965. :rtype: :class:`XmpInformation<xmp.XmpInformation>` or
  966. ``None`` if no metadata was found on the document root.
  967. """
  968. try:
  969. self._override_encryption = True
  970. return self.trailer["/Root"].getXmpMetadata()
  971. finally:
  972. self._override_encryption = False
  973. xmpMetadata = property(lambda self: self.getXmpMetadata(), None, None)
  974. """
  975. Read-only property that accesses the
  976. :meth:`getXmpMetadata()<PdfFileReader.getXmpMetadata>` function.
  977. """
  978. def getNumPages(self):
  979. """
  980. Calculates the number of pages in this PDF file.
  981. :return: number of pages
  982. :rtype: int
  983. :raises PdfReadError: if file is encrypted and restrictions prevent
  984. this action.
  985. """
  986. # Flattened pages will not work on an Encrypted PDF;
  987. # the PDF file's page count is used in this case. Otherwise,
  988. # the original method (flattened page count) is used.
  989. if self.isEncrypted:
  990. try:
  991. self._override_encryption = True
  992. self.decrypt('')
  993. return self.trailer["/Root"]["/Pages"]["/Count"]
  994. except:
  995. raise utils.PdfReadError("File has not been decrypted")
  996. finally:
  997. self._override_encryption = False
  998. else:
  999. if self.flattenedPages == None:
  1000. self._flatten()
  1001. return len(self.flattenedPages)
  1002. numPages = property(lambda self: self.getNumPages(), None, None)
  1003. """
  1004. Read-only property that accesses the
  1005. :meth:`getNumPages()<PdfFileReader.getNumPages>` function.
  1006. """
  1007. def getPage(self, pageNumber):
  1008. """
  1009. Retrieves a page by number from this PDF file.
  1010. :param int pageNumber: The page number to retrieve
  1011. (pages begin at zero)
  1012. :return: a :class:`PageObject<pdf.PageObject>` instance.
  1013. :rtype: :class:`PageObject<pdf.PageObject>`
  1014. """
  1015. ## ensure that we're not trying to access an encrypted PDF
  1016. #assert not self.trailer.has_key("/Encrypt")
  1017. if self.flattenedPages == None:
  1018. self._flatten()
  1019. return self.flattenedPages[pageNumber]
  1020. namedDestinations = property(lambda self:
  1021. self.getNamedDestinations(), None, None)
  1022. """
  1023. Read-only property that accesses the
  1024. :meth:`getNamedDestinations()<PdfFileReader.getNamedDestinations>` function.
  1025. """
  1026. # A select group of relevant field attributes. For the complete list,
  1027. # see section 8.6.2 of the PDF 1.7 reference.
  1028. def getFields(self, tree = None, retval = None, fileobj = None):
  1029. """
  1030. Extracts field data if this PDF contains interactive form fields.
  1031. The *tree* and *retval* parameters are for recursive use.
  1032. :param fileobj: A file object (usually a text file) to write
  1033. a report to on all interactive form fields found.
  1034. :return: A dictionary where each key is a field name, and each
  1035. value is a :class:`Field<PyPDF2.generic.Field>` object. By
  1036. default, the mapping name is used for keys.
  1037. :rtype: dict, or ``None`` if form data could not be located.
  1038. """
  1039. fieldAttributes = {"/FT" : "Field Type", "/Parent" : "Parent",
  1040. "/T" : "Field Name", "/TU" : "Alternate Field Name",
  1041. "/TM" : "Mapping Name", "/Ff" : "Field Flags",
  1042. "/V" : "Value", "/DV" : "Default Value"}
  1043. if retval == None:
  1044. retval = {}
  1045. catalog = self.trailer["/Root"]
  1046. # get the AcroForm tree
  1047. if "/AcroForm" in catalog:
  1048. tree = catalog["/AcroForm"]
  1049. else:
  1050. return None
  1051. if tree == None:
  1052. return retval
  1053. self._checkKids(tree, retval, fileobj)
  1054. for attr in fieldAttributes:
  1055. if attr in tree:
  1056. # Tree is a field
  1057. self._buildField(tree, retval, fileobj, fieldAttributes)
  1058. break
  1059. if "/Fields" in tree:
  1060. fields = tree["/Fields"]
  1061. for f in fields:
  1062. field = f.getObject()
  1063. self._buildField(field, retval, fileobj, fieldAttributes)
  1064. return retval
  1065. def _buildField(self, field, retval, fileobj, fieldAttributes):
  1066. self._checkKids(field, retval, fileobj)
  1067. try:
  1068. key = field["/TM"]
  1069. except KeyError:
  1070. try:
  1071. key = field["/T"]
  1072. except KeyError:
  1073. # Ignore no-name field for now
  1074. return
  1075. if fileobj:
  1076. self._writeField(fileobj, field, fieldAttributes)
  1077. fileobj.write("\n")
  1078. retval[key] = Field(field)
  1079. def _checkKids(self, tree, retval, fileobj):
  1080. if "/Kids" in tree:
  1081. # recurse down the tree
  1082. for kid in tree["/Kids"]:
  1083. self.getFields(kid.getObject(), retval, fileobj)
  1084. def _writeField(self, fileobj, field, fieldAttributes):
  1085. order = ["/TM", "/T", "/FT", "/Parent", "/TU", "/Ff", "/V", "/DV"]
  1086. for attr in order:
  1087. attrName = fieldAttributes[attr]
  1088. try:
  1089. if attr == "/FT":
  1090. # Make the field type value more clear
  1091. types = {"/Btn":"Button", "/Tx":"Text", "/Ch": "Choice",
  1092. "/Sig":"Signature"}
  1093. if field[attr] in types:
  1094. fileobj.write(attrName + ": " + types[field[attr]] + "\n")
  1095. elif attr == "/Parent":
  1096. # Let's just write the name of the parent
  1097. try:
  1098. name = field["/Parent"]["/TM"]
  1099. except KeyError:
  1100. name = field["/Parent"]["/T"]
  1101. fileobj.write(attrName + ": " + name + "\n")
  1102. else:
  1103. fileobj.write(attrName + ": " + str(field[attr]) + "\n")
  1104. except KeyError:
  1105. # Field attribute is N/A or unknown, so don't write anything
  1106. pass
  1107. def getNamedDestinations(self, tree=None, retval=None):
  1108. """
  1109. Retrieves the named destinations present in the document.
  1110. :return: a dictionary which maps names to
  1111. :class:`Destinations<PyPDF2.generic.Destination>`.
  1112. :rtype: dict
  1113. """
  1114. if retval == None:
  1115. retval = {}
  1116. catalog = self.trailer["/Root"]
  1117. # get the name tree
  1118. if "/Dests" in catalog:
  1119. tree = catalog["/Dests"]
  1120. elif "/Names" in catalog:
  1121. names = catalog['/Names']
  1122. if "/Dests" in names:
  1123. tree = names['/Dests']
  1124. if tree == None:
  1125. return retval
  1126. if "/Kids" in tree:
  1127. # recurse down the tree
  1128. for kid in tree["/Kids"]:
  1129. self.getNamedDestinations(kid.getObject(), retval)
  1130. if "/Names" in tree:
  1131. names = tree["/Names"]
  1132. for i in range(0, len(names), 2):
  1133. key = names[i].getObject()
  1134. val = names[i+1].getObject()
  1135. if isinstance(val, DictionaryObject) and '/D' in val:
  1136. val = val['/D']
  1137. dest = self._buildDestination(key, val)
  1138. if dest != None:
  1139. retval[key] = dest
  1140. return retval
  1141. outlines = property(lambda self: self.getOutlines(), None, None)
  1142. """
  1143. Read-only property that accesses the
  1144. :meth:`getOutlines()<PdfFileReader.getOutlines>` function.
  1145. """
  1146. def getOutlines(self, node=None, outlines=None):
  1147. """
  1148. Retrieves the document outline present in the document.
  1149. :return: a nested list of :class:`Destinations<PyPDF2.generic.Destination>`.
  1150. """
  1151. if outlines == None:
  1152. outlines = []
  1153. catalog = self.trailer["/Root"]
  1154. # get the outline dictionary and named destinations
  1155. if "/Outlines" in catalog:
  1156. try:
  1157. lines = catalog["/Outlines"]
  1158. except utils.PdfReadError:
  1159. # this occurs if the /Outlines object reference is incorrect
  1160. # for an example of such a file, see https://unglueit-files.s3.amazonaws.com/ebf/7552c42e9280b4476e59e77acc0bc812.pdf
  1161. # so continue to load the file without the Bookmarks
  1162. return outlines
  1163. if "/First" in lines:
  1164. node = lines["/First"]
  1165. self._namedDests = self.getNamedDestinations()
  1166. if node == None:
  1167. return outlines
  1168. # see if there are any more outlines
  1169. while True:
  1170. outline = self._buildOutline(node)
  1171. if outline:
  1172. outlines.append(outline)
  1173. # check for sub-outlines
  1174. if "/First" in node:
  1175. subOutlines = []
  1176. self.getOutlines(node["/First"], subOutlines)
  1177. if subOutlines:
  1178. outlines.append(subOutlines)
  1179. if "/Next" not in node:
  1180. break
  1181. node = node["/Next"]
  1182. return outlines
  1183. def _getPageNumberByIndirect(self, indirectRef):
  1184. """Generate _pageId2Num"""
  1185. if self._pageId2Num is None:
  1186. id2num = {}
  1187. for i, x in enumerate(self.pages):
  1188. id2num[x.indirectRef.idnum] = i
  1189. self._pageId2Num = id2num
  1190. if isinstance(indirectRef, int):
  1191. idnum = indirectRef
  1192. else:
  1193. idnum = indirectRef.idnum
  1194. ret = self._pageId2Num.get(idnum, -1)
  1195. return ret
  1196. def getPageNumber(self, page):
  1197. """
  1198. Retrieve page number of a given PageObject
  1199. :param PageObject page: The page to get page number. Should be
  1200. an instance of :class:`PageObject<PyPDF2.pdf.PageObject>`
  1201. :return: the page number or -1 if page not found
  1202. :rtype: int
  1203. """
  1204. indirectRef = page.indirectRef
  1205. ret = self._getPageNumberByIndirect(indirectRef)
  1206. return ret
  1207. def getDestinationPageNumber(self, destination):
  1208. """
  1209. Retrieve page number of a given Destination object
  1210. :param Destination destination: The destination to get page number.
  1211. Should be an instance of
  1212. :class:`Destination<PyPDF2.pdf.Destination>`
  1213. :return: the page number or -1 if page not found
  1214. :rtype: int
  1215. """
  1216. indirectRef = destination.page
  1217. ret = self._getPageNumberByIndirect(indirectRef)
  1218. return ret
  1219. def _buildDestination(self, title, array):
  1220. page, typ = array[0:2]
  1221. array = array[2:]
  1222. return Destination(title, page, typ, *array)
  1223. def _buildOutline(self, node):
  1224. dest, title, outline = None, None, None
  1225. if "/A" in node and "/Title" in node:
  1226. # Action, section 8.5 (only type GoTo supported)
  1227. title = node["/Title"]
  1228. action = node["/A"]
  1229. if action["/S"] == "/GoTo":
  1230. dest = action["/D"]
  1231. elif "/Dest" in node and "/Title" in node:
  1232. # Destination, section 8.2.1
  1233. title = node["/Title"]
  1234. dest = node["/Dest"]
  1235. # if destination found, then create outline
  1236. if dest:
  1237. if isinstance(dest, ArrayObject):
  1238. outline = self._buildDestination(title, dest)
  1239. elif isString(dest) and dest in self._namedDests:
  1240. outline = self._namedDests[dest]
  1241. outline[NameObject("/Title")] = title
  1242. else:
  1243. raise utils.PdfReadError("Unexpected destination %r" % dest)
  1244. return outline
  1245. pages = property(lambda self: ConvertFunctionsToVirtualList(self.getNumPages, self.getPage),
  1246. None, None)
  1247. """
  1248. Read-only property that emulates a list based upon the
  1249. :meth:`getNumPages()<PdfFileReader.getNumPages>` and
  1250. :meth:`getPage()<PdfFileReader.getPage>` methods.
  1251. """
  1252. def getPageLayout(self):
  1253. """
  1254. Get the page layout.
  1255. See :meth:`setPageLayout()<PdfFileWriter.setPageLayout>`
  1256. for a description of valid layouts.
  1257. :return: Page layout currently being used.
  1258. :rtype: ``str``, ``None`` if not specified
  1259. """
  1260. try:
  1261. return self.trailer['/Root']['/PageLayout']
  1262. except KeyError:
  1263. return None
  1264. pageLayout = property(getPageLayout)
  1265. """Read-only property accessing the
  1266. :meth:`getPageLayout()<PdfFileReader.getPageLayout>` method."""
  1267. def getPageMode(self):
  1268. """
  1269. Get the page mode.
  1270. See :meth:`setPageMode()<PdfFileWriter.setPageMode>`
  1271. for a description of valid modes.
  1272. :return: Page mode currently being used.
  1273. :rtype: ``str``, ``None`` if not specified
  1274. """
  1275. try:
  1276. return self.trailer['/Root']['/PageMode']
  1277. except KeyError:
  1278. return None
  1279. pageMode = property(getPageMode)
  1280. """Read-only property accessing the
  1281. :meth:`getPageMode()<PdfFileReader.getPageMode>` method."""
  1282. def _flatten(self, pages=None, inherit=None, indirectRef=None):
  1283. inheritablePageAttributes = (
  1284. NameObject("/Resources"), NameObject("/MediaBox"),
  1285. NameObject("/CropBox"), NameObject("/Rotate")
  1286. )
  1287. if inherit == None:
  1288. inherit = dict()
  1289. if pages == None:
  1290. self.flattenedPages = []
  1291. catalog = self.trailer["/Root"].getObject()
  1292. pages = catalog["/Pages"].getObject()
  1293. t = "/Pages"
  1294. if "/Type" in pages:
  1295. t = pages["/Type"]
  1296. if t == "/Pages":
  1297. for attr in inheritablePageAttributes:
  1298. if attr in pages:
  1299. inherit[attr] = pages[attr]
  1300. for page in pages["/Kids"]:
  1301. addt = {}
  1302. if isinstance(page, IndirectObject):
  1303. addt["indirectRef"] = page
  1304. self._flatten(page.getObject(), inherit, **addt)
  1305. elif t == "/Page":
  1306. for attr, value in list(inherit.items()):
  1307. # if the page has it's own value, it does not inherit the
  1308. # parent's value:
  1309. if attr not in pages:
  1310. pages[attr] = value
  1311. pageObj = PageObject(self, indirectRef)
  1312. pageObj.update(pages)
  1313. self.flattenedPages.append(pageObj)
  1314. def _getObjectFromStream(self, indirectReference):
  1315. # indirect reference to object in object stream
  1316. # read the entire object stream into memory
  1317. debug = False
  1318. stmnum, idx = self.xref_objStm[indirectReference.idnum]
  1319. if debug: print(("Here1: %s %s"%(stmnum, idx)))
  1320. objStm = IndirectObject(stmnum, 0, self).getObject()
  1321. if debug: print(("Here2: objStm=%s.. stmnum=%s data=%s"%(objStm, stmnum, objStm.getData())))
  1322. # This is an xref to a stream, so its type better be a stream
  1323. assert objStm['/Type'] == '/ObjStm'
  1324. # /N is the number of indirect objects in the stream
  1325. assert idx < objStm['/N']
  1326. streamData = BytesIO(b_(objStm.getData()))
  1327. for i in range(objStm['/N']):
  1328. readNonWhitespace(streamData)
  1329. streamData.seek(-1, 1)
  1330. objnum = NumberObject.readFromStream(streamData)
  1331. readNonWhitespace(streamData)
  1332. streamData.seek(-1, 1)
  1333. offset = NumberObject.readFromStream(streamData)
  1334. readNonWhitespace(streamData)
  1335. streamData.seek(-1, 1)
  1336. if objnum != indirectReference.idnum:
  1337. # We're only interested in one object
  1338. continue
  1339. if self.strict and idx != i:
  1340. raise utils.PdfReadError("Object is in wrong index.")
  1341. streamData.seek(objStm['/First']+offset, 0)
  1342. if debug:
  1343. pos = streamData.tell()
  1344. streamData.seek(0, 0)
  1345. lines = streamData.readlines()
  1346. for i in range(0, len(lines)):
  1347. print((lines[i]))
  1348. streamData.seek(pos, 0)
  1349. try:
  1350. obj = readObject(streamData, self)
  1351. except utils.PdfStreamError as e:
  1352. # Stream object cannot be read. Normally, a critical error, but
  1353. # Adobe Reader doesn't complain, so continue (in strict mode?)
  1354. e = sys.exc_info()[1]
  1355. warnings.warn("Invalid stream (index %d) within object %d %d: %s" % \
  1356. (i, indirectReference.idnum, indirectReference.generation, e), utils.PdfReadWarning)
  1357. if self.strict:
  1358. raise utils.PdfReadError("Can't read object stream: %s"%e)
  1359. # Replace with null. Hopefully it's nothing important.
  1360. obj = NullObject()
  1361. return obj
  1362. if self.strict: raise utils.PdfReadError("This is a fatal error in strict mode.")
  1363. return NullObject()
  1364. def getObject(self, indirectReference):
  1365. debug = False
  1366. if debug: print(("looking at:", indirectReference.idnum, indirectReference.generation))
  1367. retval = self.cacheGetIndirectObject(indirectReference.generation,
  1368. indirectReference.idnum)
  1369. if retval != None:
  1370. return retval
  1371. if indirectReference.generation == 0 and \
  1372. indirectReference.idnum in self.xref_objStm:
  1373. retval = self._getObjectFromStream(indirectReference)
  1374. elif indirectReference.generation in self.xref and \
  1375. indirectReference.idnum in self.xref[indirectReference.generation]:
  1376. start = self.xref[indirectReference.generation][indirectReference.idnum]
  1377. if debug: print((" Uncompressed Object", indirectReference.idnum, indirectReference.generation, ":", start))
  1378. self.stream.seek(start, 0)
  1379. idnum, generation = self.readObjectHeader(self.stream)
  1380. if idnum != indirectReference.idnum and self.xrefIndex:
  1381. # Xref table probably had bad indexes due to not being zero-indexed
  1382. if self.strict:
  1383. raise utils.PdfReadError("Expected object ID (%d %d) does not match actual (%d %d); xref table not zero-indexed." \
  1384. % (indirectReference.idnum, indirectReference.generation, idnum, generation))
  1385. else: pass # xref table is corrected in non-strict mode
  1386. elif idnum != indirectReference.idnum:
  1387. # some other problem
  1388. raise utils.PdfReadError("Expected object ID (%d %d) does not match actual (%d %d)." \
  1389. % (indirectReference.idnum, indirectReference.generation, idnum, generation))
  1390. assert generation == indirectReference.generation
  1391. retval = readObject(self.stream, self)
  1392. # override encryption is used for the /Encrypt dictionary
  1393. if not self._override_encryption and self.isEncrypted:
  1394. # if we don't have the encryption key:
  1395. if not hasattr(self, '_decryption_key'):
  1396. raise utils.PdfReadError("file has not been decrypted")
  1397. # otherwise, decrypt here...
  1398. import struct
  1399. pack1 = struct.pack("<i", indirectReference.idnum)[:3]
  1400. pack2 = struct.pack("<i", indirectReference.generation)[:2]
  1401. key = self._decryption_key + pack1 + pack2
  1402. assert len(key) == (len(self._decryption_key) + 5)
  1403. md5_hash = md5(key).digest()
  1404. key = md5_hash[:min(16, len(self._decryption_key) + 5)]
  1405. retval = self._decryptObject(retval, key)
  1406. else:
  1407. warnings.warn("Object %d %d not defined."%(indirectReference.idnum,
  1408. indirectReference.generation), utils.PdfReadWarning)
  1409. #if self.strict:
  1410. raise utils.PdfReadError("Could not find object.")
  1411. self.cacheIndirectObject(indirectReference.generation,
  1412. indirectReference.idnum, retval)
  1413. return retval
  1414. def _decryptObject(self, obj, key):
  1415. if isinstance(obj, ByteStringObject) or isinstance(obj, TextStringObject):
  1416. obj = createStringObject(utils.RC4_encrypt(key, obj.original_bytes))
  1417. elif isinstance(obj, StreamObject):
  1418. obj._data = utils.RC4_encrypt(key, obj._data)
  1419. elif isinstance(obj, DictionaryObject):
  1420. for dictkey, value in list(obj.items()):
  1421. obj[dictkey] = self._decryptObject(value, key)
  1422. elif isinstance(obj, ArrayObject):
  1423. for i in range(len(obj)):
  1424. obj[i] = self._decryptObject(obj[i], key)
  1425. return obj
  1426. def readObjectHeader(self, stream):
  1427. # Should never be necessary to read out whitespace, since the
  1428. # cross-reference table should put us in the right spot to read the
  1429. # object header. In reality... some files have stupid cross reference
  1430. # tables that are off by whitespace bytes.
  1431. extra = False
  1432. utils.skipOverComment(stream)
  1433. extra |= utils.skipOverWhitespace(stream); stream.seek(-1, 1)
  1434. idnum = readUntilWhitespace(stream)
  1435. extra |= utils.skipOverWhitespace(stream); stream.seek(-1, 1)
  1436. generation = readUntilWhitespace(stream)
  1437. obj = stream.read(3)
  1438. readNonWhitespace(stream)
  1439. stream.seek(-1, 1)
  1440. if (extra and self.strict):
  1441. #not a fatal error
  1442. warnings.warn("Superfluous whitespace found in object header %s %s" % \
  1443. (idnum, generation), utils.PdfReadWarning)
  1444. return int(idnum), int(generation)
  1445. def cacheGetIndirectObject(self, generation, idnum):
  1446. debug = False
  1447. out = self.resolvedObjects.get((generation, idnum))
  1448. if debug and out: print(("cache hit: %d %d"%(idnum, generation)))
  1449. elif debug: print(("cache miss: %d %d"%(idnum, generation)))
  1450. return out
  1451. def cacheIndirectObject(self, generation, idnum, obj):
  1452. # return None # Sometimes we want to turn off cache for debugging.
  1453. if (generation, idnum) in self.resolvedObjects:
  1454. msg = "Overwriting cache for %s %s"%(generation, idnum)
  1455. if self.strict: raise utils.PdfReadError(msg)
  1456. else: warnings.warn(msg)
  1457. self.resolvedObjects[(generation, idnum)] = obj
  1458. return obj
  1459. def read(self, stream):
  1460. debug = False
  1461. if debug: print(">>read", stream)
  1462. # start at the end:
  1463. stream.seek(-1, 2)
  1464. if not stream.tell():
  1465. raise utils.PdfReadError('Cannot read an empty file')
  1466. last1K = stream.tell() - 1024 + 1 # offset of last 1024 bytes of stream
  1467. line = b_('')
  1468. while line[:5] != b_("%%EOF"):
  1469. if stream.tell() < last1K:
  1470. raise utils.PdfReadError("EOF marker not found")
  1471. line = self.readNextEndLine(stream)
  1472. if debug: print(" line:",line)
  1473. # find startxref entry - the location of the xref table
  1474. line = self.readNextEndLine(stream)
  1475. try:
  1476. startxref = int(line)
  1477. except ValueError:
  1478. # 'startxref' may be on the same line as the location
  1479. if not line.startswith(b_("startxref")):
  1480. raise utils.PdfReadError("startxref not found")
  1481. startxref = int(line[9:].strip())
  1482. warnings.warn("startxref on same line as offset")
  1483. else:
  1484. line = self.readNextEndLine(stream)
  1485. if line[:9] != b_("startxref"):
  1486. raise utils.PdfReadError("startxref not found")
  1487. # read all cross reference tables and their trailers
  1488. self.xref = {}
  1489. self.xref_objStm = {}
  1490. self.trailer = DictionaryObject()
  1491. while True:
  1492. # load the xref table
  1493. stream.seek(startxref, 0)
  1494. x = stream.read(1)
  1495. if x == b_("x"):
  1496. # standard cross-reference table
  1497. ref = stream.read(4)
  1498. if ref[:3] != b_("ref"):
  1499. raise utils.PdfReadError("xref table read error")
  1500. readNonWhitespace(stream)
  1501. stream.seek(-1, 1)
  1502. firsttime = True; # check if the first time looking at the xref table
  1503. while True:
  1504. num = readObject(stream, self)
  1505. if firsttime and num != 0:
  1506. self.xrefIndex = num
  1507. warnings.warn("Xref table not zero-indexed. ID numbers for objects will %sbe corrected." % \
  1508. ("" if not self.strict else "not "), utils.PdfReadWarning)
  1509. #if table not zero indexed, could be due to error from when PDF was created
  1510. #which will lead to mismatched indices later on
  1511. firsttime = False
  1512. readNonWhitespace(stream)
  1513. stream.seek(-1, 1)
  1514. size = readObject(stream, self)
  1515. readNonWhitespace(stream)
  1516. stream.seek(-1, 1)
  1517. cnt = 0
  1518. while cnt < size:
  1519. line = stream.read(20)
  1520. # It's very clear in section 3.4.3 of the PDF spec
  1521. # that all cross-reference table lines are a fixed
  1522. # 20 bytes (as of PDF 1.7). However, some files have
  1523. # 21-byte entries (or more) due to the use of \r\n
  1524. # (CRLF) EOL's. Detect that case, and adjust the line
  1525. # until it does not begin with a \r (CR) or \n (LF).
  1526. while line[0] in b_("\x0D\x0A"):
  1527. stream.seek(-20 + 1, 1)
  1528. line = stream.read(20)
  1529. # On the other hand, some malformed PDF files
  1530. # use a single character EOL without a preceeding
  1531. # space. Detect that case, and seek the stream
  1532. # back one character. (0-9 means we've bled into
  1533. # the next xref entry, t means we've bled into the
  1534. # text "trailer"):
  1535. if line[-1] in b_("0123456789t"):
  1536. stream.seek(-1, 1)
  1537. offset, generation = line[:16].split(b_(" "))
  1538. offset, generation = int(offset), int(generation)
  1539. if generation not in self.xref:
  1540. self.xref[generation] = {}
  1541. if num in self.xref[generation]:
  1542. # It really seems like we should allow the last
  1543. # xref table in the file to override previous
  1544. # ones. Since we read the file backwards, assume
  1545. # any existing key is already set correctly.
  1546. pass
  1547. else:
  1548. self.xref[generation][num] = offset
  1549. cnt += 1
  1550. num += 1
  1551. readNonWhitespace(stream)
  1552. stream.seek(-1, 1)
  1553. trailertag = stream.read(7)
  1554. if trailertag != b_("trailer"):
  1555. # more xrefs!
  1556. stream.seek(-7, 1)
  1557. else:
  1558. break
  1559. readNonWhitespace(stream)
  1560. stream.seek(-1, 1)
  1561. newTrailer = readObject(stream, self)
  1562. for key, value in list(newTrailer.items()):
  1563. if key not in self.trailer:
  1564. self.trailer[key] = value
  1565. if "/Prev" in newTrailer:
  1566. startxref = newTrailer["/Prev"]
  1567. else:
  1568. break
  1569. elif x.isdigit():
  1570. # PDF 1.5+ Cross-Reference Stream
  1571. stream.seek(-1, 1)
  1572. idnum, generation = self.readObjectHeader(stream)
  1573. xrefstream = readObject(stream, self)
  1574. assert xrefstream["/Type"] == "/XRef"
  1575. self.cacheIndirectObject(generation, idnum, xrefstream)
  1576. streamData = BytesIO(b_(xrefstream.getData()))
  1577. # Index pairs specify the subsections in the dictionary. If
  1578. # none create one subsection that spans everything.
  1579. idx_pairs = xrefstream.get("/Index", [0, xrefstream.get("/Size")])
  1580. if debug: print(("read idx_pairs=%s"%list(self._pairs(idx_pairs))))
  1581. entrySizes = xrefstream.get("/W")
  1582. assert len(entrySizes) >= 3
  1583. if self.strict and len(entrySizes) > 3:
  1584. raise utils.PdfReadError("Too many entry sizes: %s" %entrySizes)
  1585. def getEntry(i):
  1586. # Reads the correct number of bytes for each entry. See the
  1587. # discussion of the W parameter in PDF spec table 17.
  1588. if entrySizes[i] > 0:
  1589. d = streamData.read(entrySizes[i])
  1590. return convertToInt(d, entrySizes[i])
  1591. # PDF Spec Table 17: A value of zero for an element in the
  1592. # W array indicates...the default value shall be used
  1593. if i == 0: return 1 # First value defaults to 1
  1594. else: return 0
  1595. def used_before(num, generation):
  1596. # We move backwards through the xrefs, don't replace any.
  1597. return num in self.xref.get(generation, []) or \
  1598. num in self.xref_objStm
  1599. # Iterate through each subsection
  1600. last_end = 0
  1601. for start, size in self._pairs(idx_pairs):
  1602. # The subsections must increase
  1603. assert start >= last_end
  1604. last_end = start + size
  1605. for num in range(start, start+size):
  1606. # The first entry is the type
  1607. xref_type = getEntry(0)
  1608. # The rest of the elements depend on the xref_type
  1609. if xref_type == 0:
  1610. # linked list of free objects
  1611. next_free_object = getEntry(1)
  1612. next_generation = getEntry(2)
  1613. elif xref_type == 1:
  1614. # objects that are in use but are not compressed
  1615. byte_offset = getEntry(1)
  1616. generation = getEntry(2)
  1617. if generation not in self.xref:
  1618. self.xref[generation] = {}
  1619. if not used_before(num, generation):
  1620. self.xref[generation][num] = byte_offset
  1621. if debug: print(("XREF Uncompressed: %s %s"%(
  1622. num, generation)))
  1623. elif xref_type == 2:
  1624. # compressed objects
  1625. objstr_num = getEntry(1)
  1626. obstr_idx = getEntry(2)
  1627. generation = 0 # PDF spec table 18, generation is 0
  1628. if not used_before(num, generation):
  1629. if debug: print(("XREF Compressed: %s %s %s"%(
  1630. num, objstr_num, obstr_idx)))
  1631. self.xref_objStm[num] = (objstr_num, obstr_idx)
  1632. elif self.strict:
  1633. raise utils.PdfReadError("Unknown xref type: %s"%
  1634. xref_type)
  1635. trailerKeys = "/Root", "/Encrypt", "/Info", "/ID"
  1636. for key in trailerKeys:
  1637. if key in xrefstream and key not in self.trailer:
  1638. self.trailer[NameObject(key)] = xrefstream.raw_get(key)
  1639. if "/Prev" in xrefstream:
  1640. startxref = xrefstream["/Prev"]
  1641. else:
  1642. break
  1643. else:
  1644. # bad xref character at startxref. Let's see if we can find
  1645. # the xref table nearby, as we've observed this error with an
  1646. # off-by-one before.
  1647. stream.seek(-11, 1)
  1648. tmp = stream.read(20)
  1649. xref_loc = tmp.find(b_("xref"))
  1650. if xref_loc != -1:
  1651. startxref -= (10 - xref_loc)
  1652. continue
  1653. # No explicit xref table, try finding a cross-reference stream.
  1654. stream.seek(startxref, 0)
  1655. found = False
  1656. for look in range(5):
  1657. if stream.read(1).isdigit():
  1658. # This is not a standard PDF, consider adding a warning
  1659. startxref += look
  1660. found = True
  1661. break
  1662. if found:
  1663. continue
  1664. # no xref table found at specified location
  1665. raise utils.PdfReadError("Could not find xref table at specified location")
  1666. #if not zero-indexed, verify that the table is correct; change it if necessary
  1667. if self.xrefIndex and not self.strict:
  1668. loc = stream.tell()
  1669. for gen in self.xref:
  1670. if gen == 65535: continue
  1671. for id in self.xref[gen]:
  1672. stream.seek(self.xref[gen][id], 0)
  1673. try:
  1674. pid, pgen = self.readObjectHeader(stream)
  1675. except ValueError:
  1676. break
  1677. if pid == id - self.xrefIndex:
  1678. self._zeroXref(gen)
  1679. break
  1680. #if not, then either it's just plain wrong, or the non-zero-index is actually correct
  1681. stream.seek(loc, 0) #return to where it was
  1682. def _zeroXref(self, generation):
  1683. self.xref[generation] = dict( (k-self.xrefIndex, v) for (k, v) in list(self.xref[generation].items()) )
  1684. def _pairs(self, array):
  1685. i = 0
  1686. while True:
  1687. yield array[i], array[i+1]
  1688. i += 2
  1689. if (i+1) >= len(array):
  1690. break
  1691. def readNextEndLine(self, stream):
  1692. debug = False
  1693. if debug: print(">>readNextEndLine")
  1694. line = b_("")
  1695. while True:
  1696. # Prevent infinite loops in malformed PDFs
  1697. if stream.tell() == 0:
  1698. raise utils.PdfReadError("Could not read malformed PDF file")
  1699. x = stream.read(1)
  1700. if debug: print((" x:", x, "%x"%ord(x)))
  1701. if stream.tell() < 2:
  1702. raise utils.PdfReadError("EOL marker not found")
  1703. stream.seek(-2, 1)
  1704. if x == b_('\n') or x == b_('\r'): ## \n = LF; \r = CR
  1705. crlf = False
  1706. while x == b_('\n') or x == b_('\r'):
  1707. if debug:
  1708. if ord(x) == 0x0D: print(" x is CR 0D")
  1709. elif ord(x) == 0x0A: print(" x is LF 0A")
  1710. x = stream.read(1)
  1711. if x == b_('\n') or x == b_('\r'): # account for CR+LF
  1712. stream.seek(-1, 1)
  1713. crlf = True
  1714. if stream.tell() < 2:
  1715. raise utils.PdfReadError("EOL marker not found")
  1716. stream.seek(-2, 1)
  1717. stream.seek(2 if crlf else 1, 1) #if using CR+LF, go back 2 bytes, else 1
  1718. break
  1719. else:
  1720. if debug: print(" x is neither")
  1721. line = x + line
  1722. if debug: print((" RNEL line:", line))
  1723. if debug: print("leaving RNEL")
  1724. return line
  1725. def decrypt(self, password):
  1726. """
  1727. When using an encrypted / secured PDF file with the PDF Standard
  1728. encryption handler, this function will allow the file to be decrypted.
  1729. It checks the given password against the document's user password and
  1730. owner password, and then stores the resulting decryption key if either
  1731. password is correct.
  1732. It does not matter which password was matched. Both passwords provide
  1733. the correct decryption key that will allow the document to be used with
  1734. this library.
  1735. :param str password: The password to match.
  1736. :return: ``0`` if the password failed, ``1`` if the password matched the user
  1737. password, and ``2`` if the password matched the owner password.
  1738. :rtype: int
  1739. :raises NotImplementedError: if document uses an unsupported encryption
  1740. method.
  1741. """
  1742. self._override_encryption = True
  1743. try:
  1744. return self._decrypt(password)
  1745. finally:
  1746. self._override_encryption = False
  1747. def _decrypt(self, password):
  1748. encrypt = self.trailer['/Encrypt'].getObject()
  1749. if encrypt['/Filter'] != '/Standard':
  1750. raise NotImplementedError("only Standard PDF encryption handler is available")
  1751. if not (encrypt['/V'] in (1, 2)):
  1752. raise NotImplementedError("only algorithm code 1 and 2 are supported")
  1753. user_password, key = self._authenticateUserPassword(password)
  1754. if user_password:
  1755. self._decryption_key = key
  1756. return 1
  1757. else:
  1758. rev = encrypt['/R'].getObject()
  1759. if rev == 2:
  1760. keylen = 5
  1761. else:
  1762. keylen = encrypt['/Length'].getObject() // 8
  1763. key = _alg33_1(password, rev, keylen)
  1764. real_O = encrypt["/O"].getObject()
  1765. if rev == 2:
  1766. userpass = utils.RC4_encrypt(key, real_O)
  1767. else:
  1768. val = real_O
  1769. for i in range(19, -1, -1):
  1770. new_key = b_('')
  1771. for l in range(len(key)):
  1772. new_key += b_(chr(utils.ord_(key[l]) ^ i))
  1773. val = utils.RC4_encrypt(new_key, val)
  1774. userpass = val
  1775. owner_password, key = self._authenticateUserPassword(userpass)
  1776. if owner_password:
  1777. self._decryption_key = key
  1778. return 2
  1779. return 0
  1780. def _authenticateUserPassword(self, password):
  1781. encrypt = self.trailer['/Encrypt'].getObject()
  1782. rev = encrypt['/R'].getObject()
  1783. owner_entry = encrypt['/O'].getObject()
  1784. p_entry = encrypt['/P'].getObject()
  1785. id_entry = self.trailer['/ID'].getObject()
  1786. id1_entry = id_entry[0].getObject()
  1787. real_U = encrypt['/U'].getObject().original_bytes
  1788. if rev == 2:
  1789. U, key = _alg34(password, owner_entry, p_entry, id1_entry)
  1790. elif rev >= 3:
  1791. U, key = _alg35(password, rev,
  1792. encrypt["/Length"].getObject() // 8, owner_entry,
  1793. p_entry, id1_entry,
  1794. encrypt.get("/EncryptMetadata", BooleanObject(False)).getObject())
  1795. U, real_U = U[:16], real_U[:16]
  1796. return U == real_U, key
  1797. def getIsEncrypted(self):
  1798. return "/Encrypt" in self.trailer
  1799. isEncrypted = property(lambda self: self.getIsEncrypted(), None, None)
  1800. """
  1801. Read-only boolean property showing whether this PDF file is encrypted.
  1802. Note that this property, if true, will remain true even after the
  1803. :meth:`decrypt()<PdfFileReader.decrypt>` method is called.
  1804. """
  1805. # returns a tuple indicating if the file has an owner and a user password, and the permissions
  1806. def getPermissions(self) :
  1807. if "/Encrypt" in self.trailer :
  1808. encrypt = self.trailer['/Encrypt'].getObject()
  1809. return (encrypt['/O'].getObject(),
  1810. encrypt['/U'].getObject(),
  1811. encrypt['/P'].getObject())
  1812. def getRectangle(self, name, defaults):
  1813. retval = self.get(name)
  1814. if isinstance(retval, RectangleObject):
  1815. return retval
  1816. if retval == None:
  1817. for d in defaults:
  1818. retval = self.get(d)
  1819. if retval != None:
  1820. break
  1821. if isinstance(retval, IndirectObject):
  1822. retval = self.pdf.getObject(retval)
  1823. retval = RectangleObject(retval)
  1824. setRectangle(self, name, retval)
  1825. return retval
  1826. def setRectangle(self, name, value):
  1827. if not isinstance(name, NameObject):
  1828. name = NameObject(name)
  1829. self[name] = value
  1830. def deleteRectangle(self, name):
  1831. del self[name]
  1832. def createRectangleAccessor(name, fallback):
  1833. return \
  1834. property(
  1835. lambda self: getRectangle(self, name, fallback),
  1836. lambda self, value: setRectangle(self, name, value),
  1837. lambda self: deleteRectangle(self, name)
  1838. )
  1839. class PageObject(DictionaryObject):
  1840. """
  1841. This class represents a single page within a PDF file. Typically this
  1842. object will be created by accessing the
  1843. :meth:`getPage()<PyPDF2.PdfFileReader.getPage>` method of the
  1844. :class:`PdfFileReader<PyPDF2.PdfFileReader>` class, but it is
  1845. also possible to create an empty page with the
  1846. :meth:`createBlankPage()<PageObject.createBlankPage>` static method.
  1847. :param pdf: PDF file the page belongs to.
  1848. :param indirectRef: Stores the original indirect reference to
  1849. this object in its source PDF
  1850. """
  1851. def __init__(self, pdf=None, indirectRef=None):
  1852. DictionaryObject.__init__(self)
  1853. self.pdf = pdf
  1854. self.indirectRef = indirectRef
  1855. def createBlankPage(pdf=None, width=None, height=None):
  1856. """
  1857. Returns a new blank page.
  1858. If ``width`` or ``height`` is ``None``, try to get the page size
  1859. from the last page of *pdf*.
  1860. :param pdf: PDF file the page belongs to
  1861. :param float width: The width of the new page expressed in default user
  1862. space units.
  1863. :param float height: The height of the new page expressed in default user
  1864. space units.
  1865. :return: the new blank page:
  1866. :rtype: :class:`PageObject<PageObject>`
  1867. :raises PageSizeNotDefinedError: if ``pdf`` is ``None`` or contains
  1868. no page
  1869. """
  1870. page = PageObject(pdf)
  1871. # Creates a new page (cf PDF Reference 7.7.3.3)
  1872. page.__setitem__(NameObject('/Type'), NameObject('/Page'))
  1873. page.__setitem__(NameObject('/Parent'), NullObject())
  1874. page.__setitem__(NameObject('/Resources'), DictionaryObject())
  1875. if width is None or height is None:
  1876. if pdf is not None and pdf.getNumPages() > 0:
  1877. lastpage = pdf.getPage(pdf.getNumPages() - 1)
  1878. width = lastpage.mediaBox.getWidth()
  1879. height = lastpage.mediaBox.getHeight()
  1880. else:
  1881. raise utils.PageSizeNotDefinedError()
  1882. page.__setitem__(NameObject('/MediaBox'),
  1883. RectangleObject([0, 0, width, height]))
  1884. return page
  1885. createBlankPage = staticmethod(createBlankPage)
  1886. def rotateClockwise(self, angle):
  1887. """
  1888. Rotates a page clockwise by increments of 90 degrees.
  1889. :param int angle: Angle to rotate the page. Must be an increment
  1890. of 90 deg.
  1891. """
  1892. assert angle % 90 == 0
  1893. self._rotate(angle)
  1894. return self
  1895. def rotateCounterClockwise(self, angle):
  1896. """
  1897. Rotates a page counter-clockwise by increments of 90 degrees.
  1898. :param int angle: Angle to rotate the page. Must be an increment
  1899. of 90 deg.
  1900. """
  1901. assert angle % 90 == 0
  1902. self._rotate(-angle)
  1903. return self
  1904. def _rotate(self, angle):
  1905. currentAngle = self.get("/Rotate", 0)
  1906. self[NameObject("/Rotate")] = NumberObject(currentAngle + angle)
  1907. def _mergeResources(res1, res2, resource):
  1908. newRes = DictionaryObject()
  1909. newRes.update(res1.get(resource, DictionaryObject()).getObject())
  1910. page2Res = res2.get(resource, DictionaryObject()).getObject()
  1911. renameRes = {}
  1912. for key in list(page2Res.keys()):
  1913. if key in newRes and newRes.raw_get(key) != page2Res.raw_get(key):
  1914. newname = NameObject(key + str(uuid.uuid4()))
  1915. renameRes[key] = newname
  1916. newRes[newname] = page2Res[key]
  1917. elif key not in newRes:
  1918. newRes[key] = page2Res.raw_get(key)
  1919. return newRes, renameRes
  1920. _mergeResources = staticmethod(_mergeResources)
  1921. def _contentStreamRename(stream, rename, pdf):
  1922. if not rename:
  1923. return stream
  1924. stream = ContentStream(stream, pdf)
  1925. for operands, operator in stream.operations:
  1926. for i in range(len(operands)):
  1927. op = operands[i]
  1928. if isinstance(op, NameObject):
  1929. operands[i] = rename.get(op,op)
  1930. return stream
  1931. _contentStreamRename = staticmethod(_contentStreamRename)
  1932. def _pushPopGS(contents, pdf):
  1933. # adds a graphics state "push" and "pop" to the beginning and end
  1934. # of a content stream. This isolates it from changes such as
  1935. # transformation matricies.
  1936. stream = ContentStream(contents, pdf)
  1937. stream.operations.insert(0, [[], "q"])
  1938. stream.operations.append([[], "Q"])
  1939. return stream
  1940. _pushPopGS = staticmethod(_pushPopGS)
  1941. def _addCode(contents, pdf, code, endCode = ""):
  1942. stream = ContentStream(contents, pdf)
  1943. stream.operations.insert(0, [[], code])
  1944. stream.operations.append([[], endCode])
  1945. return stream
  1946. _addCode = staticmethod(_addCode)
  1947. def _addTransformationMatrix(contents, pdf, ctm):
  1948. # adds transformation matrix at the beginning of the given
  1949. # contents stream.
  1950. a, b, c, d, e, f = ctm
  1951. contents = ContentStream(contents, pdf)
  1952. contents.operations.insert(0, [[FloatObject(a), FloatObject(b),
  1953. FloatObject(c), FloatObject(d), FloatObject(e),
  1954. FloatObject(f)], " cm"])
  1955. return contents
  1956. _addTransformationMatrix = staticmethod(_addTransformationMatrix)
  1957. def getContents(self):
  1958. """
  1959. Accesses the page contents.
  1960. :return: the ``/Contents`` object, or ``None`` if it doesn't exist.
  1961. ``/Contents`` is optional, as described in PDF Reference 7.7.3.3
  1962. """
  1963. if "/Contents" in self:
  1964. return self["/Contents"].getObject()
  1965. else:
  1966. return None
  1967. def mergePage(self, page2):
  1968. """
  1969. Merges the content streams of two pages into one. Resource references
  1970. (i.e. fonts) are maintained from both pages. The mediabox/cropbox/etc
  1971. of this page are not altered. The parameter page's content stream will
  1972. be added to the end of this page's content stream, meaning that it will
  1973. be drawn after, or "on top" of this page.
  1974. :param PageObject page2: The page to be merged into this one. Should be
  1975. an instance of :class:`PageObject<PageObject>`.
  1976. """
  1977. self._mergePage(page2)
  1978. def _mergePage(self, page2, page2transformation=None, ctm=None, expand=False):
  1979. # First we work on merging the resource dictionaries. This allows us
  1980. # to find out what symbols in the content streams we might need to
  1981. # rename.
  1982. newResources = DictionaryObject()
  1983. rename = {}
  1984. originalResources = self["/Resources"].getObject()
  1985. page2Resources = page2["/Resources"].getObject()
  1986. newAnnots = ArrayObject()
  1987. for page in (self, page2):
  1988. if "/Annots" in page:
  1989. annots = page["/Annots"]
  1990. if isinstance(annots, ArrayObject):
  1991. for ref in annots:
  1992. newAnnots.append(ref)
  1993. for res in "/ExtGState", "/Font", "/XObject", "/ColorSpace", "/Pattern", "/Shading", "/Properties":
  1994. new, newrename = PageObject._mergeResources(originalResources, page2Resources, res)
  1995. if new:
  1996. newResources[NameObject(res)] = new
  1997. rename.update(newrename)
  1998. # Combine /ProcSet sets.
  1999. newResources[NameObject("/ProcSet")] = ArrayObject(
  2000. frozenset(originalResources.get("/ProcSet", ArrayObject()).getObject()).union(
  2001. frozenset(page2Resources.get("/ProcSet", ArrayObject()).getObject())
  2002. )
  2003. )
  2004. newContentArray = ArrayObject()
  2005. originalContent = self.getContents()
  2006. if originalContent is not None:
  2007. newContentArray.append(PageObject._pushPopGS(
  2008. originalContent, self.pdf))
  2009. page2Content = page2.getContents()
  2010. if page2Content is not None:
  2011. if page2transformation is not None:
  2012. page2Content = page2transformation(page2Content)
  2013. page2Content = PageObject._contentStreamRename(
  2014. page2Content, rename, self.pdf)
  2015. page2Content = PageObject._pushPopGS(page2Content, self.pdf)
  2016. newContentArray.append(page2Content)
  2017. # if expanding the page to fit a new page, calculate the new media box size
  2018. if expand:
  2019. corners1 = [self.mediaBox.getLowerLeft_x().as_numeric(), self.mediaBox.getLowerLeft_y().as_numeric(),
  2020. self.mediaBox.getUpperRight_x().as_numeric(), self.mediaBox.getUpperRight_y().as_numeric()]
  2021. corners2 = [page2.mediaBox.getLowerLeft_x().as_numeric(), page2.mediaBox.getLowerLeft_y().as_numeric(),
  2022. page2.mediaBox.getUpperLeft_x().as_numeric(), page2.mediaBox.getUpperLeft_y().as_numeric(),
  2023. page2.mediaBox.getUpperRight_x().as_numeric(), page2.mediaBox.getUpperRight_y().as_numeric(),
  2024. page2.mediaBox.getLowerRight_x().as_numeric(), page2.mediaBox.getLowerRight_y().as_numeric()]
  2025. if ctm is not None:
  2026. ctm = [float(x) for x in ctm]
  2027. new_x = [ctm[0]*corners2[i] + ctm[2]*corners2[i+1] + ctm[4] for i in range(0, 8, 2)]
  2028. new_y = [ctm[1]*corners2[i] + ctm[3]*corners2[i+1] + ctm[5] for i in range(0, 8, 2)]
  2029. else:
  2030. new_x = corners2[0:8:2]
  2031. new_y = corners2[1:8:2]
  2032. lowerleft = [min(new_x), min(new_y)]
  2033. upperright = [max(new_x), max(new_y)]
  2034. lowerleft = [min(corners1[0], lowerleft[0]), min(corners1[1], lowerleft[1])]
  2035. upperright = [max(corners1[2], upperright[0]), max(corners1[3], upperright[1])]
  2036. self.mediaBox.setLowerLeft(lowerleft)
  2037. self.mediaBox.setUpperRight(upperright)
  2038. self[NameObject('/Contents')] = ContentStream(newContentArray, self.pdf)
  2039. self[NameObject('/Resources')] = newResources
  2040. self[NameObject('/Annots')] = newAnnots
  2041. # Variant of the mergePage function.
  2042. # Merges the content streams of several pages and code strings into one page.
  2043. # Resource references (i.e. fonts) are maintained from all pages.
  2044. # The parameter ar_data is an array containing code strings and PageObjects.
  2045. # ContentStream is called only if necessary because it calls ParseContentStream
  2046. # which is slox. Otherwise the Content is directly extracted and added to the code.
  2047. def mergePage3(self, ar_data ):
  2048. newResources = DictionaryObject()
  2049. rename = {}
  2050. originalResources = self["/Resources"].getObject()
  2051. code_s = b""
  2052. if isinstance(ar_data, PageObject) :
  2053. ar_data = [ar_data]
  2054. for data in ar_data :
  2055. # modified by Dysmas, march 2017
  2056. if sys.version[0:1] == "2" : # when used in python3, this code raises the error : unicode is not defined
  2057. if isinstance(data, unicode) :
  2058. data = data.encode("utf8")
  2059. elif isinstance(data, str) :
  2060. data = bytes(data, "utf-8")
  2061. if isinstance(data, PageObject) :
  2062. # Now we work on merging the resource dictionaries. This allows us
  2063. # to find out what symbols in the content streams we might need to
  2064. # rename.
  2065. pagexResources = data["/Resources"].getObject()
  2066. for res in "/ExtGState", "/Font", "/XObject", "/ColorSpace", "/Pattern", "/Shading":
  2067. new, newrename = PageObject._mergeResources(originalResources, pagexResources, res)
  2068. if new:
  2069. newResources[NameObject(res)] = new
  2070. rename.update(newrename)
  2071. # Combine /Resources sets.
  2072. originalResources.update(newResources)
  2073. # Combine /ProcSet sets.
  2074. newResources[NameObject("/ProcSet")] = ArrayObject(
  2075. frozenset(originalResources.get("/ProcSet", ArrayObject()).getObject()).union(
  2076. frozenset(pagexResources.get("/ProcSet", ArrayObject()).getObject())
  2077. )
  2078. )
  2079. if len(rename) > 0 :
  2080. pagexContent = data['/Contents'].getObject()
  2081. pagexContent = PageObject._contentStreamRename(pagexContent, rename, self.pdf)
  2082. code_s += bytes(pagexContent.getData()) + b"\n"
  2083. else :
  2084. page_keys = data.keys()
  2085. if "/Contents" in page_keys : # if page is not blank
  2086. data1 = bytes(self.extractContent(data["/Contents"]))
  2087. code_s += data1 + b"\n"
  2088. else :
  2089. code_s += data + b"\n"
  2090. originalContent = self["/Contents"].getObject()
  2091. outputContent = PageObject._addCode(originalContent, self.pdf, code_s)
  2092. self[NameObject('/Contents')] = outputContent
  2093. self[NameObject('/Resources')] = originalResources
  2094. def extractContent(self,data) :
  2095. code_s = b""
  2096. pageContent = data.getObject()
  2097. if isinstance(pageContent, ArrayObject) :
  2098. for data2 in pageContent :
  2099. code_s += self.extractContent(data2)
  2100. else :
  2101. if isinstance(data, TextStringObject) :
  2102. code_s += data
  2103. else :
  2104. try :
  2105. decodedData = filters.decodeStreamData(pageContent)
  2106. code_s += decodedData
  2107. except :
  2108. print ("le code n'a pas pu etre extrait")
  2109. return code_s
  2110. def mergeModifiedPage(self, page2, code, endCode = ""):
  2111. self._mergePage(page2, lambda page2Content:
  2112. PageObject._addCode(page2Content, page2.pdf, code, endCode), code)
  2113. def mergeTransformedPage(self, page2, ctm, expand=False):
  2114. """
  2115. This is similar to mergePage, but a transformation matrix is
  2116. applied to the merged stream.
  2117. :param PageObject page2: The page to be merged into this one. Should be
  2118. an instance of :class:`PageObject<PageObject>`.
  2119. :param tuple ctm: a 6-element tuple containing the operands of the
  2120. transformation matrix
  2121. :param bool expand: Whether the page should be expanded to fit the dimensions
  2122. of the page to be merged.
  2123. """
  2124. self._mergePage(page2, lambda page2Content:
  2125. PageObject._addTransformationMatrix(page2Content, page2.pdf, ctm), ctm, expand)
  2126. def mergeScaledPage(self, page2, scale, expand=False):
  2127. """
  2128. This is similar to mergePage, but the stream to be merged is scaled
  2129. by appling a transformation matrix.
  2130. :param PageObject page2: The page to be merged into this one. Should be
  2131. an instance of :class:`PageObject<PageObject>`.
  2132. :param float scale: The scaling factor
  2133. :param bool expand: Whether the page should be expanded to fit the
  2134. dimensions of the page to be merged.
  2135. """
  2136. # CTM to scale : [ sx 0 0 sy 0 0 ]
  2137. return self.mergeTransformedPage(page2, [scale, 0,
  2138. 0, scale,
  2139. 0, 0], expand)
  2140. def mergeRotatedPage(self, page2, rotation, expand=False):
  2141. """
  2142. This is similar to mergePage, but the stream to be merged is rotated
  2143. by appling a transformation matrix.
  2144. :param PageObject page2: the page to be merged into this one. Should be
  2145. an instance of :class:`PageObject<PageObject>`.
  2146. :param float rotation: The angle of the rotation, in degrees
  2147. :param bool expand: Whether the page should be expanded to fit the
  2148. dimensions of the page to be merged.
  2149. """
  2150. rotation = math.radians(rotation)
  2151. return self.mergeTransformedPage(page2,
  2152. [math.cos(rotation), math.sin(rotation),
  2153. -math.sin(rotation), math.cos(rotation),
  2154. 0, 0], expand)
  2155. def mergeTranslatedPage(self, page2, tx, ty, expand=False):
  2156. """
  2157. This is similar to mergePage, but the stream to be merged is translated
  2158. by appling a transformation matrix.
  2159. :param PageObject page2: the page to be merged into this one. Should be
  2160. an instance of :class:`PageObject<PageObject>`.
  2161. :param float tx: The translation on X axis
  2162. :param float ty: The translation on Y axis
  2163. :param bool expand: Whether the page should be expanded to fit the
  2164. dimensions of the page to be merged.
  2165. """
  2166. return self.mergeTransformedPage(page2, [1, 0,
  2167. 0, 1,
  2168. tx, ty], expand)
  2169. def mergeRotatedTranslatedPage(self, page2, rotation, tx, ty, expand=False):
  2170. """
  2171. This is similar to mergePage, but the stream to be merged is rotated
  2172. and translated by appling a transformation matrix.
  2173. :param PageObject page2: the page to be merged into this one. Should be
  2174. an instance of :class:`PageObject<PageObject>`.
  2175. :param float tx: The translation on X axis
  2176. :param float ty: The translation on Y axis
  2177. :param float rotation: The angle of the rotation, in degrees
  2178. :param bool expand: Whether the page should be expanded to fit the
  2179. dimensions of the page to be merged.
  2180. """
  2181. translation = [[1, 0, 0],
  2182. [0, 1, 0],
  2183. [-tx, -ty, 1]]
  2184. rotation = math.radians(rotation)
  2185. rotating = [[math.cos(rotation), math.sin(rotation), 0],
  2186. [-math.sin(rotation), math.cos(rotation), 0],
  2187. [0, 0, 1]]
  2188. rtranslation = [[1, 0, 0],
  2189. [0, 1, 0],
  2190. [tx, ty, 1]]
  2191. ctm = utils.matrixMultiply(translation, rotating)
  2192. ctm = utils.matrixMultiply(ctm, rtranslation)
  2193. return self.mergeTransformedPage(page2, [ctm[0][0], ctm[0][1],
  2194. ctm[1][0], ctm[1][1],
  2195. ctm[2][0], ctm[2][1]], expand)
  2196. def mergeRotatedScaledPage(self, page2, rotation, scale, expand=False):
  2197. """
  2198. This is similar to mergePage, but the stream to be merged is rotated
  2199. and scaled by appling a transformation matrix.
  2200. :param PageObject page2: the page to be merged into this one. Should be
  2201. an instance of :class:`PageObject<PageObject>`.
  2202. :param float rotation: The angle of the rotation, in degrees
  2203. :param float scale: The scaling factor
  2204. :param bool expand: Whether the page should be expanded to fit the
  2205. dimensions of the page to be merged.
  2206. """
  2207. rotation = math.radians(rotation)
  2208. rotating = [[math.cos(rotation), math.sin(rotation), 0],
  2209. [-math.sin(rotation), math.cos(rotation), 0],
  2210. [0, 0, 1]]
  2211. scaling = [[scale, 0, 0],
  2212. [0, scale, 0],
  2213. [0, 0, 1]]
  2214. ctm = utils.matrixMultiply(rotating, scaling)
  2215. return self.mergeTransformedPage(page2,
  2216. [ctm[0][0], ctm[0][1],
  2217. ctm[1][0], ctm[1][1],
  2218. ctm[2][0], ctm[2][1]], expand)
  2219. def mergeScaledTranslatedPage(self, page2, scale, tx, ty, expand=False):
  2220. """
  2221. This is similar to mergePage, but the stream to be merged is translated
  2222. and scaled by appling a transformation matrix.
  2223. :param PageObject page2: the page to be merged into this one. Should be
  2224. an instance of :class:`PageObject<PageObject>`.
  2225. :param float scale: The scaling factor
  2226. :param float tx: The translation on X axis
  2227. :param float ty: The translation on Y axis
  2228. :param bool expand: Whether the page should be expanded to fit the
  2229. dimensions of the page to be merged.
  2230. """
  2231. translation = [[1, 0, 0],
  2232. [0, 1, 0],
  2233. [tx, ty, 1]]
  2234. scaling = [[scale, 0, 0],
  2235. [0, scale, 0],
  2236. [0, 0, 1]]
  2237. ctm = utils.matrixMultiply(scaling, translation)
  2238. return self.mergeTransformedPage(page2, [ctm[0][0], ctm[0][1],
  2239. ctm[1][0], ctm[1][1],
  2240. ctm[2][0], ctm[2][1]], expand)
  2241. def mergeRotatedScaledTranslatedPage(self, page2, rotation, scale, tx, ty, expand=False):
  2242. """
  2243. This is similar to mergePage, but the stream to be merged is translated,
  2244. rotated and scaled by appling a transformation matrix.
  2245. :param PageObject page2: the page to be merged into this one. Should be
  2246. an instance of :class:`PageObject<PageObject>`.
  2247. :param float tx: The translation on X axis
  2248. :param float ty: The translation on Y axis
  2249. :param float rotation: The angle of the rotation, in degrees
  2250. :param float scale: The scaling factor
  2251. :param bool expand: Whether the page should be expanded to fit the
  2252. dimensions of the page to be merged.
  2253. """
  2254. translation = [[1, 0, 0],
  2255. [0, 1, 0],
  2256. [tx, ty, 1]]
  2257. rotation = math.radians(rotation)
  2258. rotating = [[math.cos(rotation), math.sin(rotation), 0],
  2259. [-math.sin(rotation), math.cos(rotation), 0],
  2260. [0, 0, 1]]
  2261. scaling = [[scale, 0, 0],
  2262. [0, scale, 0],
  2263. [0, 0, 1]]
  2264. ctm = utils.matrixMultiply(rotating, scaling)
  2265. ctm = utils.matrixMultiply(ctm, translation)
  2266. return self.mergeTransformedPage(page2, [ctm[0][0], ctm[0][1],
  2267. ctm[1][0], ctm[1][1],
  2268. ctm[2][0], ctm[2][1]], expand)
  2269. ##
  2270. # Applys a transformation matrix the page.
  2271. #
  2272. # @param ctm A 6 elements tuple containing the operands of the
  2273. # transformation matrix
  2274. def addTransformation(self, ctm):
  2275. """
  2276. Applies a transformation matrix to the page.
  2277. :param tuple ctm: A 6-element tuple containing the operands of the
  2278. transformation matrix.
  2279. """
  2280. originalContent = self.getContents()
  2281. if originalContent is not None:
  2282. newContent = PageObject._addTransformationMatrix(
  2283. originalContent, self.pdf, ctm)
  2284. newContent = PageObject._pushPopGS(newContent, self.pdf)
  2285. self[NameObject('/Contents')] = newContent
  2286. def scale(self, sx, sy):
  2287. """
  2288. Scales a page by the given factors by appling a transformation
  2289. matrix to its content and updating the page size.
  2290. :param float sx: The scaling factor on horizontal axis.
  2291. :param float sy: The scaling factor on vertical axis.
  2292. """
  2293. self.addTransformation([sx, 0,
  2294. 0, sy,
  2295. 0, 0])
  2296. self.mediaBox = RectangleObject([
  2297. float(self.mediaBox.getLowerLeft_x()) * sx,
  2298. float(self.mediaBox.getLowerLeft_y()) * sy,
  2299. float(self.mediaBox.getUpperRight_x()) * sx,
  2300. float(self.mediaBox.getUpperRight_y()) * sy])
  2301. if "/VP" in self:
  2302. viewport = self["/VP"]
  2303. if isinstance(viewport, ArrayObject):
  2304. bbox = viewport[0]["/BBox"]
  2305. else:
  2306. bbox = viewport["/BBox"]
  2307. scaled_bbox = RectangleObject([
  2308. float(bbox[0]) * sx,
  2309. float(bbox[1]) * sy,
  2310. float(bbox[2]) * sx,
  2311. float(bbox[3]) * sy])
  2312. if isinstance(viewport, ArrayObject):
  2313. self[NameObject("/VP")][NumberObject(0)][NameObject("/BBox")] = scaled_bbox
  2314. else:
  2315. self[NameObject("/VP")][NameObject("/BBox")] = scaled_bbox
  2316. def scaleBy(self, factor):
  2317. """
  2318. Scales a page by the given factor by appling a transformation
  2319. matrix to its content and updating the page size.
  2320. :param float factor: The scaling factor (for both X and Y axis).
  2321. """
  2322. self.scale(factor, factor)
  2323. def scaleTo(self, width, height):
  2324. """
  2325. Scales a page to the specified dimentions by appling a
  2326. transformation matrix to its content and updating the page size.
  2327. :param float width: The new width.
  2328. :param float height: The new heigth.
  2329. """
  2330. sx = width / float(self.mediaBox.getUpperRight_x() -
  2331. self.mediaBox.getLowerLeft_x ())
  2332. sy = height / float(self.mediaBox.getUpperRight_y() -
  2333. self.mediaBox.getLowerLeft_y ())
  2334. self.scale(sx, sy)
  2335. def compressContentStreams(self):
  2336. """
  2337. Compresses the size of this page by joining all content streams and
  2338. applying a FlateDecode filter.
  2339. However, it is possible that this function will perform no action if
  2340. content stream compression becomes "automatic" for some reason.
  2341. """
  2342. content = self.getContents()
  2343. if content is not None:
  2344. if not isinstance(content, ContentStream):
  2345. content = ContentStream(content, self.pdf)
  2346. self[NameObject("/Contents")] = content.flateEncode()
  2347. def extractText(self):
  2348. """
  2349. Locate all text drawing commands, in the order they are provided in the
  2350. content stream, and extract the text. This works well for some PDF
  2351. files, but poorly for others, depending on the generator used. This will
  2352. be refined in the future. Do not rely on the order of text coming out of
  2353. this function, as it will change if this function is made more
  2354. sophisticated.
  2355. :return: a unicode string object.
  2356. """
  2357. text = u_("")
  2358. content = self["/Contents"].getObject()
  2359. if not isinstance(content, ContentStream):
  2360. content = ContentStream(content, self.pdf)
  2361. # Note: we check all strings are TextStringObjects. ByteStringObjects
  2362. # are strings where the byte->string encoding was unknown, so adding
  2363. # them to the text here would be gibberish.
  2364. for operands, operator in content.operations:
  2365. if operator == b_("Tj"):
  2366. _text = operands[0]
  2367. if isinstance(_text, TextStringObject):
  2368. text += _text
  2369. elif operator == b_("T*"):
  2370. text += "\n"
  2371. elif operator == b_("'"):
  2372. text += "\n"
  2373. _text = operands[0]
  2374. if isinstance(_text, TextStringObject):
  2375. text += operands[0]
  2376. elif operator == b_('"'):
  2377. _text = operands[2]
  2378. if isinstance(_text, TextStringObject):
  2379. text += "\n"
  2380. text += _text
  2381. elif operator == b_("TJ"):
  2382. for i in operands[0]:
  2383. if isinstance(i, TextStringObject):
  2384. text += i
  2385. text += "\n"
  2386. return text
  2387. mediaBox = createRectangleAccessor("/MediaBox", ())
  2388. """
  2389. A :class:`RectangleObject<PyPDF2.generic.RectangleObject>`, expressed in default user space units,
  2390. defining the boundaries of the physical medium on which the page is
  2391. intended to be displayed or printed.
  2392. """
  2393. cropBox = createRectangleAccessor("/CropBox", ("/MediaBox",))
  2394. """
  2395. A :class:`RectangleObject<PyPDF2.generic.RectangleObject>`, expressed in default user space units,
  2396. defining the visible region of default user space. When the page is
  2397. displayed or printed, its contents are to be clipped (cropped) to this
  2398. rectangle and then imposed on the output medium in some
  2399. implementation-defined manner. Default value: same as :attr:`mediaBox<mediaBox>`.
  2400. """
  2401. bleedBox = createRectangleAccessor("/BleedBox", ("/CropBox", "/MediaBox"))
  2402. """
  2403. A :class:`RectangleObject<PyPDF2.generic.RectangleObject>`, expressed in default user space units,
  2404. defining the region to which the contents of the page should be clipped
  2405. when output in a production enviroment.
  2406. """
  2407. trimBox = createRectangleAccessor("/TrimBox", ("/CropBox", "/MediaBox"))
  2408. """
  2409. A :class:`RectangleObject<PyPDF2.generic.RectangleObject>`, expressed in default user space units,
  2410. defining the intended dimensions of the finished page after trimming.
  2411. """
  2412. artBox = createRectangleAccessor("/ArtBox", ("/CropBox", "/MediaBox"))
  2413. """
  2414. A :class:`RectangleObject<PyPDF2.generic.RectangleObject>`, expressed in default user space units,
  2415. defining the extent of the page's meaningful content as intended by the
  2416. page's creator.
  2417. """
  2418. class ContentStream(DecodedStreamObject):
  2419. def __init__(self, stream, pdf):
  2420. self.pdf = pdf
  2421. self.operations = []
  2422. # stream may be a StreamObject or an ArrayObject containing
  2423. # multiple StreamObjects to be cat'd together.
  2424. stream = stream.getObject()
  2425. if isinstance(stream, ArrayObject):
  2426. data = b_("")
  2427. for s in stream:
  2428. data += s.getObject().getData()
  2429. stream = BytesIO(b_(data))
  2430. else:
  2431. stream = BytesIO(b_(stream.getData()))
  2432. self.__parseContentStream(stream)
  2433. def __parseContentStream(self, stream):
  2434. # file("f:\\tmp.txt", "w").write(stream.read())
  2435. stream.seek(0, 0)
  2436. operands = []
  2437. while True:
  2438. peek = readNonWhitespace(stream)
  2439. if peek == b_('') or ord_(peek) == 0:
  2440. break
  2441. stream.seek(-1, 1)
  2442. if peek.isalpha() or peek == b_("'") or peek == b_('"'):
  2443. operator = utils.readUntilRegex(stream,
  2444. NameObject.delimiterPattern, True)
  2445. if operator == b_("BI"):
  2446. # begin inline image - a completely different parsing
  2447. # mechanism is required, of course... thanks buddy...
  2448. assert operands == []
  2449. ii = self._readInlineImage(stream)
  2450. self.operations.append((ii, b_("INLINE IMAGE")))
  2451. else:
  2452. self.operations.append((operands, operator))
  2453. operands = []
  2454. elif peek == b_('%'):
  2455. # If we encounter a comment in the content stream, we have to
  2456. # handle it here. Typically, readObject will handle
  2457. # encountering a comment -- but readObject assumes that
  2458. # following the comment must be the object we're trying to
  2459. # read. In this case, it could be an operator instead.
  2460. while peek not in (b_('\r'), b_('\n')):
  2461. peek = stream.read(1)
  2462. else:
  2463. operands.append(readObject(stream, None))
  2464. def _readInlineImage(self, stream):
  2465. # begin reading just after the "BI" - begin image
  2466. # first read the dictionary of settings.
  2467. settings = DictionaryObject()
  2468. while True:
  2469. tok = readNonWhitespace(stream)
  2470. stream.seek(-1, 1)
  2471. if tok == b_("I"):
  2472. # "ID" - begin of image data
  2473. break
  2474. key = readObject(stream, self.pdf)
  2475. tok = readNonWhitespace(stream)
  2476. stream.seek(-1, 1)
  2477. value = readObject(stream, self.pdf)
  2478. settings[key] = value
  2479. # left at beginning of ID
  2480. tmp = stream.read(3)
  2481. assert tmp[:2] == b_("ID")
  2482. data = b_("")
  2483. while True:
  2484. # Read the inline image, while checking for EI (End Image) operator.
  2485. tok = stream.read(1)
  2486. if tok == b_("E"):
  2487. # Check for End Image
  2488. tok2 = stream.read(1)
  2489. if tok2 == b_("I"):
  2490. # Sometimes that data will contain EI, so check for the Q operator.
  2491. tok3 = stream.read(1)
  2492. info = tok + tok2
  2493. while tok3 in utils.WHITESPACES:
  2494. info += tok3
  2495. tok3 = stream.read(1)
  2496. if tok3 == b_("Q"):
  2497. stream.seek(-1, 1)
  2498. break
  2499. else:
  2500. stream.seek(-1,1)
  2501. data += info
  2502. else:
  2503. stream.seek(-1, 1)
  2504. data += tok
  2505. else:
  2506. data += tok
  2507. return {"settings": settings, "data": data}
  2508. def _getData(self):
  2509. newdata = BytesIO()
  2510. for operands, operator in self.operations:
  2511. if operator == "INLINE IMAGE":
  2512. newdata.write("BI")
  2513. dicttext = StringIO()
  2514. operands["settings"].writeToStream(dicttext, None)
  2515. newdata.write(dicttext.getvalue()[2:-2])
  2516. newdata.write("ID ")
  2517. newdata.write(operands["data"])
  2518. newdata.write("EI")
  2519. else:
  2520. for op in operands:
  2521. op.writeToStream(newdata, None)
  2522. newdata.write(b_(" "))
  2523. newdata.write(b_(operator))
  2524. newdata.write(b_("\n"))
  2525. return newdata.getvalue()
  2526. def _setData(self, value):
  2527. self.__parseContentStream(BytesIO(b_(value)))
  2528. _data = property(_getData, _setData)
  2529. class DocumentInformation(DictionaryObject):
  2530. """
  2531. A class representing the basic document metadata provided in a PDF File.
  2532. This class is accessible through
  2533. :meth:`getDocumentInfo()<PyPDF2.PdfFileReader.getDocumentInfo()>`
  2534. All text properties of the document metadata have
  2535. *two* properties, eg. author and author_raw. The non-raw property will
  2536. always return a ``TextStringObject``, making it ideal for a case where
  2537. the metadata is being displayed. The raw property can sometimes return
  2538. a ``ByteStringObject``, if PyPDF2 was unable to decode the string's
  2539. text encoding; this requires additional safety in the caller and
  2540. therefore is not as commonly accessed.
  2541. """
  2542. def __init__(self):
  2543. DictionaryObject.__init__(self)
  2544. def getText(self, key):
  2545. retval = self.get(key, None)
  2546. if isinstance(retval, TextStringObject):
  2547. return retval
  2548. return None
  2549. title = property(lambda self: self.getText("/Title"))
  2550. """Read-only property accessing the document's **title**.
  2551. Returns a unicode string (``TextStringObject``) or ``None``
  2552. if the title is not specified."""
  2553. title_raw = property(lambda self: self.get("/Title"))
  2554. """The "raw" version of title; can return a ``ByteStringObject``."""
  2555. author = property(lambda self: self.getText("/Author"))
  2556. """Read-only property accessing the document's **author**.
  2557. Returns a unicode string (``TextStringObject``) or ``None``
  2558. if the author is not specified."""
  2559. author_raw = property(lambda self: self.get("/Author"))
  2560. """The "raw" version of author; can return a ``ByteStringObject``."""
  2561. subject = property(lambda self: self.getText("/Subject"))
  2562. """Read-only property accessing the document's **subject**.
  2563. Returns a unicode string (``TextStringObject``) or ``None``
  2564. if the subject is not specified."""
  2565. subject_raw = property(lambda self: self.get("/Subject"))
  2566. """The "raw" version of subject; can return a ``ByteStringObject``."""
  2567. creator = property(lambda self: self.getText("/Creator"))
  2568. """Read-only property accessing the document's **creator**. If the
  2569. document was converted to PDF from another format, this is the name of the
  2570. application (e.g. OpenOffice) that created the original document from
  2571. which it was converted. Returns a unicode string (``TextStringObject``)
  2572. or ``None`` if the creator is not specified."""
  2573. creator_raw = property(lambda self: self.get("/Creator"))
  2574. """The "raw" version of creator; can return a ``ByteStringObject``."""
  2575. producer = property(lambda self: self.getText("/Producer"))
  2576. """Read-only property accessing the document's **producer**.
  2577. If the document was converted to PDF from another format, this is
  2578. the name of the application (for example, OSX Quartz) that converted
  2579. it to PDF. Returns a unicode string (``TextStringObject``)
  2580. or ``None`` if the producer is not specified."""
  2581. producer_raw = property(lambda self: self.get("/Producer"))
  2582. """The "raw" version of producer; can return a ``ByteStringObject``."""
  2583. def convertToInt(d, size):
  2584. if size > 8:
  2585. raise utils.PdfReadError("invalid size in convertToInt")
  2586. d = b_("\x00\x00\x00\x00\x00\x00\x00\x00") + b_(d)
  2587. d = d[-8:]
  2588. return struct.unpack(">q", d)[0]
  2589. # ref: pdf1.8 spec section 3.5.2 algorithm 3.2
  2590. _encryption_padding = b_('\x28\xbf\x4e\x5e\x4e\x75\x8a\x41\x64\x00\x4e\x56') + \
  2591. b_('\xff\xfa\x01\x08\x2e\x2e\x00\xb6\xd0\x68\x3e\x80\x2f\x0c') + \
  2592. b_('\xa9\xfe\x64\x53\x69\x7a')
  2593. # Implementation of algorithm 3.2 of the PDF standard security handler,
  2594. # section 3.5.2 of the PDF 1.6 reference.
  2595. def _alg32(password, rev, keylen, owner_entry, p_entry, id1_entry, metadata_encrypt=True):
  2596. # 1. Pad or truncate the password string to exactly 32 bytes. If the
  2597. # password string is more than 32 bytes long, use only its first 32 bytes;
  2598. # if it is less than 32 bytes long, pad it by appending the required number
  2599. # of additional bytes from the beginning of the padding string
  2600. # (_encryption_padding).
  2601. password = b_((str_(password) + str_(_encryption_padding))[:32])
  2602. # 2. Initialize the MD5 hash function and pass the result of step 1 as
  2603. # input to this function.
  2604. import struct
  2605. m = md5(password)
  2606. # 3. Pass the value of the encryption dictionary's /O entry to the MD5 hash
  2607. # function.
  2608. m.update(owner_entry.original_bytes)
  2609. # 4. Treat the value of the /P entry as an unsigned 4-byte integer and pass
  2610. # these bytes to the MD5 hash function, low-order byte first.
  2611. p_entry = struct.pack('<i', p_entry)
  2612. m.update(p_entry)
  2613. # 5. Pass the first element of the file's file identifier array to the MD5
  2614. # hash function.
  2615. m.update(id1_entry.original_bytes)
  2616. # 6. (Revision 3 or greater) If document metadata is not being encrypted,
  2617. # pass 4 bytes with the value 0xFFFFFFFF to the MD5 hash function.
  2618. if rev >= 3 and not metadata_encrypt:
  2619. m.update(b_("\xff\xff\xff\xff"))
  2620. # 7. Finish the hash.
  2621. md5_hash = m.digest()
  2622. # 8. (Revision 3 or greater) Do the following 50 times: Take the output
  2623. # from the previous MD5 hash and pass the first n bytes of the output as
  2624. # input into a new MD5 hash, where n is the number of bytes of the
  2625. # encryption key as defined by the value of the encryption dictionary's
  2626. # /Length entry.
  2627. if rev >= 3:
  2628. for i in range(50):
  2629. md5_hash = md5(md5_hash[:keylen]).digest()
  2630. # 9. Set the encryption key to the first n bytes of the output from the
  2631. # final MD5 hash, where n is always 5 for revision 2 but, for revision 3 or
  2632. # greater, depends on the value of the encryption dictionary's /Length
  2633. # entry.
  2634. return md5_hash[:keylen]
  2635. # Implementation of algorithm 3.3 of the PDF standard security handler,
  2636. # section 3.5.2 of the PDF 1.6 reference.
  2637. def _alg33(owner_pwd, user_pwd, rev, keylen):
  2638. # steps 1 - 4
  2639. key = _alg33_1(owner_pwd, rev, keylen)
  2640. # 5. Pad or truncate the user password string as described in step 1 of
  2641. # algorithm 3.2.
  2642. user_pwd = b_((user_pwd + str_(_encryption_padding))[:32])
  2643. # 6. Encrypt the result of step 5, using an RC4 encryption function with
  2644. # the encryption key obtained in step 4.
  2645. val = utils.RC4_encrypt(key, user_pwd)
  2646. # 7. (Revision 3 or greater) Do the following 19 times: Take the output
  2647. # from the previous invocation of the RC4 function and pass it as input to
  2648. # a new invocation of the function; use an encryption key generated by
  2649. # taking each byte of the encryption key obtained in step 4 and performing
  2650. # an XOR operation between that byte and the single-byte value of the
  2651. # iteration counter (from 1 to 19).
  2652. if rev >= 3:
  2653. for i in range(1, 20):
  2654. new_key = ''
  2655. for l in range(len(key)):
  2656. new_key += chr(ord_(key[l]) ^ i)
  2657. val = utils.RC4_encrypt(new_key, val)
  2658. # 8. Store the output from the final invocation of the RC4 as the value of
  2659. # the /O entry in the encryption dictionary.
  2660. return val
  2661. # Steps 1-4 of algorithm 3.3
  2662. def _alg33_1(password, rev, keylen):
  2663. # 1. Pad or truncate the owner password string as described in step 1 of
  2664. # algorithm 3.2. If there is no owner password, use the user password
  2665. # instead.
  2666. password = b_((password + str_(_encryption_padding))[:32])
  2667. # 2. Initialize the MD5 hash function and pass the result of step 1 as
  2668. # input to this function.
  2669. m = md5(password)
  2670. # 3. (Revision 3 or greater) Do the following 50 times: Take the output
  2671. # from the previous MD5 hash and pass it as input into a new MD5 hash.
  2672. md5_hash = m.digest()
  2673. if rev >= 3:
  2674. for i in range(50):
  2675. md5_hash = md5(md5_hash).digest()
  2676. # 4. Create an RC4 encryption key using the first n bytes of the output
  2677. # from the final MD5 hash, where n is always 5 for revision 2 but, for
  2678. # revision 3 or greater, depends on the value of the encryption
  2679. # dictionary's /Length entry.
  2680. key = md5_hash[:keylen]
  2681. return key
  2682. # Implementation of algorithm 3.4 of the PDF standard security handler,
  2683. # section 3.5.2 of the PDF 1.6 reference.
  2684. def _alg34(password, owner_entry, p_entry, id1_entry):
  2685. # 1. Create an encryption key based on the user password string, as
  2686. # described in algorithm 3.2.
  2687. key = _alg32(password, 2, 5, owner_entry, p_entry, id1_entry)
  2688. # 2. Encrypt the 32-byte padding string shown in step 1 of algorithm 3.2,
  2689. # using an RC4 encryption function with the encryption key from the
  2690. # preceding step.
  2691. U = utils.RC4_encrypt(key, _encryption_padding)
  2692. # 3. Store the result of step 2 as the value of the /U entry in the
  2693. # encryption dictionary.
  2694. return U, key
  2695. # Implementation of algorithm 3.4 of the PDF standard security handler,
  2696. # section 3.5.2 of the PDF 1.6 reference.
  2697. def _alg35(password, rev, keylen, owner_entry, p_entry, id1_entry, metadata_encrypt):
  2698. # 1. Create an encryption key based on the user password string, as
  2699. # described in Algorithm 3.2.
  2700. key = _alg32(password, rev, keylen, owner_entry, p_entry, id1_entry)
  2701. # 2. Initialize the MD5 hash function and pass the 32-byte padding string
  2702. # shown in step 1 of Algorithm 3.2 as input to this function.
  2703. m = md5()
  2704. m.update(_encryption_padding)
  2705. # 3. Pass the first element of the file's file identifier array (the value
  2706. # of the ID entry in the document's trailer dictionary; see Table 3.13 on
  2707. # page 73) to the hash function and finish the hash. (See implementation
  2708. # note 25 in Appendix H.)
  2709. m.update(id1_entry.original_bytes)
  2710. md5_hash = m.digest()
  2711. # 4. Encrypt the 16-byte result of the hash, using an RC4 encryption
  2712. # function with the encryption key from step 1.
  2713. val = utils.RC4_encrypt(key, md5_hash)
  2714. # 5. Do the following 19 times: Take the output from the previous
  2715. # invocation of the RC4 function and pass it as input to a new invocation
  2716. # of the function; use an encryption key generated by taking each byte of
  2717. # the original encryption key (obtained in step 2) and performing an XOR
  2718. # operation between that byte and the single-byte value of the iteration
  2719. # counter (from 1 to 19).
  2720. for i in range(1, 20):
  2721. new_key = b_('')
  2722. for l in range(len(key)):
  2723. new_key += b_(chr(ord_(key[l]) ^ i))
  2724. val = utils.RC4_encrypt(new_key, val)
  2725. # 6. Append 16 bytes of arbitrary padding to the output from the final
  2726. # invocation of the RC4 function and store the 32-byte result as the value
  2727. # of the U entry in the encryption dictionary.
  2728. # (implementator note: I don't know what "arbitrary padding" is supposed to
  2729. # mean, so I have used null bytes. This seems to match a few other
  2730. # people's implementations)
  2731. return val + (b_('\x00') * 16), key