o
    `^h w                     @   sl  d dl Z d dlmZmZmZ d dlmZ d dlmZ d dl	m
Z
mZmZmZmZmZmZmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZmZmZ ddlmZ ddl m!Z! ddl m"Z# ddl m$Z$m%Z% ddl&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3 ddl4m5Z5m6Z6 ddlm7Z7m8Z8m9Z9m:Z:m;Z; dZ<G dd dZ=G dd dZ>G dd de>Z?dS )    N)BytesIOFileIOIOBase)Path)TracebackType)	AnyDictIterableListOptionalTupleTypeUnioncast   )
Encryption)
PageObject)	PdfReader)StrByteTypedeprecation_bookmarkdeprecation_with_replacementstr_)	PdfWriter)GoToActionArguments)PagesAttributes)TypArgumentsTypFitArguments)PAGE_FITArrayObjectDestinationDictionaryObjectFitFloatObjectIndirectObject
NameObject
NullObjectNumberObjectOutlineItemTextStringObject
TreeObject)	PageRangePageRangeSpec)FitType
LayoutTypeOutlineTypePagemodeTypeZoomArgTypez=close() was called and thus the writer cannot be used anymorec                   @   s*   e Zd ZdZdedededdfddZdS )	_MergedPagez@Collect necessary information on each page that is being merged.pagedatasrcidreturnNc                 C   s   || _ || _d | _|| _d S N)r3   r2   out_pagedatar4   )selfr2   r3   r4    r9   L/home/air/shanriGPT/back/venv/lib/python3.10/site-packages/PyPDF2/_merger.py__init__Q   s   
z_MergedPage.__init__)__name__
__module____qualname____doc__r   r   intr;   r9   r9   r9   r:   r1   N   s    r1   c                   @   s  e Zd ZdZedd	d]dedeeef dd	fd
dZ	d^ddZ
deee  dee dee dd	fddZeddd											d_dee deeeef dee dee dedee dd	fddZdeeeef deeee f fddZeddd					d`deeeef dee ded	eeeef eeeef ee f dedd	f
ddZdeeef dd	fd d!Zdad"d#Zd$eeef dd	fd%d&Z d$eeef dd	fd'd(Z!d)e"dd	fd*d+Z#d)e"dd	fd,d-Z$d.e%dd	fd/d0Z&d.e%dd	fd1d2Z'd3ed4eeeeef f deeeef eeeef ee f deeeef  fd5d6Z(d3ede)deeeef eeeef ee f de)fd7d8Z*dad9d:Z+edd				dbdee,e-  d;ee. dd	fd<d=Z/edd>dee-e0f d?e1dd	fd@dAZ2dee1 dd	fdBdCZ3edd		dcdee1 dee,e-  dd	fdDdEZ4edd>		dcdeeef dFee) deee  fdGdHZ5edd>		dcdeeef dFee) deee  fdIdJZ6d	d	d	dde7d	fdKedee d;ed	e.e8f dLeee9e9e9f  dMedNedOe:dPee de8fdQdRZ;							SdddKedPed;ed	e.e8f dLeee9e9e9f  dMedNedOe<dTe=de8fdUdVZ>							SdddKedPed;ed	e.e8f dLeee9e9e9f  dMedNedOe<dTe=de8fdWdXZ?dKedPedd	fdYdZZ@				dbdKedee dPee dd	fd[d\ZAd	S )e	PdfMergeraI  
    Initialize a ``PdfMerger`` object.

    ``PdfMerger`` merges multiple PDFs into a single PDF.
    It can concatenate, slice, insert, or any combination of the above.

    See the functions :meth:`merge()<merge>` (or :meth:`append()<append>`)
    and :meth:`write()<write>` for usage information.

    :param bool strict: Determines whether user should be warned of all
            problems and also causes some correctable problems to be fatal.
            Defaults to ``False``.
    :param fileobj: Output file. Can be a filename or any kind of
            file-like object.
    outline)	bookmarksF strictfileobjr5   Nc                 C   s6   g | _ g | _t | _g | _g | _d| _|| _|| _d S )Nr   )	inputspagesr   outputrB   named_destsid_countrF   rE   )r8   rE   rF   r9   r9   r:   r;   i   s   
