U
    d                    @   s  d Z dZdZdZdZddlZddlZddlZddlZddl	Z	ddlm
Z
 e
dk r^dd	lmZ ndd	lmZ e
dk rxeZndd
lmZ ddlmZ ddlmZ ddlZddlZddlT ddlmZmZmZ ddlmZmZmZmZmZmZmZ e
dk rddlm Z! e
dk rddl"m"Z" nddl#m"Z" ddl	Z	G dd de$Z%G dd de$Z&dd Z'dd Z(dd Z)dd  Z*G d!d" d"e+Z,G d#d$ d$e-Z.G d%d& d&e+Z/d'd( Z0ed)ed* ed+ Z1d7d-d.Z2d/d0 Z3d1d2 Z4d3d4 Z5d5d6 Z6dS )8z
A pure-Python PDF library with an increasing number of capabilities.
See README for links to FAQ, documentation, homepage, etc.
zMathieu Fenniakzbiziqe@mathieu.fenniak.netzPhaseit, Inc.zPyPDF3@phaseit.net    N)version_info)   r   )StringIO)BytesIO   )filters)utils)*)readNonWhitespacereadUntilWhitespaceConvertFunctionsToVirtualList)isStringb_u_ord_chr_str_formatWarning)      )ImmutableSet)r      )md5c                   @   s  e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zd_ddZ	dd Z
dd Zd`ddZdaddZdd Zdd ZdbddZdd Zd d! Zdcd"d#Zddd&d'Zded)d*Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zdfd5d6Zdgd7d8Zdhd:d;Zd<d= Zd>d? Zd@dA Z didBdCZ!djdDdEZ"dkdFdGZ#dldHdIZ$dJdKdLdMdNdOdPgZ%dQdR Z&dSdT Z'e(e&e'Z)dUdVdWdXdYdZgZ*d[d\ Z+d]d^ Z,e(e+e,Z-dS )mPdfFileWriterz
    This class supports writing PDF files out, given pages produced by another
    class (typically :class:`PdfFileReader<PdfFileReader>`).
    c                 C   s   t d| _g | _t }|tdtdtdtdtdt i | || _	t }|tdt
tjtdd	 i | || _t }|tdtd
td| j	i d | _|| _d S )Nz%PDF-1.3/Type/Pages/Countr   /Kids	/ProducerZPyPDF3zutf-16bez/Catalog)r   _header_objectsDictionaryObjectupdate
NameObjectNumberObjectArrayObject
_addObject_pagescreateStringObjectcodecsBOM_UTF16_BEr   encode_info_root_root_object)selfpagesinforoot r3   ./tmp/pip-unpacked-wheel-eeeohlmn/PyPDF3/pdf.py__init__V   s6    
      zPdfFileWriter.__init__c                 C   s   | j | tt| j d| S )Nr   )r    appendIndirectObjectlen)r/   objr3   r3   r4   r&   s   s    zPdfFileWriter._addObjectc                 C   s"   |j | krtd| j|jd  S )Nzpdf must be selfr   )pdf
ValueErrorr    idnum)r/   Zidor3   r3   r4   	getObjectw   s    
zPdfFileWriter.getObjectc                 C   s^   |d dkst | j|td< | |}| | j}||d | t|d d |td< d S )Nr   /Page/Parentr   r   r   )AssertionErrorr'   r#   r&   r=   r$   )r/   pageactionr0   r3   r3   r4   _addPage|   s    
zPdfFileWriter._addPagec                 C   s   |  |tj dS )a  
        Adds a page to this PDF file.  The page is usually acquired from a
        :class:`PdfFileReader<PdfFileReader>` instance.

        :param PageObject page: The page to add to the document. Should be
            an instance of :class:`PageObject<PyPDF3.pdf.PageObject>`
        N)rC   listr6   )r/   rA   r3   r3   r4   addPage   s    zPdfFileWriter.addPager   c                    s   |  | fdd dS )ao  
        Insert a page in this PDF file. The page is usually acquired from a
        :class:`PdfFileReader<PdfFileReader>` instance.

        :param PageObject page: The page to add to the document.  This
            argument should be an instance of :class:`PageObject<pdf.PageObject>`.
        :param int index: Position at which the page will be inserted.
        c                    s   |   |S N)insert)lpindexr3   r4   <lambda>       z*PdfFileWriter.insertPage.<locals>.<lambda>N)rC   )r/   rA   rK   r3   rJ   r4   
insertPage   s    	zPdfFileWriter.insertPagec                 C   s   |  | j}|d |   S )a  
        Retrieves a page by number from this PDF file.

        :param int pageNumber: The page number to retrieve
            (pages begin at zero)
        :return: the page at the index given by *pageNumber*
        :rtype: :class:`PageObject<pdf.PageObject>`
        r   r=   r'   )r/   
pageNumberr0   r3   r3   r4   getPage   s    	zPdfFileWriter.getPagec                 C   s   |  | j}t|td S )zC
        :return: the number of pages.
        :rtype: int
        r   )r=   r'   intr#   )r/   r0   r3   r3   r4   getNumPages   s    zPdfFileWriter.getNumPagesNc                 C   s   t | ||}| | |S )a@  
        Appends a blank page to this PDF file and returns it. If no page size
        is specified, use the size of the last page.

        :param float width: The width of the new page expressed in default user
            space units.
        :param float height: The height of the new page expressed in default
            user space units.
        :return: the newly appended page
        :rtype: :class:`PageObject<PyPDF3.pdf.PageObject>`
        :raises PageSizeNotDefinedError: if width and height are not defined
            and previous page does not exist.
        )
PageObjectcreateBlankPagerE   )r/   widthheightrA   r3   r3   r4   addBlankPage   s    
zPdfFileWriter.addBlankPagec                 C   s\   |dks |dkr>|   d |kr>| |}|j }|j }t| ||}| || |S )at  
        Inserts a blank page to this PDF file and returns it. If no page size
        is specified, use the size of the last page.

        :param float width: The width of the new page expressed in default user
            space units.
        :param float height: The height of the new page expressed in default
            user space units.
        :param int index: Position to add the page.
        :return: the newly appended page
        :rtype: :class:`PageObject<PyPDF3.pdf.PageObject>`
        :raises PageSizeNotDefinedError: if width and height are not defined
            and previous page does not exist.
        Nr   )rS   rQ   mediaBoxgetWidth	getHeightrT   rU   rN   )r/   rV   rW   rK   ZoldpagerA   r3   r3   r4   insertBlankPage   s    


zPdfFileWriter.insertBlankPagec              
   C   s   t  }|tdtdtdtdtdtd| i | |}tt }t  }|tdt tdtt||gii | | | j	td|td|i d	S )
a  
        Add Javascript which will launch upon opening this PDF.

        :param str javascript: Your Javascript.

        >>> output.addJS("this.print({bUI:true,bSilent:false,bShrinkToFit:true});")
        # Example: This will launch the print window when the PDF is opened.
        r   z/Action/Sz/JavaScriptz/JSz(%s)/Namesz/OpenActionN)
r!   r"   r#   r&   struuiduuid4r%   r(   r.   )r/   Z
javascriptZjsZjs_indirect_objectZjs_string_nameZjs_name_treer3   r3   r4   addJS   s4    	   

  
  zPdfFileWriter.addJSc                 C   s   t  }|| |tdtdi t }|td|i t }|tdtdtdt|td|i t }|tdtt||gi t }|td|i | jtd|i dS )	a  
        Embed a file inside the PDF.

        :param str fname: The filename to display.
        :param str fdata: The data in the file.

        Reference:
        https://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/PDF32000_2008.pdf
        Section 7.11.3
        r   z/EmbeddedFile/Fz	/Filespecz/EFr^   z/EmbeddedFilesN)DecodedStreamObjectZsetDatar"   r#   r!   r(   r%   r.   )r/   fnamefdataZ
file_entryZefEntryZfilespecZembeddedFilesNamesDictionaryZembeddedFilesDictionaryr3   r3   r4   addAttachment   s>    
       zPdfFileWriter.addAttachmentc                 C   sV   |  }|   }td|D ]6}||}| | | || }t|r|| qdS )aX  
        Copy pages from reader to writer. Includes an optional callback parameter
        which is invoked after pages are appended to the writer.

        :param reader: a PdfFileReader object from which to copy page
            annotations to this writer object.  The writer's annots
        will then be updated
        :callback after_page_append (function): Callback function that is invoked after
            each page is appended to the writer. Callback signature:

            :param writer_pageref (PDF page reference): Reference to the page
                appended to the writer.
        r   N)rS   rangerQ   rE   callable)r/   readerafter_page_appendZreader_num_pagesZwriter_num_pagesZrpagenumZreader_pageZwriter_pager3   r3   r4   appendPagesFromReaderI  s    

 z#PdfFileWriter.appendPagesFromReaderc                 C   s^   t dt|d D ]F}|d |  }|D ],}|d|kr*|tdt|| i q*qdS )ai  
        Update the form field values for a given page from a fields dictionary.
        Copy field texts and values from fields to page.

        :param page: Page reference from PDF writer where the annotations
            and field data will be updated.
        :param fields: a Python dictionary of field names (/T) and text
            values (/V)
        r   /Annots/T/VN)rh   r8   r=   getr"   r#   TextStringObject)r/   rA   fieldsjZwriter_annotfieldr3   r3   r4   updatePageFormFieldValuesc  s     
z'PdfFileWriter.updatePageFormFieldValuesc                 C   s   |j d | _dS )z
        Copy the reader document root to the writer.

        :param reader:  PdfFileReader from the document root should be copied.
        :callback after_page_append
        /RootN)trailerr.   )r/   rj   r3   r3   r4   cloneReaderDocumentRootv  s    z%PdfFileWriter.cloneReaderDocumentRootc                 C   s   |  | | || dS )a2  
        Create a copy (clone) of a document from a PDF file reader

        :param reader: PDF file reader instance from which the clone
            should be created.
        :callback after_page_append (function): Callback function that is invoked after
            each page is appended to the writer. Signature includes a reference to the
            appended page (delegates to appendPagesFromReader). Callback signature:

            :param writer_pageref (PDF page reference): Reference to the page just
                appended to the document.
        N)rx   rl   )r/   rj   rk   r3   r3   r4   cloneDocumentFromReader  s    
z%PdfFileWriter.cloneDocumentFromReaderTFc                 C   s  dd }ddl }ddl}	|dkr$|}|r:d}
d}td}nd}
d}td	}||||}tt||||}tttt|   }tttt|	  }t	||f| _
|dkrt||||\}}n$|dkstt||||||d
\}}t }td|td< t|
|td< |
dkr2t|d |td< t||td< t||td< t||td< t||td< | || _|| _dS )a  
        Encrypt this PDF file with the PDF Standard encryption handler.

        :param str user_pwd: The "user password", which allows for opening
            and reading the PDF file with the restrictions provided.
        :param str owner_pwd: The "owner password", which allows for
            opening the PDF files without any restrictions.  By default,
            the owner password is the same as the user password.
        :param bool use_128bit: flag as to whether to use 128bit
            encryption.  When false, 40bit encryption will be used.  By default,
            this flag is on.
        :param bool allow_printing: flag as to whether to restrict
            permissions to allow printing.  By default, this flag is on.
        :param bool allow_commenting: flag as to whether to restrict
            permissions to allow commenting.  By default, this flag is on.
        :param int overwrite_permission: Manually set value of PDF document's
            /P flag
        c                 S   sH   |d k	rt |tkrt|S | r(|s(dS | r4|r4dS | s@|r@dS dS d S )Nii$ir   )typerR   )ZprintingZ
commentingZ
permissionr3   r3   r4   set_permissions  s    z.PdfFileWriter.encrypt.<locals>.set_permissionsr   Nr   r   g      0@r   g      @F	/Standard/Filterro      /Length/R/O/U/P)timerandomrR   ByteStringObject_alg33r   r   reprdigestr%   _ID_alg34r@   _alg35r!   r#   r$   r&   _encrypt_encrypt_key)r/   user_pwd	owner_pwdZ
use_128bitZallow_printingZallow_commentingZoverwrite_permissionr{   r   r   VrevkeylenPOZID_1ZID_2Ukeyencryptr3   r3   r4   r     s>    

zPdfFileWriter.encrypttqdmc                 C   s  t |dr$d|jkr$td|j  d}ddl}| jsD| | j| _i }t	t
| jD ]~}| j| }t|trV|jdkrV|j}	|	j|kri ||	j< |	j||	j kri ||	j |	j< t|d d| ||	j |	j |	j< qVg | _|rtd|d	| jf | || j | `g }
|| jtd
  |td t
