pdf.py 126 KB

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