zPdfMerger.__init__c                 C   s   | S r6   r9   )r8   r9   r9   r:   	__enter__v   s   zPdfMerger.__enter__exc_typeexc	tracebackc                 C   s   | j r	| | j  |   dS )z*Write to the fileobj and close the merger.N)rF   writeclose)r8   rM   rN   rO   r9   r9   r:   __exit__z   s   zPdfMerger.__exit__outline_itemimport_outline)bookmarkimport_bookmarksTpage_numberrH   positionc                 C   s  |dur|du r|}d}d}t | d| dt ntd|du r'td|du r/td| |\}	}
t|	| jd	}| j|	|f |
durL|
|_	|du rXd
t
|jf}nt|trf|t
|j}nt|trln	t|tsutdg }g }|r|j}| |||}|rtt|t| jt }|  j||g7  _n|  j|7  _|j}| |||}|  j|7  _t| D ]}|j| }| j}|  jd7  _t|||}|| q| | |  | || j||< dS )a  
        Merge the pages from the given file into the output file at the
        specified page number.

        :param int page_number: The *page number* to insert this file. File will
            be inserted after the given number.

        :param fileobj: 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 str outline_item: Optionally, you may specify an outline item
            (previously referred to as a 'bookmark') to be applied at the
            beginning of the included file by supplying the text of the outline item.

        :param pages: can be a :class:`PageRange<PyPDF2.pagerange.PageRange>`
            or a ``(start, stop[, step])`` tuple
            to merge only the specified range of pages from the source
            document into the output document.
            Can also be a list of pages to merge.

        :param bool import_outline: You may prevent the source document's
            outline (collection of outline items, previously referred to as
            'bookmarks') from being imported by specifying this as ``False``.
        NrX   rW   zG is deprecated as an argument and will be removed in PyPDF2=4.0.0. Use  insteadzCThe argument position of merge is deprecated. Use page_number only.page_number may not be Nonezfileobj may not be None)rE   r   z0"pages" must be a tuple of (start, stop[, step])r   )!warningswarnDeprecationWarning
ValueError_create_streamr   rE   rG   append_encryptionlenrH   
isinstancer*   indiceslisttuple	TypeErrorrB   _trim_outliner'   r(   r&   rK   r!   fitnamed_destinations_trim_destsrJ   ranger1   _associate_dests_to_pages!_associate_outline_items_to_pages)r8   rW   rF   rS   rH   rT   rX   old_termnew_termstreamencryption_objreadersrcpagesrB   outline_item_typdeststrimmed_destsipager4   mpr9   r9   r:   merge   sp   #