| jdkr|r|dkrdtjkrddl}t	t
| jD ]}|jd|d t
| jddds q|d }| j| }|
|  |tt|d  d}t | drj|| j jkrj|!d|d dd }|!dddd }| j"| | }t
|t
| j"d ksBt#t$|% }|dt&dt
| j"d  }|'|| |td qln`t
| jdkr|r|dkrdtjkrddl(m(} |t	t
| jdt
| jdd}nt	t
| j}|D ]}|d }| j| }|
|  |tt|d  d}t | dr|| j jkr|!d|d dd }|!dddd }| j"| | }t
|t
| j"d kst#t$|% }|dt&dt
| j"d  }|'|| |td q| }|td |td t
| jd   |td!d"  |
D ]}|td#|df  q4|td$ t) }|*t+d%t,t
| jd t+d&| jt+d'| j-i t | d(r| j.|t+d)< t | dr| j |t+d*< |'|d |td+|  dS ),z
        Writes the collection of pages added to this object out as a PDF file.

        :param stream: An object to write the file to.  The object must support
            the write method and the tell method, similar to a file object.
        modebzPFile <%s> to write to is not in binary mode. It may not be written to correctly.Fr   Nr   zERM:zroot:
u
   %âãÏÓ
   guiPySimpleGUIzEncrypting PDFhprogress)Zorientationr   z 0 obj
r   <ir   r   r      z
endobj
r   )r   Zobjects)desctotalunitzxref
z0 %s
z%010d %05d f 
)r     z%010d %05d n 
ztrailer
/Sizerv   /Infor   /ID/Encryptz
startxref
%s
%%%%EOF
)/hasattrr   warningswarnnamestructr-   r&   r.   rh   r8   r    
isinstancerT   indirectRefr:   
generationr7   r<   stackprint_sweepIndirectReferenceswriter   r   sysmodulesr   ZOneLineProgressMeterr6   tellr_   r   packr   r@   r   r   minwriteToStreamr   r!   r"   r#   r$   r,   r   )r/   streamZprogress_bar_enabledprogress_bardebugr   ZexternalReferenceMapZobjIndexr9   dataZobject_positionsr   ir<   r   pack1pack2md5_hashr   ZloopZxref_locationoffsetrw   r3   r3   r4   r     s    



$ ,
,"
   zPdfFileWriter.writec                 C   s@   i }t | D ]\}}t||t|< q| | j| dS )z
        Add custom metadata to the output.

        :param dict infos: a Python dictionary where each key is a field
            and each value is your new metadata.
        N)rD   itemsr(   r#   r=   r,   r"   )r/   Zinfosargsr   valuer3   r3   r4   addMetadataC  s    zPdfFileWriter.addMetadatac              	   C   sF  d}|rt |d|jjf t|trjt| D ]4\}}|}| ||}t|tr\| 	|}|||< q0|S t|t
rtt|D ]0}| ||| }t|tr| 	|}|||< q|S t|tr>|j| kr
|j| jkr|S | j|j | |}| || |S qBt|jdr8|jjjr8td|jjj||ji |ji |jd }	|	d kr8z|j|}	| jd  t| j}
t|
d| }|j|kri ||j< |j||j kri ||j |j< |||j |j |j< | ||	}	|	| j|
d < |W S  ttfk
r6   td|jj| t  Y S X |	S n|S d S )NFZTYPEr   z I/O operation on closed file: {}r   r   z8Unable to resolve [{}: {}], returning NullObject instead) r   	__class____name__r   r!   rD   r   r   StreamObjectr&   r%   rh   r8   r7   r:   r<   r   r6   r=   r   r   closedr;   formatr   rp   r   r    RecursionErrorr   r   
NullObject)r/   Z	externMapr   r   r   r   Z	origvaluer   ZrealdataZnewobjr<   Z
newobj_idor3   r3   r4   r   O  sf     








"


 z&PdfFileWriter._sweepIndirectReferencesc                 C   s0   | j |d }t|d| }| |ks,t|S )Nr   r   )r    rK   r7   r=   r@   )r/   r9   r<   refr3   r3   r4   getReference  s    zPdfFileWriter.getReferencec                 C   sn   d| j krB| j d }| j|d }t|d| }| |ksjtn(t }|i  | |}|| j t	d< |S )N	/Outlinesr   r   )
r.   r    rK   r7   r=   r@   
TreeObjectr"   r&   r#   )r/   outliner<   
outlineRefr3   r3   r4   getOutlineRoot  s    



zPdfFileWriter.getOutlineRootc                 C   s@  d| j krt| j d tr| j d }| j|d }t|d| }| |ksPtd|krt|d tr|d }| j|d }t|d| }| |kstd|kr|d }qt }||t	d< n.t }| 
|}||t	d< t }||t	d< nLt }| 
|}|| j t	d< t }| 
|}||t	d< t }||t	d< |S )Nr^   r   r   /Dests)r.   r   r!   r    rK   r7   r=   r@   r%   r#   r&   )r/   namesr<   ZnamesRefZdestsZdestsRefndr3   r3   r4   getNamedDestRoot  s8    




zPdfFileWriter.getNamedDestRootc                 C   s6   |  |}|  }|d kr|}| }|||  |S rF   )r&   r   r=   addChild)r/   destparentdestRefr   r3   r3   r4   addBookmarkDestination  s    
z$PdfFileWriter.addBookmarkDestinationc           
      C   s   t  }t| D ]\}}||tt|< q|| d|krt }t|d  D ]\}}||tt|< qT| |}||td< | |}|  }	|d kr|	}|	 }|
||  |S )N/A)r   rD   r   r#   r_   r"   r!   r&   r   r=   r   )
r/   bookmarkr   ZbookmarkObjkvrB   	actionRefbookmarkRefr   r3   r3   r4   addBookmarkDict  s"    


zPdfFileWriter.addBookmarkDict/Fitc                 G   s\  |  | jd | }	t }
g }|D ](}|dk	r>|t| q"|t  q"ttd| d |	t|f| }| }|
	td|tdtdi | 
|
}|  }|dkr|}t }|	td|td	t|i |dk	r|	td
tdd |D i d}|r|d7 }|r|d7 }|r:|	tdt|i | 
|}|  }|||  |S )aG  
        Add a bookmark to this PDF file.

        :param str title: Title to use for this bookmark.
        :param int pagenum: Page number this bookmark will point to.
        :param parent: A reference to a parent bookmark to create nested
            bookmarks.
        :param tuple color: Color of the bookmark as a red, green, blue tuple
            from 0.0 to 1.0
        :param bool bold: Bookmark is bold
        :param bool italic: Bookmark is italic
        :param str fit: The fit of the destination page. See
            :meth:`addLink()<addLink>` for details.
        r   N/z	 bookmark/Dr]   /GoTor   /Titlez/Cc                 S   s   g | ]}t |qS r3   )FloatObject).0cr3   r3   r4   
<listcomp>  s     z-PdfFileWriter.addBookmark.<locals>.<listcomp>r   r   r   rc   )r=   r'   r!   r6   r$   r   Destinationr#   getDestArrayr"   r&   r   r   r(   r%   r   )r/   titlepagenumr   colorZboldZitalicfitr   pageRefrB   zoomArgsar   	destArrayr   r   r   r   r   r3   r3   r4   addBookmark  sN    "  
   
zPdfFileWriter.addBookmarkc                 C   s(   |  |}|  }||d |g |S Nr   )r&   r   extend)r/   r   r   r   r3   r3   r4   addNamedDestinationObject&  s    
z'PdfFileWriter.addNamedDestinationObjectc                 C   sn   |  | jd | }t }|tdt|tdtdgtdtdi | |}|  }|	||g |S )Nr   r   z/FitHi:  r]   r   )
r=   r'   r!   r"   r#   r%   r$   r&   r   r   )r/   r   r   r   r   r   r   r3   r3   r4   addNamedDestination.  s      
z!PdfFileWriter.addNamedDestinationc                 C   s6   |  | jd }|D ]}|  |}d|kr|d= qdS )zA
        Removes links and annotations from this output.
        r   rm   NrO   )r/   r0   rA   r   r3   r3   r4   removeLinks=  s
    
zPdfFileWriter.removeLinksc                 C   sL  |  | jd }tt|D ](}|| }|  |}|d   }t|tsTt||}g }d}|jD ]\}	}
|
tdkr|	d }|rt|tst |	d< n|
tdkr|	d }|rt|tst |	d< n||
tdkr|	d }|rt|tst |	d< nN|
td	krDtt|	d D ].}|rt|	d | tst |	d |< q|
td
krVd}|
tdkrhd}|r|
tdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtd td!td"td#td$td%fkrqb|
td&kr qb|	|	|
f qb||_|
td| qd'S )(
        Removes images from this output.

        :param bool ignoreByteStringObject: optional parameter
            to ignore ByteString Objects.
        r   	/ContentsFTjr   '"r   TJqTQcmwJrs   Mdrir   ZgsWr   sSfFnmrH   r   r   yr   BZDoshreN)r=   r'   rh   r8   r   ContentStream
operationsr   rq   r6   __setitem__r#   )r/   ignoreByteStringObjectr0   rs   rA   r   contentZ_operationsZseq_graphicsoperandsoperatortextr   r3   r3   r4   removeImagesG  sx    





2              zPdfFileWriter.removeImagesc                 C   s  |  | jd }tt|D ]}|| }|  |}|d   }t|tsTt||}|jD ]\}}|tdkr|d }	|st|	trt |d< nt|	tst|	t	rt |d< qZ|tdkr|d }	|st|	trt |d< n t|	tst|	t	rt |d< qZ|tdkr\|d }	|s8t|	trZt |d< n"t|	tsPt|	t	rt |d< qZ|tdkrZtt|d D ]f}
|st|d |
 trt |d |
< n6t|d |
 tst|d |
 t	rxt |d |
< qxqZ|
td| qd	S )
r  r   r  r  r   r  r  r   r  N)r=   r'   rh   r8   r   r  r  r   rq   r   r  r#   )r/   r  r0   rs   rA   r   r  r   r!  r"  r   r3   r3   r4   
removeText  sZ    






zPdfFileWriter.removeTextc                 C   sX  |  | jd | }|  |}|dk	rjdd |dd D }t|dkrxtdd |d D }|| ntdgd }t|rt|}nt|t	rnt	|}t
 }	|	td	td
td
t|i t
 }
|
tdtdtdtdtd|td|tdtdtdt|td|	i | |
}d|krB|d | nt|g|td< dS )a  
        Add an URI from a rectangular area to the specified page.
        This uses the basic structure of AddLink

        :param int pagenum: index of the page on which to place the URI action.
        :param int uri: string -- uri of resource to link to.
        :param rect: :class:`RectangleObject<PyPDF3.generic.RectangleObject>` or array of four
            integers specifying the clickable rectangular area
            ``[xLL, yLL, xUR, yUR]``, or string in the form ``"[ xLL yLL xUR yUR ]"``.
        :param border: if provided, an array describing border-drawing
            properties. See the PDF spec for details. No border will be
            drawn if this argument is omitted.

        REMOVED FIT/ZOOM ARG
        -John Mulligan
        r   Nc                 S   s   g | ]}t |qS r3   r#   r   r  r3   r3   r4   r     s     z(PdfFileWriter.addURI.<locals>.<listcomp>r   r   c                 S   s   g | ]}t |qS r3   r%  r&  r3   r3   r4   r     s     r   r]   z/URIr   /Annot/Subtype/Linkr   /Rectz/Hz/I/Borderr   rm   )r=   r'   r8   r%   r6   r$   r   r#   r   RectangleObjectr!   r"   rq   r&   )r/   r   urirectborderpageLinkr   	borderArrdashPatternZlnk2lnklnkRefr3   r3   r4   addURI  sR    


         	

zPdfFileWriter.addURIc                 G   s  |  | jd | }|  | jd | }|  |}	|dk	r~dd |dd D }
t|dkrtdd |d D }|
| ntdgd }
t|rt|}nt|t	rnt	|}g }|D ](}|dk	r|t| q|t
  qttd	|t|f| }| }t }|td
tdtdtdtd|td|tdt|
td|i | |}d|	krv|	d | nt|g|	td< dS )a  
        Add an internal link from a rectangular area to the specified page.

        :param int pagenum: index of the page on which to place the link.
        :param int pagedest: index of the page to which the link should go.
        :param rect: :class:`RectangleObject<PyPDF3.generic.RectangleObject>` or array of four
            integers specifying the clickable rectangular area
            ``[xLL, yLL, xUR, yUR]``, or string in the form ``"[ xLL yLL xUR yUR ]"``.
        :param border: if provided, an array describing border-drawing
            properties. See the PDF spec for details. No border will be
            drawn if this argument is omitted.
        :param str fit: Page fit or 'zoom' option (see below). Additional arguments may need
            to be supplied. Passing ``None`` will be read as a null value for that coordinate.

        Valid zoom arguments (see Table 8.2 of the PDF 1.7 reference for details):
             /Fit       No additional arguments
             /XYZ       [left] [top] [zoomFactor]
             /FitH      [top]
             /FitV      [left]
             /FitR      [left] [bottom] [right] [top]
             /FitB      No additional arguments
             /FitBH     [top]
             /FitBV     [left]
        r   Nc                 S   s   g | ]}t |qS r3   r%  r&  r3   r3   r4   r     s     z)PdfFileWriter.addLink.<locals>.<listcomp>r   r   c                 S   s   g | ]}t |qS r3   r%  r&  r3   r3   r4   r     s     r   z	/LinkNamer   r'  r(  r)  r   r*  r+  /Destrm   )r=   r'   r8   r%   r6   r$   r   r#   r   r,  r   r   r   r!   r"   r&   )r/   r   Zpagedestr.  r/  r   r   r0  ZpageDestr   r1  r2  r   r   r   r   r3  r4  r3   r3   r4   addLink  sT    


      

zPdfFileWriter.addLinkz	/NoLayoutz/SinglePagez
/OneColumnz/TwoColumnLeftz/TwoColumnRightz/TwoPageLeftz/TwoPageRightc                 C   s(   z| j d W S  tk
r"   Y dS X dS )z
        Get the page layout.
        See :meth:`setPageLayout()<PdfFileWriter.setPageLayout>` for a description of valid layouts.

        :return: Page layout currently being used.
        :rtype: str, None if not specified
        /PageLayoutNr.   KeyErrorr/   r3   r3   r4   getPageLayout9  s    zPdfFileWriter.getPageLayoutc                 C   sL   t |ts4|| jkr,tdd| j t|}| jtd|i dS )a  
        Set the page layout

        :param str layout: The page layout to be used

        Valid layouts are:
             /NoLayout        Layout explicitly not specified
             /SinglePage      Show one page at a time
             /OneColumn       Show one column at a time
             /TwoColumnLeft   Show pages in two columns, odd-numbered pages on the left
             /TwoColumnRight  Show pages in two columns, odd-numbered pages on the right
             /TwoPageLeft     Show two pages at a time, odd-numbered pages on the left
             /TwoPageRight    Show two pages at a time, odd-numbered pages on the right
        zLayout should be one of: {}, r8  N)	r   r#   _valid_layoutsr   r   r   joinr.   r"   )r/   Zlayoutr3   r3   r4   setPageLayoutF  s
    

zPdfFileWriter.setPageLayoutz/UseNonez/UseOutlinesz
/UseThumbsz/FullScreenz/UseOCz/UseAttachmentsc                 C   s(   z| j d W S  tk
r"   Y dS X dS )z
        Get the page mode.
        See :meth:`setPageMode()<PdfFileWriter.setPageMode>` for a description
        of valid modes.

        :return: Page mode currently being used.
        :rtype: str, None if not specified
        	/PageModeNr9  r;  r3   r3   r4   getPageModea  s    	zPdfFileWriter.getPageModec                 C   sL   t |ts4|| jkr,tdd| j t|}| jtd|i dS )a  
        Set the page mode.

        :param str mode: The page mode to use.

        Valid modes are:
            /UseNone         Do not show outlines or thumbnails panels
            /UseOutlines     Show outlines (aka bookmarks) panel
            /UseThumbs       Show page thumbnails panel
            /FullScreen      Fullscreen view
            /UseOC           Show Optional Content Group (OCG) panel
            /UseAttachments  Show attachments panel
        zMode should be one of: {}r=  rA  N)	r   r#   _valid_modesr   r   r   r?  r.   r"   )r/   r   r3   r3   r4   setPageModeo  s
    

zPdfFileWriter.setPageMode)r   )NN)NNr   )N)N)NTTFN)Fr   )N)N)NNFFr   )F)F)N)Nr   ).r   
__module____qualname____doc__r5   r&   r=   rC   rE   rN   rQ   rS   rX   r\   rb   rg   rl   ru   rx   ry   r   r   r   r   r   r   r   r   r   r   r   r   r  r#  r$  r5  r7  r>  r<  r@  property
pageLayoutrC  rB  rD  pageModer3   r3   r3   r4   r   P   s^   