zPdfMerger.mergec                 C   s   d }t |ttfrt|d}||fS t |tr9|jr|j}|j }|jd t	|j
 }|j| ||fS t|drTt|drT|d |
 }t	|}||fS td)Nrbr   seekreadzPdfMerger.merge requires an object that PdfReader can parse. Typically, that is a Path or a string representing a Path, a file object, or an object implementing .seek and .read. Passing a PdfReader directly works as well.)rc   strr   r   r   ra   rq   tellr}   r   r~   hasattrNotImplementedError)r8   rF   rr   rq   	orig_tellfilecontentr9   r9   r:   r_      s(   	



zPdfMerger._create_streamc                 C   s   |  t| j|||| dS )a  
        Identical to the :meth:`merge()<merge>` method, but assumes you want to
        concatenate all pages onto the end of the file instead of specifying a
        position.

        :param fileobj: 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 str outline_item: Optionally, you may specify an outline item
            (previously referred to as a 'bookmark') to be applied at the
            beginning of the included file by supplying the text of the outline item.

        :param pages: can be a :class:`PageRange<PyPDF2.pagerange.PageRange>`
            or a ``(start, stop[, step])`` tuple
            to merge only the specified range of pages from the source
            document into the output document.
            Can also be a list of pages to append.

        :param bool import_outline: You may prevent the source document's
            outline (collection of outline items, previously referred to as
            'bookmarks') from being imported by specifying this as ``False``.
        N)r{   rb   rH   )r8   rF   rS   rH   rT   r9   r9   r:   r`     s   !zPdfMerger.appendc                 C   s   | j du r	tt| jD ]$}| j |j tttt	f | j j
 }| j |tj d  |_q|   |   | j |\}}|rI|  dS dS )z
        Write all data that has been merged to the given output file.

        :param fileobj: Output file. Can be a filename or any kind of
            file-like object.
        N)rI   RuntimeErrorERR_CLOSED_WRITERrH   add_pager2   r   r   r   r   _pages
get_objectget_referencePAKIDSr7   _write_dests_write_outlinerP   rQ   )r8   rF   ry   	pages_objmy_fileret_fileobjr9   r9   r:   rP   A  s   

zPdfMerger.writec                 C   s.   g | _ | jD ]\}}|  qg | _d| _dS )zHShut all file descriptors (input and output) and clear all memory usage.N)rH   rG   rQ   rI   )r8   fo_readerr9   r9   r:   rQ   a  s
   

zPdfMerger.closeinfosc                 C   "   | j du r	tt| 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.
            Example: ``{u'/Title': u'My title'}``
        N)rI   r   r   add_metadatar8   r   r9   r9   r:   r   j  s   
zPdfMerger.add_metadatac                 C      t dd | | dS )zW
        .. deprecated:: 1.28.0

            Use :meth:`add_metadata` instead.
        addMetadatar   N)r   r   r   r9   r9   r:   r   v     
zPdfMerger.addMetadatalayoutc                 C   r   )zZ
        .. deprecated:: 1.28.0

            Use :meth:`set_page_layout` instead.
        setPageLayoutset_page_layoutN)r   r   r8   r   r9   r9   r:   r     r   zPdfMerger.setPageLayoutc                 C   r   )a  
        Set the page layout.

        :param str layout: The page layout to be used

        .. list-table:: Valid ``layout`` arguments
           :widths: 50 200

           * - /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
        N)rI   r   r   _set_page_layoutr   r9   r9   r:   r     s   
zPdfMerger.set_page_layoutmodec                 C   s   t ddd | | dS )zX
        .. deprecated:: 1.28.0

            Use :meth:`set_page_mode` instead.
        setPageModeset_page_mode3.0.0N)r   r   r8   r   r9   r9   r:   r     s   zPdfMerger.setPageModec                 C   r   )aP  
        Set the page mode.

        :param str mode: The page mode to use.

        .. list-table:: Valid ``mode`` arguments
           :widths: 50 200

           * - /UseNone
             - Do not show outline or thumbnails panels
           * - /UseOutlines
             - Show outline (aka bookmarks) panel
           * - /UseThumbs
             - Show page thumbnails panel
           * - /FullScreen
             - Fullscreen view
           * - /UseOC
             - Show Optional Content Group (OCG) panel
           * - /UseAttachments
             - Show attachments panel
        N)rI   r   r   r   r   r9   r9   r:   r     s   
zPdfMerger.set_page_modepdfrv   c           	      C   s   g }t |tr	|ntt| }| D ]3\}}|D ],}|j|  |d  krE|d  |td< t|t|d ks>J ||  nqq|S )zHRemove named destinations that are not a part of the specified page set./Page/Title)	rc   re   rl   itemsrH   r   r$   r   r`   )	r8   r   rv   rH   	new_destslstkeyobjjr9   r9   r:   rk     s   
zPdfMerger._trim_destsc                 C   s   g }d}t |tr|ntt| }t|D ]Q\}}t |tr8| |||}	|	r7|s2|||d   ||	 qd}|D ])}
|d du rEq<|j|
  |d  kre|d  |td< || d} nq<q|S )zJRemove outline item entries that are not a part of the specified page set.Tr   Fr   N)	rc   re   rl   	enumeraterh   r`   rH   r   r$   )r8   r   rB   rH   new_outlineprev_header_addedr   rx   rS   subr   r9   r9   r:   rh     s6   



zPdfMerger._trim_outlinec                 C   sv   | j d u r	tt| jD ],}d }d|v r.t| jD ]\}}|j|d kr-|j|td<  nq|d ur8| j 	| qd S )Nr   )
rI   r   r   rJ   r   rH   r4   r7   r$   add_named_destination_object)r8   
named_destpagenory   r9   r9   r:   r     s   

zPdfMerger._write_destsparentc                 C   s   | j d u r	tt|d u r| j}|d usJ dd }|D ]>}t|tr*| || qd }d|v rIt| jD ]\}}|j	|d krH| 
||  nq5|d urZ|d= |d= | j ||}qd S )Nhint for mypyr   /Type)rI   r   r   rB   rc   re   r   r   rH   r4   _write_outline_item_on_pageadd_outline_item_dict)r8   rB   r   
last_addedrS   page_nory   r9   r9   r:   r     s,   

zPdfMerger._write_outline)rU   ry   c                 C   s   t t|d }t|jt|g}tjtjftj	tjftj
tjftjtjftjtjtjdftjtjtjtjtjfi}||t D ]!}||v rWt|| tsW|t||  n|td ||= q@tttjtdttjt|i|td< d S )Nr   z/Zoomr   z/GoToz/A)r   r   r&   r4   r$   r   FIT_Hr   TOPFIT_BHFIT_VLEFTFIT_BVXYZFIT_RBOTTOMRIGHTgetrf   rc   r%   r`   r"   r    r   SDr   )r8   rS   ry   oi_typeargsfit2arg_keysarg_keyr9   r9   r:   r   "  s4   




z%PdfMerger._write_outline_item_on_pagec                 C   sv   | j D ]5}d }|d }t|trq|D ]}| |j kr!|j}q|d u r0td|d  dt||td< qd S )Nr   zUnresolved named destination 'r   ')rJ   rc   r&   r   r2   r4   r^   r$   )r8   rH   r   r   npry   r9   r9   r:   rm   E  s   

z#PdfMerger._associate_dests_to_pagesc                 C   s   |d u r| j }|d usJ d|D ]7}t|tr| || qd }|d }t|tr+q|D ]}| |j kr;|j}q-|d urHt||td< qd S )Nr   r   )	rB   rc   re   rn   r&   r   r2   r4   r$   )r8   rH   rB   rS   r   outline_item_pagepr9   r9   r:   rn   W  s&   

z+PdfMerger._associate_outline_items_to_pagesrootc                 C   sz   |d u r| j }t|D ]/\}}t|tr$| ||}|r#|g|   S q||ks5ttttf |d |kr:|g  S qd S )Nr   )rB   r   rc   re   find_outline_itemr   r   r   )r8   rS   r   rx   oi_enumresr9   r9   r:   r   p  s   

zPdfMerger.find_outline_itemc                 C   s   |  ||S )zZ
        .. deprecated:: 2.9.0
            Use :meth:`find_outline_item` instead.
        )r   )r8   rS   r   r9   r9   r:   find_bookmark  s   
zPdfMerger.find_bookmarktitlecolorbolditalicri   pagenumc	              
   C   s   |dur|durt d|dur"d}	d}
t|	 d|
 dt |}|du r*t d| j}|du r5tt||||d||||S )al  
        Add an outline item (commonly referred to as a "Bookmark") to this PDF file.

        :param str title: Title to use for this outline item.
        :param int page_number: Page number this outline item will point to.
        :param parent: A reference to a parent outline item to create nested
            outline items.
        :param tuple color: Color of the outline item's font as a red, green, blue tuple
            from 0.0 to 1.0
        :param bool bold: Outline item font is bold
        :param bool italic: Outline item font is italic
        :param Fit fit: The fit of the destination page.
        NzMThe argument pagenum of add_outline_item is deprecated. Use page_number only.r   rW   H is deprecated as an argument and will be removed in PyPDF2==4.0.0. Use rY   rZ   )r^   r[   r\   r]   rI   r   r   add_outline_item)r8   r   rW   r   r   r   r   ri   r   ro   rp   writerr9   r9   r:   r     s:   zPdfMerger.add_outline_item/Fitr   c           	      G   *   t ddd | ||||||t||dS )zZ
        .. deprecated:: 1.28.0
            Use :meth:`add_outline_item` instead.
        addBookmarkr   r   fit_typefit_argsr   r   r!   	r8   r   r   r   r   r   r   ri   r   r9   r9   r:   r        
zPdfMerger.addBookmarkc           	      G   r   )zY
        .. deprecated:: 2.9.0
            Use :meth:`add_outline_item` instead.
        r   r   r   r   r   r   r9   r9   r:   add_bookmark  r   zPdfMerger.add_bookmarkc                 C   s   t ddd | ||S )z_
        .. deprecated:: 1.28.0
            Use :meth:`add_named_destination` instead.
        addNamedDestinationadd_named_destinationr   )r   r   )r8   r   r   r9   r9   r:   r      s   zPdfMerger.addNamedDestinationc                 C   s   |dur|durt d|dur"d}d}t| d| dt |}|du r*t dtt|t|tjdd	}| j	
| dS )
z
        Add a destination to the output.

        :param str title: Title to use
        :param int page_number: Page number this destination points at.
        NzRThe argument pagenum of add_named_destination is deprecated. Use page_number only.r   rW   r   rY   rZ   i:  )top)r^   r[   r\   r]   r   r(   r&   r!   fit_horizontallyrJ   r`   )r8   r   rW   r   ro   rp   destr9   r9   r:   r   
  s,   
zPdfMerger.add_named_destination)FrD   )r5   rA   )NNNNTN)NNT)r5   N)NNr6   )NNFFr   )Br<   r=   r>   r?   r   boolr   r   r   r;   rL   r   r   BaseExceptionr   rR   r@   r   r   r+   r{   r   r   r   r_   r*   r
   r`   rP   rQ   r   r   r   r   r-   r   r   r/   r   r   rk   r.   rh   r   r	   r'   r)   r   r   r1   r   rm   rn   r   r   r   r#   floatr!   r   r,   r0   r   r   r   r   r9   r9   r9   r:   rA   X   s   




u

#""
 				"
"



"




	

;	

	

rA   c                       s*   e Zd Zdededdf fddZ  ZS )PdfFileMergerr   kwargsr5   Nc                    s>   t ddd d|vrt|dk rd|d< t j|i | d S )Nr   rA   r   rE   r   T)r   rb   superr;   )r8   r   r   	__class__r9   r:   r;   0  s   zPdfFileMerger.__init__)r<   r=   r>   r   r;   __classcell__r9   r9   r   r:   r   /  s    "r   )@r[   ior   r   r   pathlibr   typesr   typingr   r   r	   r
   r   r   r   r   r   ra   r   _pager   r   r   _utilsr   r   r   r   _writerr   	constantsr   r   r   r   r   genericr   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   	pageranger*   r+   r,   r-   r.   r/   r0   r   r1   rA   r   r9   r9   r9   r:   <module>   s2   ,<
     \