!P
	
  
B
r<#


=

8
6
:
G

r   c                   @   s  e Zd ZdZdPddZdd Zedd	 ddZd
d Zedd	 ddZ	dd Z
edd	 ddZdd Zedd	 ddZdQddZdd Zdd Zdd Zdd ZdRddZedd	 ddZdSd d!Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zed,d	 ddZd-d. ZeeZd/d0 ZeeZdTd1d2Z d3d4 Z!d5d6 Z"d7d8 Z#d9d: Z$d;d< Z%d=d> Z&d?d@ Z'dAdB Z(dCdD Z)dEdF Z*dGdH Z+dIdJ Z,dKdL Z-dMdN Z.edOd	 ddZ/dS )UPdfFileReadera  
    Initializes a PdfFileReader object.  This operation can take some time, as
    the PDF stream's cross-reference tables are read into memory.

    :param stream: A File object or an object that supports the standard read
        and seek methods similar to a File object. Could also be a
        string representing a path to a PDF file.
    :param bool strict: Determines whether user should be warned of all
        problems and also causes some correctable problems to be fatal.
        Defaults to ``True``.
    :param warndest: Destination for logging warnings (defaults to
        ``sys.stderr``).
    :param bool overwriteWarnings: Determines whether to override Python's
        ``warnings.py`` module with a custom implementation (defaults to
        ``True``).
    TNc                 C   s   |r|d fdd}|t _|| _d | _i | _d| _d | _t|drXd|jkrXt 	dt
j t|rt|d}tt| }|  | | || _d| _d S )	Nc                 S   sB   |d krt j}z|t| |||| W n tk
r<   Y nX d S rF   )r   stderrr   r   IOError)messagecategoryfilenamelinenofileliner3   r3   r4   _showwarning  s    z,PdfFileReader.__init__.<locals>._showwarningr   r   r   zUPdfFileReader stream/file object is not in binary mode. It may not be read correctly.rbF)r   showwarningstrictflattenedPagesresolvedObjects	xrefIndex_pageId2Numr   r   r   r   PdfReadWarningr   openr   r   readcloser   _override_encryption)r/   r   rW  ZwarndestZoverwriteWarningsrT  fileobjr3   r3   r4   r5     s&    

zPdfFileReader.__init__c                 C   s,   d| j krdS | j d }t }|| |S )a  
        Retrieves the PDF file's document information dictionary, if it exists.
        Note that some PDF files use metadata streams instead of docinfo
        dictionaries, and these metadata streams will not be accessed by this
        function.

        :return: the document information of this PDF file
        :rtype: :class:`DocumentInformation<pdf.DocumentInformation>` or ``None`` if none exists.
        r   N)rw   DocumentInformationr"   )r/   r9   retvalr3   r3   r4   getDocumentInfo  s    



zPdfFileReader.getDocumentInfoc                 C   s   |   S rF   )rd  r;  r3   r3   r4   rL     rM   zPdfFileReader.<lambda>c                 C   s&   zd| _ | jd  W S d| _ X dS )az  
        Retrieves XMP (Extensible Metadata Platform) data from the PDF document
        root.

        :return: a :class:`XmpInformation<xmp.XmpInformation>`
            instance that can be used to access XMP metadata from the document.
        :rtype: :class:`XmpInformation<xmp.XmpInformation>` or
            ``None`` if no metadata was found on the document root.
        FTrv   N)r`  rw   getXmpMetadatar;  r3   r3   r4   re    s    
zPdfFileReader.getXmpMetadatac                 C   s   |   S rF   )re  r;  r3   r3   r4   rL     rM   c                 C   sv   | j rVzDz(d| _| d | jd d d W W S    tdY nX W 5 d| _X n| jdkrh|   t| jS dS )	z
        Calculates the number of pages in this PDF file.

        :return: number of pages
        :rtype: int
        :raises PdfReadError: if file is encrypted and restrictions prevent
            this action.
        FT rv   r   r   zFile has not been decryptedN)	isEncryptedr`  decryptrw   r   PdfReadErrorrX  _flattenr8   r;  r3   r3   r4   rS     s    


zPdfFileReader.getNumPagesc                 C   s   |   S rF   )rS   r;  r3   r3   r4   rL     rM   c                 C   s   | j dkr|   | j | S )a  
        Retrieves a page by number from this PDF file.

        :param int pageNumber: The page number to retrieve
            (pages begin at zero)
        :return: a :class:`PageObject<pdf.PageObject>` instance.
        :rtype: :class:`PageObject<pdf.PageObject>`
        N)rX  rj  )r/   rP   r3   r3   r4   rQ     s    
zPdfFileReader.getPagec                 C   s   |   S rF   )getNamedDestinationsr;  r3   r3   r4   rL     s    c           
   	   C   s   ddddddddd	}|d
krBi }| j d }d|kr>|d }nd
S |d
krN|S | ||| |D ] }||kr`| ||||  qq`d|kr|d }|D ]}| }	| |	||| q|S )a$  
        Extracts field data if this PDF contains interactive form fields.
        The *tree* and *retval* parameters are for recursive use.

        :param fileobj: A file object (usually a text file) to write
            a report to on all interactive form fields found.
        :return: A dictionary where each key is a field name, and each
            value is a :class:`Field<PyPDF3.generic.Field>` object. By
            default, the mapping name is used for keys.
        :rtype: dict, or ``None`` if form data could not be located.
        z
Field TypeZParentz
Field NamezAlternate Field NamezMapping NamezField FlagsValuezDefault Value)/FTr?   rn   /TU/TM/Ffro   /DVNrv   z	/AcroFormz/Fields)rw   
_checkKids_buildFieldr=   )
r/   treerc  ra  fieldAttributescatalogattrrr   r  rt   r3   r3   r4   	getFields  s6       

zPdfFileReader.getFieldsc                 C   s   |  ||| z|d }W n: tk
rT   z|d }W n tk
rN   Y Y d S X Y nX |rr| ||| |d t|||< d S )Nro  rn   r   )rr  r:  _writeFieldr   ZField)r/   rt   rc  ra  ru  r   r3   r3   r4   rs  F  s    
zPdfFileReader._buildFieldc                 C   s,   d|kr(|d D ]}|  | || qd S )Nr   )rx  r=   )r/   rt  rc  ra  kidr3   r3   r4   rr  U  s    zPdfFileReader._checkKidsc           	   	   C   s   ddddddddg}|D ]}|| }z|dkrhd	d
ddd}|| |kr| |d |||   d  np|dkrz|d d }W n  tk
r   |d d }Y nX | |d | d  n| |d t||  d  W q tk
r   Y qX qd S )Nro  rn   rm  r?   rn  rp  ro   rq  ZButtonTextZChoice	Signature)z/Btn/Txz/Chz/Sigz: r   )r   r:  r_   )	r/   ra  rt   ru  orderrw  attrNametypesr   r3   r3   r4   ry  [  s&     "zPdfFileReader._writeFieldc                    s   |    t fdd D S )zW Retrieves form fields from the document with textual data (inputs, dropdowns)
        c                 3   s:   | ]2} |  d dkr | d  |  dfV  qdS )rm  r}  rn   ro   Nrp   )r   rt   Z
formfieldsr3   r4   	<genexpr>x  s   z2PdfFileReader.getFormTextFields.<locals>.<genexpr>)rx  dictr;  r3   r  r4   getFormTextFieldss  s    zPdfFileReader.getFormTextFieldsc           
      C   s   |dkrHi }| j d }d|kr(|d }n d|krH|d }d|krH|d }|dkrT|S d|krz|d D ]}| | | qdd|kr|d }tdt|dD ]V}||  }||d   }t|trd	|kr|d	 }| ||}	|	dkr|	||< q|S )
z
        Retrieves the named destinations present in the document.

        :return: a dictionary which maps names to
            :class:`Destinations<PyPDF3.generic.Destination>`.
        :rtype: dict
        Nrv   r   r^   r   r   r   r   r   )rw   rk  r=   rh   r8   r   r!   _buildDestination)
r/   rt  rc  rv  r   rz  r   r   valr   r3   r3   r4   rk  }  s2    


z"PdfFileReader.getNamedDestinationsc                 C   s   |   S rF   )getOutlinesr;  r3   r3   r4   rL     rM   c                 C   s   |dkr`g }| j d }d|krVz|d }W n tjk
rD   | Y S X d|krV|d }|  | _|dkrl|S | |}|r|| d|krg }| |d | |r|| d|krq|d }ql|S )z
        Retrieves the document outline present in the document.

        :return: a nested list of :class:`Destinations<PyPDF3.generic.Destination>`.
        Nrv   r   /Firstz/Next)rw   r   ri  rk  _namedDests_buildOutliner6   r  )r/   nodeoutlinesrv  linesr   ZsubOutlinesr3   r3   r4   r    s2    






zPdfFileReader.getOutlinesc                 C   s\   | j dkr4i }t| jD ]\}}|||jj< q|| _ t|trD|}n|j}| j |d}|S )zGenerate _pageId2NumN)r[  	enumerater0   r   r<   r   rR   rp   )r/   r   Zid2numr   xr<   retr3   r3   r4   _getPageNumberByIndirect  s    

z&PdfFileReader._getPageNumberByIndirectc                 C   s   |j }| |}|S )a  
        Retrieve page number of a given PageObject

        :param PageObject page: The page to get page number. Should be
            an instance of :class:`PageObject<PyPDF3.pdf.PageObject>`
        :return: the page number or -1 if page not found
        :rtype: int
        )r   r  )r/   rA   r   r  r3   r3   r4   getPageNumber  s    	
zPdfFileReader.getPageNumberc                 C   s   |j }| |}|S )a>  
        Retrieve page number of a given Destination object

        :param Destination destination: The destination to get page number.
             Should be an instance of
             :class:`Destination<PyPDF3.pdf.Destination>`
        :return: the page number or -1 if page not found
        :rtype: int
        )rA   r  )r/   Zdestinationr   r  r3   r3   r4   getDestinationPageNumber  s    

z&PdfFileReader.getDestinationPageNumberc                 C   s.   |dd \}}|dd  }t |||f| S )Nr   r   )r   )r/   r   arrayrA   typr3   r3   r4   r    s    zPdfFileReader._buildDestinationc                 C   s   d\}}}d|kr@d|kr@|d }|d }|d dkr`|d }n d|kr`d|kr`|d }|d }|rt |tr|| ||}n8t|r|| jkr| j| }||td< ntd| |S )	N)NNNr   r   r]   r   r   r6  zUnexpected destination %r)r   r%   r  r   r  r#   r   ri  )r/   r  r   r   r   rB   r3   r3   r4   r  
  s"    



zPdfFileReader._buildOutlinec                 C   s   t | j| jS rF   )r   rS   rQ   r;  r3   r3   r4   rL   #  rM   c                 C   s,   z| j d d W S  tk
r&   Y dS X dS )z
        Get the page layout.
        See :meth:`setPageLayout()<PdfFileWriter.setPageLayout>`
        for a description of valid layouts.

        :return: Page layout currently being used.
        :rtype: ``str``, ``None`` if not specified
        rv   r8  Nrw   r:  r;  r3   r3   r4   r<  +  s    	zPdfFileReader.getPageLayoutc                 C   s,   z| j d d W S  tk
r&   Y dS X dS )z
        Get the page mode.
        See :meth:`setPageMode()<PdfFileWriter.setPageMode>`
        for a description of valid modes.

        :return: Page mode currently being used.
        :rtype: ``str``, ``None`` if not specified
        rv   rA  Nr  r;  r3   r3   r4   rB  =  s    	zPdfFileReader.getPageModec                 C   s  t dt dt dt df}|d kr*t }|d krRg | _| jd  }|d  }d}d|krf|d }|dkr|D ]}||krr|| ||< qr|d D ].}i }	t|tr||	d	< | j| |f|	 qnP|d
krt|	 D ]\}}
||kr|
||< qt
| |}|| | j| d S )N
/Resources	/MediaBox/CropBox/Rotaterv   r   r   r   r   r>   )r#   r  rX  rw   r=   r   r7   rj  rD   r   rT   r"   r6   )r/   r0   Zinheritr   ZinheritablePageAttributesrv  trw  rA   Zaddtr   ZpageObjr3   r3   r4   rj  O  s<      




zPdfFileReader._flattenc                 C   s  d}| j |j \}}|r(td||f  t|d|  }|rRtd||| f  |d dksbt||d k srttt| }t	|d D ]b}t
| |dd	 t|}t
| |dd	 t|}	t
| |dd	 ||jkrq| jr||krtd
||d |	 d |rp| }
|dd | }t	dt|D ]}t||  qP||
d zt|| }W nl tjk
r } zJt d	 }td||j|j|f tj | jrtd| t }W 5 d }~X Y nX |  S | jrtdt S )NFzHere1: %s %sr   z$Here2: objStm=%s.. stmnum=%s data=%sr   z/ObjStmz/Nr  r   zObject is in wrong index.r  z1Invalid stream (index %d) within object %d %d: %szCan't read object stream: %sz%This is a fatal error in strict mode.)xref_objStmr<   r   r7   r=   getDatar@   r   r   rh   r
   seekr$   ZreadFromStreamrW  r   ri  r   	readlinesr8   
readObjectZPdfStreamErrorr   exc_infor   r   r   r\  r   )r/   indirectReferencer   ZstmnumidxZobjStm
streamDatar   Zobjnumr   posr  r9   er3   r3   r4   _getObjectFromStreamr  s^      



 
z"PdfFileReader._getObjectFromStreamc                 C   s8  d}|rt d|j|jf | |j|j}|d kr6|S |jdkrZ|j| jkrZ| |}n|j| jkr|j| j|j kr| j|j |j }|rt d|j|jd|f | j|d | 	| j\}}||jkr| j
r| jrtd|j|j||f n n&||jkr td|j|j||f ||jks0tt| j| }| js"| jr"t| dsbtd	dd l}|d
|jd d }|d
|jd d }	| j| |	 }
t|
t| jd kstt|
 }|d tdt| jd  }
| ||
}n,td|j|jf tj | jr"td| |j|j| |S )NFzlooking at:r   z  Uncompressed Object:zVExpected object ID (%d %d) does not match actual (%d %d); xref table not zero-indexed.z9Expected object ID (%d %d) does not match actual (%d %d)._decryption_keyzfile has not been decryptedr   r   r   r   r   zObject %d %d not defined.zCould not find object.)r   r<   r   cacheGetIndirectObjectr  r  xrefr   r  readObjectHeaderrZ  rW  r   ri  r@   r  r`  rg  r   r   r   r  r8   r   r   r   _decryptObjectr   r   r\  cacheIndirectObject)r/   r  r   rc  startr<   r   r   r   r   r   r   r3   r3   r4   r=     sv     

 


 zPdfFileReader.getObjectc                 C   s   t |tst |tr(tt||j}n~t |trDt||j|_nbt |t	rvt
| D ]\}}| ||||< qZn0t |trtt|D ]}| || |||< q|S rF   )r   r   rq   r(   r   RC4_encryptoriginal_bytesr   _datar!   rD   r   r  r%   rh   r8   )r/   r9   r   Zdictkeyr   r   r3   r3   r4   r    s    


zPdfFileReader._decryptObjectc                 C   s   d}t | |t |O }|dd t|}|t |O }|dd t|}|d}t| |dd |r| jrt	d||f t j
 t|t|fS )NFr  r   r   z3Superfluous whitespace found in object header %s %s)r   ZskipOverCommentZskipOverWhitespacer  r   r^  r
   rW  r   r   r\  rR   )r/   r   extrar<   r   r9   r3   r3   r4   r    s$    


zPdfFileReader.readObjectHeaderc                 C   sF   d}| j ||f}|r.|r.td||f  n|rBtd||f  |S )NFzcache hit: %d %dzcache miss: %d %d)rY  rp   r   )r/   r   r<   r   outr3   r3   r4   r    s    z$PdfFileReader.cacheGetIndirectObjectc                 C   sH   ||f| j kr6d||f }| jr,t|n
t| || j ||f< |S )NzOverwriting cache for %s %s)rY  rW  r   ri  r   r   )r/   r   r<   r9   msgr3   r3   r4   r    s    
z!PdfFileReader.cacheIndirectObjectc           )   
      sv  d}|rt d| |dd | s0td| d d }td}|d d	 td
kr| |k rrtd|}|rHt d| qH|}zt|}W nJ tk
r   |	tdstdt|dd  
 }td Y n,X |}|d d tdkrtdi _i _t _||d |d}|tdkr|d}|d d tdkrztdt| |dd d}t|}	|r|	dkr|	_jrtdtj d}t| |dd t|}
t| |dd d}||
k r|d}|d tdkrB|dd |d}q|d tdkr`|dd |d d td\}}t|t| }}|jkri j|< |	j| krn|j| |	< |d7 }|	d7 }	qt| |dd |d}|td kr|d!d nqqt| |dd t|}t| D ] \}}|jkrB|j|< qBd"|kr|d" }nqq,| r|dd |\}}t|}|d# d$kst||| tt| | d%d| d&g}|rt d't!|  | d( t" dks,tjrPt" dkrPtd)   fd*d+}fd,d-}d}!|D ]$\}}
||kst||
 }t#|||
 D ]}	|d}|dkr|d}|d}n|dkr0|d}|d}|jkri j|< ||	|s|j| |	< |rt d.|	|f  nh|dkr|d}|d}d}||	|s|rrt d/|	||f  ||fj|	< njrtd0| qqxd1}|D ]0}||kr|jkr|$|jt%|< qd"|kr|d" }nqn|dkr jrtd2ntd3 q|d4d |d} | &td5}!|!dkr^|d6|! 8 }q,||d d}"t#d	D ](}#|d rv||#7 }d}" qqv|"rq,td7q,jrrjsr| }$jD ]}%|%d8krqֈj|% D ]n}&|j|% |& d z|\}'}(W n tk
r<   Y  qY nX |'|&j kr'|%  q֐qq||$d d S )9NFz>>readr  r   zCannot read an empty filei   r   rf  r   z%%EOFzEOF marker not foundz  line:	startxrefzstartxref not found	   z startxref on same line as offsetr   r  r   r   r   zxref table read errorTzFXref table not zero-indexed. ID numbers for objects will be corrected.   z
iZ0123456789tr       rw   iz/Prevr   z/XRefz/Indexr   zread idx_pairs=%sz/WzToo many entry sizes: %sc                    s<    |  dkr(  |  }t| |  S | dkr4dS dS d S )Nr   r   )r^  convertToInt)r   r  )
entrySizesr  r3   r4   getEntry  s    z$PdfFileReader.read.<locals>.getEntryc                    s   |  j |g kp|  jkS rF   )r  rp   r  )numr   r;  r3   r4   used_before  s    z'PdfFileReader.read.<locals>.used_beforezXREF Uncompressed: %s %szXREF Compressed: %s %s %szUnknown xref type: %s)rv   r   r   r   z6/Prev=0 in the trailer (try opening with strict=False)zA/Prev=0 in the trailer - assuming there is no previous xref tableir  
   z/Could not find xref table at specified locationr   )(r   r  r   r   ri  r   readNextEndLinerR   r;   
startswithstripr   r   r  r  r!   rw   r^  r
   r  rZ  rW  r\  splitrD   r   isdigitr  r@   r  r   r  rp   _pairsr8   rh   raw_getr#   find	_zeroXref))r/   r   r   Zlast1KrS  r  r  r   Z	firsttimer  sizeZcntr   r   Z
trailertagZ
newTrailerr   r   r<   Z
xrefstreamZ	idx_pairsr  r  Zlast_endr  Z	xref_typeZnext_free_objectZnext_generationZbyte_offsetZ
objstr_numZ	obstr_idxZtrailerKeystmpZxref_locfoundZlooklocgenidpidZpgenr3   )r  r/   r  r4   r^    sd    



 

















 




  

   








 
zPdfFileReader.readc                    s.   t  fddt j|  D  j|< d S )Nc                 3   s    | ]\}}| j  |fV  qd S rF   )rZ  )r   r   r   r;  r3   r4   r    s     z*PdfFileReader._zeroXref.<locals>.<genexpr>)r  rD   r  r   )r/   r   r3   r;  r4   r    s    zPdfFileReader._zeroXrefc                 c   s:   d}|| ||d  fV  |d7 }|d t |krq6qd S )Nr   r   r   )r8   )r/   r  r   r3   r3   r4   r    s
    zPdfFileReader._pairsc                 C   s  d}|rt d td}| dkr.td|d}|rRt d|dt| f | d	k rhtd
|dd |tdks|tdkrPd}|tdks|tdkr4|rt|dkrt d nt|dkrt d |d}|tdks|tdkr|dd d}| d	k r&td
|dd q||rBd	ndd qxq|r^t d || }|rt d|f q|rt d |S )NFz>>readNextEndLinerf  r   z!Could not read malformed PDF filer   z  x:z%xr   zEOL marker not foundr      z  x is CR 0Dr  z  x is LF 0Ar  Tz  x is neitherz  RNEL line:zleaving RNEL)r   r   r   r   ri  r^  ordr  )r/   r   r   rS  r  Zcrlfr3   r3   r4   r    sJ     

 



   zPdfFileReader.readNextEndLinec                 C   s"   d| _ z| |W S d| _ X dS )a`  
        When using an encrypted / secured PDF file with the PDF Standard
        encryption handler, this function will allow the file to be decrypted.
        It checks the given password against the document's user password and
        owner password, and then stores the resulting decryption key if either
        password is correct.

        It does not matter which password was matched.  Both passwords provide
        the correct decryption key that will allow the document to be used with
        this library.

        :param str password: The password to match.
        :return: ``0`` if the password failed, ``1`` if the password matched the user
            password, and ``2`` if the password matched the owner password.
        :rtype: int
        :raises NotImplementedError: if document uses an unsupported encryption
            method.
        TFN)r`  _decrypt)r/   passwordr3   r3   r4   rh  <  s    zPdfFileReader.decryptc              	   C   s2  | j d  }|d dkr"td|d dkr>td|d  | |\}}|rZ|| _dS |d	  }|d
krtd}n|d  d }t|||}|d  }|d
krt||}n^|}	tdddD ]H}
t	d}tt
|D ]"}|t	tt|| |
A 7 }qt||	}	q|	}| |\}}|r.|| _d
S dS )Nr   r}   r|   z1only Standard PDF encryption handler is availablero   )r   r   z@only algorithm code 1 and 2 are supported. This PDF uses code %sr   r   r   r   r   r~   r      r  rf  r   )rw   r=   NotImplementedError_authenticateUserPasswordr  _alg33_1r   r  rh   r   r8   chrr   )r/   r  r   Zuser_passwordr   r   r   Zreal_OZuserpassr  r   new_keyrH   Zowner_passwordr3   r3   r4   r  V  s>    
 zPdfFileReader._decryptc                 C   s   | j d  }|d  }|d  }|d  }| j d  }|d  }|d  j}|dkrvt||||\}	}
nV|d	krt|||d
  d ||||dtd \}	}
|	d d |d d  }	}|	|k|
fS )Nr   r   r   r   r   r   r   r   r   r   r~   z/EncryptMetadataFr   )rw   r=   r  r   r   rp   ZBooleanObject)r/   r  r   r   owner_entryp_entryZid_entry	id1_entryZreal_Ur   r   r3   r3   r4   r  y  s&      z'PdfFileReader._authenticateUserPasswordc                 C   s
   d| j kS )Nr   )rw   r;  r3   r3   r4   getIsEncrypted  s    zPdfFileReader.getIsEncryptedc                 C   s   |   S rF   )r  r;  r3   r3   r4   rL     rM   )TNT)NNN)NN)NN)NNN)0r   rE  rF  rG  r5   rd  rH  ZdocumentInfore  ZxmpMetadatarS   ZnumPagesrQ   ZnamedDestinationsrx  rs  rr  ry  r  rk  r  r  r  r  r  r  r  r0   r<  rI  rB  rJ  rj  r  r=   r  r  r  r  r^  r  r  r  rh  r  r  r  rg  r3   r3   r3   r4   rK    sh   
 

*

)
. 
#58	 w%#rK  c                 C   sn   |  |}t|tr|S |d kr@|D ]}|  |}|d kr$ q@q$t|trV| j|}t|}t| || |S rF   )rp   r   r,  r7   r:   r=   setRectangle)r/   r   defaultsrc  r  r3   r3   r4   getRectangle  s    



r  c                 C   s   t |tst|}|| |< d S rF   )r   r#   )r/   r   r   r3   r3   r4   r    s    
r  c                 C   s
   | |= d S rF   r3   )r/   r   r3   r3   r4   deleteRectangle  s    r  c                    s&   t  fddfddfddS )Nc                    s   t |  S rF   )r  r;  fallbackr   r3   r4   rL     rM   z)createRectangleAccessor.<locals>.<lambda>c                    s   t |  |S rF   )r  r/   r   r   r3   r4   rL     rM   c                    s
   t |  S rF   )r  r;  r  r3   r4   rL     rM   )rH  )r   r  r3   r  r4   createRectangleAccessor  s    

r  c                   @   sP  e Zd ZdZd@ddZdAddZeeZdd Zd	d
 Zdd Z	dd Z
ee
Z
dd ZeeZdd ZeeZdd ZeeZdd Zdd ZdBddZdCddZdDddZdEd d!ZdFd"d#ZdGd$d%ZdHd&d'ZdId(d)ZdJd*d+Zd,d- Zd.d/ Zd0d1 Zd2d3 Zd4d5 Zd6d7 Zed8d9Z ed:d;Z!ed<d=Z"ed>d=Z#ed?d=Z$dS )KrT   a  
    This class represents a single page within a PDF file.  Typically this
    object will be created by accessing the
    :meth:`getPage()<PyPDF3.PdfFileReader.getPage>` method of the
    :class:`PdfFileReader<PyPDF3.PdfFileReader>` class, but it is
    also possible to create an empty page with the
    :meth:`createBlankPage()<PageObject.createBlankPage>` static method.

    :param pdf: PDF file the page belongs to.
    :param indirectRef: Stores the original indirect reference to
        this object in its source PDF
    Nc                 C   s   t |  || _|| _d S rF   )r!   r5   r:   r   )r/   r:   r   r3   r3   r4   r5     s    
zPageObject.__init__c                 C   s   t | }|tdtd |tdt  |tdt  |dksP|dkr| dk	r|  dkr| |  d }|j }|j	 }nt
 |tdtdd||g |S )	aT  
        Returns a new blank page.
        If ``width`` or ``height`` is ``None``, try to get the page size
        from the last page of *pdf*.

        :param pdf: PDF file the page belongs to
        :param float width: The width of the new page expressed in default user
            space units.
        :param float height: The height of the new page expressed in default user
            space units.
        :return: the new blank page:
        :rtype: :class:`PageObject<PageObject>`
        :raises PageSizeNotDefinedError: if ``pdf`` is ``None`` or contains
            no page
        r   r>   r?   r  Nr   r   r  )rT   r  r#   r   r!   rS   rQ   rY   rZ   r[   r   ZPageSizeNotDefinedErrorr,  )r:   rV   rW   rA   Zlastpager3   r3   r4   rU     s    

zPageObject.createBlankPagec                 C   s   |d dkst | | | S )z
        Rotates a page clockwise by increments of 90 degrees.

        :param int angle: Angle to rotate the page.  Must be an increment
            of 90 deg.
        Z   r   r@   _rotater/   angler3   r3   r4   rotateClockwise  s    
zPageObject.rotateClockwisec                 C   s    |d dkst | |  | S )z
        Rotates a page counter-clockwise by increments of 90 degrees.

        :param int angle: Angle to rotate the page.  Must be an increment
            of 90 deg.
        r  r   r  r  r3   r3   r4   rotateCounterClockwise  s    z!PageObject.rotateCounterClockwisec                 C   s:   |  dd}t|tr|n| }t|| | td< d S )Nr  r   )rp   r   rR   r=   r$   r#   )r/   r  Z	rotateObjZcurrentAngler3   r3   r4   r  	  s    zPageObject._rotatec                 C   s   t  }|| |t    ||t   }i }t| D ]`}||kr||||krt|tt	
  }|||< || ||< q@||kr@||||< q@||fS rF   )r!   r"   rp   r=   rD   keysr  r#   r_   r`   ra   )Zres1Zres2resourceZnewResZpage2ResZ	renameResr   Znewnamer3   r3   r4   _mergeResources	  s    zPageObject._mergeResourcesc                 C   sZ   |s| S t | |} | jD ]<\}}tt|D ]&}|| }t|tr,|||||< q,q| S rF   )r  r  rh   r8   r   r#   rp   )r   renamer:   r   r!  r   opr3   r3   r4   _contentStreamRename	  s    

zPageObject._contentStreamRenamec                 C   s0   t | |}|jdg dg |jg dg |S )Nr   r  r	  )r  r  rG   r6   )contentsr:   r   r3   r3   r4   
_pushPopGS(	  s    
zPageObject._pushPopGSc           	   
   C   sT   |\}}}}}}t | |} | jdt|t|t|t|t|t|gdg | S )Nr   z cm)r  r  rG   r   )	r  r:   ctmr   r   r   r  r  r  r3   r3   r4   _addTransformationMatrix3	  s    
  z#PageObject._addTransformationMatrixc                 C   s   d| kr| d   S dS dS )z
        Accesses the page contents.

        :return: the ``/Contents`` object, or ``None`` if it doesn't exist.
            ``/Contents`` is optional, as described in PDF Reference  7.7.3.3
        r  N)r=   r;  r3   r3   r4   getContents?	  s    zPageObject.getContentsc                 C   s   |  | dS )a  
        Merges the content streams of two pages into one.  Resource references
        (i.e. fonts) are maintained from both pages.  The mediabox/cropbox/etc
        of this page are not altered.  The parameter page's content stream will
        be added to the end of this page's content stream, meaning that it will
        be drawn after, or "on top" of this page.

        :param PageObject page2: The page to be merged into this one. Should be
            an instance of :class:`PageObject<PageObject>`.
        N
_mergePage)r/   page2r3   r3   r4   	mergePageK	  s    zPageObject.mergePageFc              	      s
  t  }i }| d  }|d  }t }	| |fD ]4}
d|
kr0|
d}t|tr0|D ]}|	| qTq0dD ]0}t|||\}}|rj||t|< |	| qjtt
|dt  t
|dt  |td< t }|  }|d k	r|t|| j | }|d k	rN|d k	r&||}t||| j}t|| j}|| |r| j  | j  | j  | j  g}|j  |j  |j  |j  |j  |j  |j  |j  g d k	r>dd D  fddtdd	d
D } fddtdd	d
D }n dd	d
 } dd	d
 }t|t|g}t|t|g}t|d |d t|d |d g}t|d
 |d t|d |d g}| j| | j| t|| j| td< || td< |	| td< d S )Nr  rm   )z
/ExtGStatez/Fontz/XObjectz/ColorSpacez/Patternz/Shadingz/Propertiesz/ProcSetc                 S   s   g | ]}t |qS r3   )float)r   r  r3   r3   r4   r   	  s     z)PageObject._mergePage.<locals>.<listcomp>c                    s8   g | ]0}d   |  d  |d    d  qS )r   r   r   r   r3   r   r   Zcorners2r  r3   r4   r   	  s     r   r~   r   c                    s8   g | ]0}d   |  d  |d     d  qS )r   r   r   r3   r  r  r3   r4   r   	  s     r   r   r  ) r!   r=   r%   rp   r   r6   rT   r  r#   r"   	frozensetunionr  r  r:   r  rY   getLowerLeft_xZ
as_numericgetLowerLeft_ygetUpperRight_xgetUpperRight_yZgetUpperLeft_xZgetUpperLeft_yZgetLowerRight_xZgetLowerRight_yrh   r   maxZsetLowerLeftZsetUpperRightr  )r/   r   Zpage2transformationr  expandZnewResourcesr  ZoriginalResourcesZpage2ResourcesZ	newAnnotsrA   Zannotsr   resnewZ	newrenameZnewContentArrayoriginalContentpage2ContentZcorners1Znew_xZnew_yZ	lowerleftZ
upperrightr3   r  r4   r  X	  s    


 

  
    
$$zPageObject._mergePagec                    s   |   fdd | dS )a  
        This is similar to mergePage, but a transformation matrix is
        applied to the merged stream.

        :param PageObject page2: The page to be merged into this one. Should be
            an instance of :class:`PageObject<PageObject>`.
        :param tuple ctm: a 6-element tuple containing the operands of the
            transformation matrix
        :param bool expand: Whether the page should be expanded to fit the dimensions
            of the page to be merged.
        c                    s   t | j S rF   )rT   r  r:   )r  r  r   r3   r4   rL   	  s    z1PageObject.mergeTransformedPage.<locals>.<lambda>Nr  )r/   r   r  r  r3   r  r4   mergeTransformedPage	  s     zPageObject.mergeTransformedPagec              	   C   s   |  ||dd|ddg|S )a  
        This is similar to mergePage, but the stream to be merged is scaled
        by appling a transformation matrix.

        :param PageObject page2: The page to be merged into this one. Should be
            an instance of :class:`PageObject<PageObject>`.
        :param float scale: The scaling factor
        :param bool expand: Whether the page should be expanded to fit the
            dimensions of the page to be merged.
        r   r  )r/   r   scaler  r3   r3   r4   mergeScaledPage	  s    
  zPageObject.mergeScaledPagec              	   C   s>   t |}| |t |t |t | t |ddg|S )a  
        This is similar to mergePage, but the stream to be merged is rotated
        by appling a transformation matrix.

        :param PageObject page2: the page to be merged into this one. Should be
            an instance of :class:`PageObject<PageObject>`.
        :param float rotation: The angle of the rotation, in degrees
        :param bool expand: Whether the page should be expanded to fit the
            dimensions of the page to be merged.
        r   )mathradiansr  cossin)r/   r   rotationr  r3   r3   r4   mergeRotatedPage	  s    

  zPageObject.mergeRotatedPagec              	   C   s   |  |dddd||g|S )a  
        This is similar to mergePage, but the stream to be merged is translated
        by appling a transformation matrix.

        :param PageObject page2: the page to be merged into this one. Should be
            an instance of :class:`PageObject<PageObject>`.
        :param float tx: The translation on X axis
        :param float ty: The translation on Y axis
        :param bool expand: Whether the page should be expanded to fit the
            dimensions of the page to be merged.
        r   r   r  )r/   r   txtyr  r3   r3   r4   mergeTranslatedPage	  s    
  zPageObject.mergeTranslatedPagec           
   
   C   s   dddgdddg| | dgg}t |}t |t |dgt | t |dgdddgg}dddgdddg||dgg}t||}	t|	|}	| ||	d d |	d d |	d d |	d d |	d d |	d d g|S )aE  
        This is similar to mergePage, but the stream to be merged is rotated
        and translated by appling a transformation matrix.

        :param PageObject page2: the page to be merged into this one. Should be
            an instance of :class:`PageObject<PageObject>`.
        :param float tx: The translation on X axis
        :param float ty: The translation on Y axis
        :param float rotation: The angle of the rotation, in degrees
        :param bool expand: Whether the page should be expanded to fit the
            dimensions of the page to be merged.
        r   r   r   r  r  r  r  r   matrixMultiplyr  )
r/   r   r  r  r  r  translationrotatingZrtranslationr  r3   r3   r4   mergeRotatedTranslatedPage	  s.    

 

 
z%PageObject.mergeRotatedTranslatedPagec              
   C   s   t |}t |t |dgt | t |dgdddgg}|ddgd|dgdddgg}t||}| ||d d |d d |d d |d d |d d |d d g|S )a
  
        This is similar to mergePage, but the stream to be merged is rotated
        and scaled by appling a transformation matrix.

        :param PageObject page2: the page to be merged into this one. Should be
            an instance of :class:`PageObject<PageObject>`.
        :param float rotation: The angle of the rotation, in degrees
        :param float scale: The scaling factor
        :param bool expand: Whether the page should be expanded to fit the
            dimensions of the page to be merged.
        r   r   r   r  )r/   r   r  r  r  r"  scalingr  r3   r3   r4   mergeRotatedScaledPage
  s&    

 

 
z!PageObject.mergeRotatedScaledPagec           	   
   C   s   dddgdddg||dgg}|ddgd|dgdddgg}t ||}| ||d d |d d |d d |d d |d d |d d g|S )a.  
        This is similar to mergePage, but the stream to be merged is translated
        and scaled by appling a transformation matrix.

        :param PageObject page2: the page to be merged into this one. Should be
            an instance of :class:`PageObject<PageObject>`.
        :param float scale: The scaling factor
        :param float tx: The translation on X axis
        :param float ty: The translation on Y axis
        :param bool expand: Whether the page should be expanded to fit the
            dimensions of the page to be merged.
        r   r   r   )r   r   r  )	r/   r   r  r  r  r  r!  r$  r  r3   r3   r4   mergeScaledTranslatedPage
  s"    
 

 
z$PageObject.mergeScaledTranslatedPagec              
   C   s   dddgdddg||dgg}t |}t |t |dgt | t |dgdddgg}|ddgd|dgdddgg}	t||	}
t|
|}
| ||
d d |
d d |
d d |
d d |
d d |
d d g|S )a|  
        This is similar to mergePage, but the stream to be merged is translated,
        rotated and scaled by appling a transformation matrix.

        :param PageObject page2: the page to be merged into this one. Should be
            an instance of :class:`PageObject<PageObject>`.
        :param float tx: The translation on X axis
        :param float ty: The translation on Y axis
        :param float rotation: The angle of the rotation, in degrees
        :param float scale: The scaling factor
        :param bool expand: Whether the page should be expanded to fit the
            dimensions of the page to be merged.
        r   r   r   r  )r/   r   r  r  r  r  r  r!  r"  r$  r  r3   r3   r4    mergeRotatedScaledTranslatedPage5
  s.    

 

 
z+PageObject.mergeRotatedScaledTranslatedPagec                 C   s>   |   }|dk	r:t|| j|}t|| j}|| td< dS )z
        Applies a transformation matrix to the page.

        :param tuple ctm: A 6-element tuple containing the operands of the
            transformation matrix.
        Nr  )r  rT   r  r:   r  r#   )r/   r  r  Z
newContentr3   r3   r4   addTransformationY
  s      zPageObject.addTransformationc                 C   s  |  |dd|ddg tt| j | t| j | t| j | t| j | g| _d| kr| d }t|t	r|d d }n|d }tt|d | t|d | t|d | t|d | g}t|t	r|| t
d td t
d< n|| t
d t
d< dS )a	  
        Scales a page by the given factors by appling a transformation
        matrix to its content and updating the page size.

        :param float sx: The scaling factor on horizontal axis.
        :param float sy: The scaling factor on vertical axis.
        r   z/VPz/BBoxr   r   r   N)r(  r,  r  rY   r  r  r	  r
  r   r%   r#   r$   )r/   sxsyZviewportZbboxZscaled_bboxr3   r3   r4   r  g
  s4      


zPageObject.scalec                 C   s   |  || dS )z
        Scales a page by the given factor by appling a transformation
        matrix to its content and updating the page size.

        :param float factor: The scaling factor (for both X and Y axis).
        N)r  )r/   Zfactorr3   r3   r4   scaleBy
  s    zPageObject.scaleByc                 C   sH   |t | j | j   }|t | j | j   }| || dS )z
        Scales a page to the specified dimentions by appling a
        transformation matrix to its content and updating the page size.

        :param float width: The new width.
        :param float height: The new heigth.
        N)r  rY   r	  r  r
  r  r  )r/   rV   rW   r)  r*  r3   r3   r4   scaleTo
  s    zPageObject.scaleToc                 C   s:   |   }|dk	r6t|ts&t|| j}| | td< dS )a  
        Compresses the size of this page by joining all content streams and
        applying a FlateDecode filter.

        However, it is possible that this function will perform no action if
        content stream compression becomes "automatic" for some reason.
        Nr  )r  r   r  r:   ZflateEncoder#   )r/   r  r3   r3   r4   compressContentStreams
  s
    
z!PageObject.compressContentStreamsc                 C   s  t d}| d  }t|ts*t|| j}|jD ]\}}|tdkrh|d }t|trf||7 }|d7 }q0|tdkr~|d7 }q0|tdkr|d7 }|d }t|tr||d 7 }q0|tdkr|d	 }t|tr|d7 }||7 }q0|td
kr0|d D ]}t|tr||7 }q|d7 }q0|S )a  
        Locate all text drawing commands, in the order they are provided in the
        content stream, and extract the text.  This works well for some PDF
        files, but poorly for others, depending on the generator used.  This will
        be refined in the future.  Do not rely on the order of text coming out of
        this function, as it will change if this function is made more
        sophisticated.

        :return: a unicode string object.
        rf  r  r  r   r   zT*r  r  r   r  )r   r=   r   r  r:   r  r   rq   )r/   r"  r  r   r!  Z_textr   r3   r3   r4   extractText
  s8    









zPageObject.extractTextr  r3   r  )r  z	/BleedBox)r  r  z/TrimBoxz/ArtBox)NN)NNN)NNF)F)F)F)F)F)F)F)F)%r   rE  rF  rG  r5   rU   staticmethodr  r  r  r  r  r  r  r  r  r  r  r  r  r  r#  r%  r&  r'  r(  r  r+  r,  r-  r.  r  rY   ZcropBoxZbleedBoxZtrimBoxZartBoxr3   r3   r3   r4   rT     sL   

"	

J







$ 	+

	


rT   c                   @   s>   e Zd Zdd Zdd Zdd Zdd Zd	d
 ZeeeZ	dS )r  c                 C   sp   || _ g | _| }t|trRtd}|D ]}|t|  7 }q*tt|}ntt| }| | d S )Nrf  )	r:   r  r=   r   r%   r   r  r   "_ContentStream__parseContentStream)r/   r   r:   r   r  r3   r3   r4   r5   
  s    
zContentStream.__init__c                 C   s   | dd g }t|}|tdkst|dkr2q| dd | s^|tdks^|tdkrt|tjd}|tdkr|g kst	| 
|}| j|td	f q| j||f g }q|td
kr|tdtdfkr|d}qq|t|d  qd S )Nr   rf  r  r   r  r  TBIINLINE IMAGE%r  r   )r  r
   r   r   isalphar   ZreadUntilRegexr#   ZdelimiterPatternr@   _readInlineImager  r6   r^  r  )r/   r   r   peekr!  iir3   r3   r4   Z__parseContentStream  s*      
z"ContentStream.__parseContentStreamc                 C   sV  t  }t|}|dd |tdkr(q^t|| j}t|}|dd t|| j}|||< q|d}|d d tdksttd}|d}|tdkrB|d}|tdkr,|d}	|| }
d	}|	tj	krd
}|
|	7 }
|d}	q|	tdkr|r|dd qLn|dd ||
7 }n|dd ||7 }q||7 }q||dS )Nr  r   Ir   r   ZIDrf  EFTr	  )settingsr   )
r!   r
   r  r   r  r:   r^  r@   r   WHITESPACES)r/   r   r:  tokr   r   r  r   Ztok2Ztok3r1   Zhas_q_whitespacer3   r3   r4   r5  ,  sB    








zContentStream._readInlineImagec                 C   s   t  }| jD ]\}}|tdkr|td t  }|d |d  || dd  |td ||d  |td n2|D ]}||d  |td	 q|t| |td
 q| S )Nr2  r1  r:  r   r  zID r   ZEIr  r   )r   r  r   r   r   getvalue)r/   newdatar   r!  Zdicttextr  r3   r3   r4   _getData\  s     zContentStream._getDatac                 C   s   |  tt| d S rF   )r0  r   r   r  r3   r3   r4   _setDatao  s    zContentStream._setDataN)
r   rE  rF  r5   r0  r5  r?  r@  rH  r  r3   r3   r3   r4   r  
  s    0r  c                   @   s   e Zd ZdZdd Zdd Zedd Zedd Zed	d Z	ed
d Z
edd Zedd Zedd Zedd Zedd Zedd ZdS )rb  a  
    A class representing the basic document metadata provided in a PDF File.
    This class is accessible through
    :meth:`getDocumentInfo()<PyPDF3.PdfFileReader.getDocumentInfo()>`

    All text properties of the document metadata have
    *two* properties, eg. author and author_raw. The non-raw property will
    always return a ``TextStringObject``, making it ideal for a case where
    the metadata is being displayed. The raw property can sometimes return
    a ``ByteStringObject``, if PyPDF3 was unable to decode the string's
    text encoding; this requires additional safety in the caller and
    therefore is not as commonly accessed.
    c                 C   s   t |  d S rF   )r!   r5   r;  r3   r3   r4   r5     s    zDocumentInformation.__init__c                 C   s   |  |d }t|tr|S d S rF   )rp   r   rq   )r/   r   rc  r3   r3   r4   getText  s    
zDocumentInformation.getTextc                 C   s
   |  dS r   rA  r;  r3   r3   r4   rL     rM   zDocumentInformation.<lambda>c                 C   s
   |  dS r   r  r;  r3   r3   r4   rL     rM   c                 C   s
   |  dS Nz/AuthorrB  r;  r3   r3   r4   rL     rM   c                 C   s
   |  dS rC  r  r;  r3   r3   r4   rL     rM   c                 C   s
   |  dS Nz/SubjectrB  r;  r3   r3   r4   rL     rM   c                 C   s
   |  dS rD  r  r;  r3   r3   r4   rL     rM   c                 C   s
   |  dS Nz/CreatorrB  r;  r3   r3   r4   rL     rM   c                 C   s
   |  dS rE  r  r;  r3   r3   r4   rL     rM   c                 C   s
   |  dS Nr   rB  r;  r3   r3   r4   rL     rM   c                 C   s
   |  dS rF  r  r;  r3   r3   r4   rL     rM   N)r   rE  rF  rG  r5   rA  rH  r   Z	title_rawauthorZ
author_rawsubjectZsubject_rawZcreatorZcreator_rawZproducerZproducer_rawr3   r3   r3   r4   rb  u  s   rb  c                 C   s>   |dkrt dtdt|  } | dd  } td| d S )Nr~   zinvalid size in convertToIntz        iz>qr   )r   ri  r   r   unpack)r  r  r3   r3   r4   r    s
    
r  u   (¿N^NuAd NVu   ÿú.. ¶Ðh>/u   ©þdSizTc                 C   s   t t| tt d d } dd l}t| }||j |d|}|| ||j |dkrt|st|t d | }	|dkrt	dD ]}
t|	d |  }	q|	d | S )N    r   r   r   u   ÿÿÿÿ2   )
r   r   _encryption_paddingr   r   r"   r  r   r   rh   )r  r   r   r  r  r  metadata_encryptr   r  r   r   r3   r3   r4   _alg32  s    
rN  c           	      C   s   t | ||}t|tt d d }t||}|dkrtddD ]>}d}tt|D ]}|tt	|| |A 7 }qVt||}qB|S )NrJ  r   r   r  rf  )
r  r   r   rL  r   r  rh   r8   r  r   )	r   r   r   r   r   r  r   r  rH   r3   r3   r4   r     s    r   c                 C   sZ   t | tt d d } t| }| }|dkrJtdD ]}t| }q8|d | }|S )NrJ  r   rK  )r   r   rL  r   r   rh   )r  r   r   r  r   r   r   r3   r3   r4   r    s    r  c                 C   s&   t | dd|||}t|t}||fS )Nr   r   )rN  r   r  rL  )r  r  r  r  r   r   r3   r3   r4   r   $  s    r   c                 C   s   t | |||||}t }|t ||j | }	t||	}
tddD ]F}t	d}tt
|D ] }|t	tt|| |A 7 }qdt||
}
qL|
t	dd  |fS )Nr   r  rf   r   )rN  r   r"   rL  r  r   r   r  rh   r   r8   r  r   )r  r   r   r  r  r  rM  r   r  r   r  r   r  rH   r3   r3   r4   r   3  s    
r   )T)7rG  
__author____author_email__Z__maintainer__Z__maintainer_emailstringr  r   r   r`   r   	cStringIOr   ior   rf  r   r   r   r)   Zgenericr
   r   r   r   r   r   r   r   r   r   Zsetsr   r  r   hashlibobjectr   rK  r  r  r  r  r!   rT   rd   r  rb  r  rL  rN  r   r  r   r   r3   r3   r3   r4   <module>"   s   $

        @        	    Gy@	
,