
    h5j7                       d Z ddlmZ ddlZddlZddlZddlmZmZm	Z	m
Z
mZmZm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 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" er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/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8 ddl9m:Z: ddl;m<Z<m=Z=m>Z> ddl?m@Z@mAZAmBZBmCZC ddlDmEZEmFZFmGZG ddlHmIZImJZJmKZKmLZLmMZM g ZN e deOePe      ZQ e d      ZR eS       ZTd1dZUd2dZVd3dZW e'eL       G d d             ZX e'e3       G d d             ZY e'e8       G d d             ZZd4d Z[ e'e2       G d! d"             Z\ e'e7       G d# d$             Z] e'e4       G d% d&             Z^ e'e,       G d' d(e             Z_ e'e+       G d) d*             Z` e'e*       G d+ d,             Za e'e.       G d- d.             Zb ej                  e.        e'e/       G d/ d0             Zd ej                  e/       y)5a1  Implement some features in Python and monkey-patch them onto C++ classes.

In several cases the implementation of some higher levels features might as
well be in Python. Fortunately we can attach Python methods to C++ class
bindings after the fact.

We can also move the implementation to C++ if desired.
    )annotationsN)Callable	ItemsViewIterableIteratorKeysViewMutableMapping
ValuesView)	ExitStackcontextmanagersuppress)Decimal)BytesIO)Path)run)TemporaryDirectory)TYPE_CHECKINGBinaryIOLiteralTypeVar)warn)PageCopyResult)augment_override_cppaugments)
AccessModeAttachedFileAttachedFileSpecAttachmentsJSONStreamDataNameTree
NumberTreeObjectStreamMode
ObjectTypePagePdf	RectangleStreamDecodeLevelStreamParserToken_ObjectMapping)PageCopyWarning)atomic_overwritecheck_different_filescheck_stream_is_usable)
EncryptionEncryptionInfoOutlinePermissions)PdfMetadatadecode_pdf_dateencode_pdf_date)Array
DictionaryNameObjectStreamNumericTc                    t        j                         }|j                  j                  |        t	               }|j                  |       |j                  d       |j                         S )z=Construct a single page PDF from the provided page in memory.r   )r%   newpagesappendr   saveseekread)pagepdfbios      F/var/www/html/qr/venv/lib/python3.12/site-packages/pikepdf/_methods.py_single_page_pdfrH   L   sH    
'')CIIT
)CHHSMHHQK88:    c           	         t        dddt        |      t        |       gd       |j                  |j                  j	                  d            }|j                         st        |      |S )Nmutooldrawz-oT)check   )r   str	with_namenameformatexistsFileNotFoundError)in_pathout_patternout_paths      rG   _run_mudrawrX   V   sa    	64[!13w<@ $$[%5%5%<%<Q%?@H??))OrI   c                    t               5 }t        |      dz  }t        |      d| z  }t        |      d| z  }|j                  |        t        ||      }|j	                         cddd       S # 1 sw Y   yxY w)z9Use mupdf draw to rasterize the PDF in the memory buffer.z	input.pdfz	output%d.zoutput1.N)r   r   write_bytesrX   
read_bytes)bufferfmttmp_dirrU   rV   rW   s         rG   _mudrawr_   a   s     
	 %w-+-7m	#&77=XcU#33F#w4""$% % %s   AA22A;c                  r    e Zd Zd ZdddZd Zdddd	 	 	 	 	 	 	 ddZefddZefdd	Z	efdd
Z
efddZy)Extend_Objectc                R    t        | t        t        z        r| j                         S y N)
isinstancer7   r:   keysselfs    rG   _ipython_key_completions_z'Extend_Object._ipython_key_completions_r   s     dJ/099;rI   Nc                   | j                  |      st        d      |t        j                  f}|D ch c]  }t	        |       c}t        | j                               }t        |j                               }t        d |z  |z  D              sJ ||z
  z
  }fd|D        D ]
  }||   | |<    |D ]  }| |=  y c c}w )Nz.Objects must have the same owner for emplace()c              3  <   K   | ]  }t        |t                y wrc   )rd   rO   ).0ks     rG   	<genexpr>z(Extend_Object.emplace.<locals>.<genexpr>   s     U!:a%U   c              3  ,   K   | ]  }|vs|  y wrc    )rk   rl   
retain_sets     rG   rm   z(Extend_Object.emplace.<locals>.<genexpr>   s     ?1J+>!?s   	)same_owner_as	TypeErrorr8   ParentrO   setre   all)rg   otherretainrl   	self_keys
other_keysdel_keysrq   s          @rG   emplacezExtend_Object.emplacew   s    !!%(LMM
 >kk^F 1771A7
		$	&
U
Y0F0SUUUUz)J6?Z? 	AAhDG	 	AQ	  8s   Cc                N   t        |t              rt        |      }|j                         }t        |t              rt        |      }n|t        g       }n|j                         }t	        d |D              st        d      t	        d |D              st        d      t        |      dk7  r;t        |      t        |      k7  r$t        dt        |       dt        |       d      t        |      d	k(  r|d   }t        |      dk(  rd }||fS t        |      d	k(  r|d   }||fS )
Nc              3  <   K   | ]  }t        |t                y wrc   )rd   r8   rk   items     rG   rm   z2Extend_Object._type_check_write.<locals>.<genexpr>   s     >d:dD)>rn   z=filter must be: pikepdf.Name or pikepdf.Array([pikepdf.Name])c              3  H   K   | ]  }t        |t              xs |d u   y wrc   )rd   r7   r   s     rG   rm   z2Extend_Object._type_check_write.<locals>.<genexpr>   s(      
?CZj)9TT\9
s    "zOdecode_parms must be: pikepdf.Dictionary or pikepdf.Array([pikepdf.Dictionary])r   zfilter (z) and decode_parms (z) must be arrays of same lengthrN   )	rd   listr6   wrap_in_arrayrv   rs   len
ValueErrorrepr)rg   filter_decode_parmss      rG   _type_check_writezExtend_Object._type_check_write   sF   gt$GnG'')lD) .L! 9L'557L>g>>O   
GS
 
 6  |!c'lc,6G&G4=/ *&''FH  w<1ajG|!L $$ !#'?L$$rI   T)filterr   
type_checkc               ^    |r|| j                  ||      \  }}| j                  |||       y )N)r   r   )r   _write)rg   datar   r   r   s        rG   writezExtend_Object.write   s5     &,#'#9#9&,#O FLDlCrI   c                    | j                   t        j                  k7  r"|t        u rt	        d| j
                         |S t        |       S )av  Convert to int, or return default if not an integer.

        In explicit conversion mode, this provides a safe way to convert
        pikepdf.Integer to Python int with proper type hints.

        Args:
            default: Value to return if this object is not an integer.
                If not provided and the object is not an integer,
                raises TypeError.

        Returns:
            The integer value, or the default if provided and object is
            not an integer.

        Raises:
            TypeError: If object is not an integer and no default was provided.

        .. versionadded:: 10.1
        zExpected integer, got )
_type_coder#   integer_MISSINGrs   
_type_nameintrg   defaults     rG   as_intzExtend_Object.as_int   sE    ( ??j000(""88I JKKN4yrI   c                    | j                   t        j                  k7  r"|t        u rt	        d| j
                         |S t        |       S )as  Convert to bool, or return default if not a boolean.

        In explicit conversion mode, this provides a safe way to convert
        pikepdf.Boolean to Python bool with proper type hints.

        Args:
            default: Value to return if this object is not a boolean.
                If not provided and the object is not a boolean,
                raises TypeError.

        Returns:
            The boolean value, or the default if provided and object is
            not a boolean.

        Raises:
            TypeError: If object is not a boolean and no default was provided.

        .. versionadded:: 10.1
        zExpected boolean, got )r   r#   booleanr   rs   r   boolr   s     rG   as_boolzExtend_Object.as_bool   sE    ( ??j000(""88I JKKNDzrI   c                    | j                   t        j                  t        j                  fvr"|t        u rt        d| j                         |S t        |       S )a  Convert to float, or return default if not numeric.

        Works for both Integer and Real objects.

        Args:
            default: Value to return if this object is not numeric.
                If not provided and the object is not numeric,
                raises TypeError.

        Returns:
            The float value, or the default if provided and object is
            not numeric.

        Raises:
            TypeError: If object is not numeric and no default was provided.

        .. versionadded:: 10.1
        zExpected numeric, got )r   r#   r   realr   rs   r   floatr   s     rG   as_floatzExtend_Object.as_float   sN    & ??:#5#5z"GG(""88I JKKNT{rI   c                    | j                   t        j                  k7  r"|t        u rt	        d| j
                         |S t        | j                               S )aX  Convert to Decimal, or return default if not a Real.

        Preferred over as_float() for PDF reals to preserve precision.
        Only works for Real objects, not Integer.

        Args:
            default: Value to return if this object is not a Real.
                If not provided and the object is not a Real,
                raises TypeError.

        Returns:
            The Decimal value, or the default if provided and object is
            not a Real.

        Raises:
            TypeError: If object is not a Real and no default was provided.

        .. versionadded:: 10.1
        zExpected real, got )r   r#   r   r   rs   r   r   _get_real_valuer   s     rG   
as_decimalzExtend_Object.as_decimal  sM    ( ??joo-(""5doo5F GHHNt++-..rI   rc   )rw   r9   rx   Iterable[Name] | None)r   bytesr   zName | Array | Noner   zDictionary | Array | Noner   r   )r   r<   returnzint | T)r   r<   r   zbool | T)r   r<   r   z	float | T)r   r<   r   zDecimal | T)__name__
__module____qualname__rh   r|   r   r   r   r   r   r   r   rp   rI   rG   ra   ra   p   su    
."%P '+26DD $	D
 0D D #+ 4 $, 4 %- 2 '/ /rI   ra   c                     e Zd Zed        Zd Zd"dZed#d       Zej                  d$d       Zej                  d        Z	 	 	 d%	 	 	 	 	 	 	 d&d
Zd'd(dZd)d*dZdd	 	 	 d+dZ	 d)dd	 	 	 	 	 	 	 d,dZd-dZd Zd Zed.d       Zed/d       Z	 d)	 	 	 d0dZ	 d)d	ddddddej.                  d	d	d	ddd	d	d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d1dZej4                  ej8                  dd	 	 	 	 	 	 	 	 	 d2dZed3d       Zd4dZ edd	d	ddde!jD                  d	d 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d5d!       Z#y)6
Extend_Pdfc              #     K   | j                          	 d | j                          y# | j                          w xY ww)a  Context manager to hold the per-Pdf lock for compound operations.

        Under free-threaded Python, individual C++ method calls are
        automatically serialized, but multi-step Python operations (e.g.
        read-modify-write on the same dictionary) are not atomic.  Wrap
        such sequences in ``with pdf.lock():`` to prevent interleaving.

        On GIL-enabled builds this is a no-op.
        N)_acquire_lock_release_lockrf   s    rG   lockzExtend_Pdf.lock)  s4      		! D s   >) >;>c                ^    t               }| j                  |       |j                  d       |S )Nr   )r   rA   rB   )rg   rF   s     rG   _quick_savezExtend_Pdf._quick_save:  s$    i		#
rI   Nc                    | j                         j                         }d|i}t        t        t              5  t        |d      j                  d      |d<   d d d        |S # 1 sw Y   |S xY w)Napplication/pdfsvgutf-8image/svg+xml)r   rC   r   rT   RuntimeErrorr_   decode)rg   includeexcludepdf_datar   s        rG   _repr_mimebundle_zExtend_Pdf._repr_mimebundle_@  sk    ##%**,x
 '6 	M$+He$<$C$CG$LD!	M	Ms   A  A*c                   | j                         5  t        j                  | j                  vs$t	        | j                  j                  t
              s(| j                  t                     | j                  _        | j                  j                  j                  s4| j                  | j                  j                        | j                  _        | j                  j                  cd d d        S # 1 sw Y   y xY wrc   )r   r8   Infotrailerrd   r7   make_indirectis_indirectrf   s    rG   docinfozExtend_Pdf.docinfoI  s    YY[ 	%yy,J!!:5 %)$6$6z|$D!<<$$00$($6$6t||7H7H$I!<<$$	% 	% 	%s   CC--C6c                    | j                         5  |j                  st        d      || j                  _        d d d        y # 1 sw Y   y xY w)Nz:docinfo must be an indirect object - use Pdf.make_indirect)r   r   r   r   r   )rg   new_docinfos     rG   r   zExtend_Pdf.docinfoT  sG    YY[ 	,** P  !,DLL	, 	, 	,   )AAc                    | j                         5  t        j                  | j                  v r| j                  `d d d        y # 1 sw Y   y xY wrc   )r   r8   r   r   rf   s    rG   r   zExtend_Pdf.docinfo]  s:    YY[ 	&yyDLL(LL%	& 	& 	&r   TFc                "    t        | |||       S )N)pikepdf_marksync_docinfooverwrite_invalid_xml)r3   )rg   set_pikepdf_as_editorupdate_docinfostricts       rG   open_metadatazExtend_Pdf.open_metadatac  s     .'&,*	
 	
rI   c                    t        | ||      S )N)	max_depthr   )r1   )rg   r   r   s      rG   open_outlinezExtend_Pdf.open_outlinep  s    ty@@rI   c                    t        | ||fi |S rc   )r:   )rg   r   dkwargss       rG   make_streamzExtend_Pdf.make_streams  s    dD!.v..rI   )g      @g     @)	page_sizec                  |D ]$  }d|cxk  rdk  rt        d       t        d       | j                         5  t        t        j                  t        dd|d   |d   g      | j                  d      t                     }| j                  |      }| j                  |d	       t	        |      cd d d        S # 1 sw Y   y xY w)
N   i@8  z/Page size must be between 3 and 14400 PDF unitsr   rN   rI   )TypeMediaBoxContents	ResourcesF)first)	r   r   r7   r8   r$   r6   r   r   	_add_page)rg   r   dim	page_dictpage_objs        rG   add_blank_pagezExtend_Pdf.add_blank_pagev  s      	TC%% !RSS & !RSS	T YY[ 		""YY1ilIaLAB))#.$,	I )))4HNN85N1>		" 		" 		"s   A6B::Cpreserveformsc               &    ddl m}  || |||      S )u;  Append pages from another ``Pdf``, preserving interactive form fields.

        Unlike ``pdf.pages.extend(src.pages)``, this carries the document's
        AcroForm form fields so they remain functional in Adobe Acrobat. Fields
        whose fully-qualified names collide with existing fields are
        automatically renamed; see the returned :class:`pikepdf.PageCopyResult`.
        The original→new name mapping in ``renamed_fields`` is best-effort
        (it pairs source and destination page fields positionally).

        Independent top-level fields are only carried over when a widget is on a
        copied page, so unrelated forms on separate pages are not imported.
        However, a field sharing a top-level ancestor with a copied field is
        carried as an entire subtree; such partially-represented fields are
        listed in the result's ``partial_fields``. Use ``forms='strip'`` for a
        hard guarantee of no form data.

        Named destinations referenced by the copied pages' annotations (such as
        table-of-contents links) are carried into this document, preserving both
        the ``Names.Dests`` name tree and the legacy ``Root.Dests`` dictionary.
        A destination whose target page is not among the copied pages cannot be
        migrated and is reported in :attr:`pikepdf.PageCopyResult.dropped_dests`;
        names that collide with existing destinations are renamed and reported in
        :attr:`pikepdf.PageCopyResult.renamed_dests`.

        Args:
            src: Source ``Pdf`` to copy pages from.
            pages: Zero-based indices (iterable, ``range`` or ``slice``) of
                pages in ``src`` to copy. ``None`` copies all pages.
                A ``slice`` is clamped to the document length; explicit indices
                (including ``range``) must be valid or ``IndexError`` is raised.
            forms: ``'preserve'`` (default) carries form fields; ``'strip'``
                removes widget annotations from the copied pages.

        Returns:
            A :class:`pikepdf.PageCopyResult` describing the operation.
        r   )
copy_pagesr   )pikepdf._page_copyr   )rg   srcr?   r   r   s        rG   add_pages_fromzExtend_Pdf.add_pages_from  s    V 	2$U%88rI   c                t    | j                          t        | dd       r| j                  j                          y y )N_tmp_stream)_closegetattrr   closerf   s    rG   r   zExtend_Pdf.close  s.    4-""$ .rI   c                    | S rc   rp   rf   s    rG   	__enter__zExtend_Pdf.__enter__  s    rI   c                $    | j                          y rc   )r   )rg   exc_type	exc_value	tracebacks       rG   __exit__zExtend_Pdf.__exit__  s    

rI   c                j    i }t         j                  D ]  }t        | d|z         ||<    t        di |S )N_allow_rp   )r2   _fieldsr   )rg   resultsfields      rG   allowzExtend_Pdf.allow  s?     (( 	>E$T9u+<=GEN	>%W%%rI   c                ,    t        | j                        S rc   )r0   _encryption_datarf   s    rG   
encryptionzExtend_Pdf.encryption  s    d3344rI   c                     G d dt               }g }| j                  |        |       }| j                  D ]  }|j                  |        | j	                         D ]  }|j                  d|z           |S )Nc                  *     e Zd Z fdZd Zd Z xZS )5Extend_Pdf.check_pdf_syntax.<locals>.DiscardingParserc                "    t         |           y rc   )super__init__)rg   	__class__s    rG   r  z>Extend_Pdf.check_pdf_syntax.<locals>.DiscardingParser.__init__  s     "rI   c                     y rc   rp   )rg   _argss     rG   handle_objectzCExtend_Pdf.check_pdf_syntax.<locals>.DiscardingParser.handle_object      rI   c                     y rc   rp   rf   s    rG   
handle_eofz@Extend_Pdf.check_pdf_syntax.<locals>.DiscardingParser.handle_eof  r
  rI   )r   r   r   r  r	  r  __classcell__)r  s   @rG   DiscardingParserr    s    #rI   r  z	WARNING: )r(   _decode_all_streams_and_discardr?   parse_contentsget_warningsr@   )rg   progressr  problemsdiscarding_parserrD   warnings          rG   check_pdf_syntaxzExtend_Pdf.check_pdf_syntax  s    	| 	 !,,X6,.JJ 	3D 12	3 ((* 	3GOOK'12	3 rI    )	static_idpreserve_pdfamin_versionforce_versionfix_metadata_versioncompress_streamsstream_decode_levelobject_stream_modenormalize_content	linearizeqdfr  r   recompress_flatedeterministic_idc               l   |st        | dd       r| j                  }|st        d      | j                         }|rt	        d| dt
               t               5 }t        |d      r|}t        |       n~t        |t        t        z  t        z        st        d      t        |      }t        | dd       s#t        | dd       t        | j                  |       |j                  t!        |            }| j#                  |||||||||	|
||||t        | dd       d u ||       d d d        y # 1 sw Y   y xY w)	N_original_filenamea]  Cannot save to original filename because the original file was not opening using Pdf.open(..., allow_overwriting_input=True). Either specify a new destination filename/file stream or open with allow_overwriting_input=True. If this Pdf was created using Pdf.new(), you must specify a destination object since there is no original filename to save to.zThis document has z form widget annotation(s) that are not reachable from /AcroForm; they may not display in Adobe Acrobat. Use Pdf.add_pages_from() to copy pages with forms.rB   )expected str, bytes or os.PathLike objectr   )r  r  r  r  r  r  r  r  r   r!  r"  r  r   samefile_checkr#  r$  )r   r&  r   _count_orphaned_widgetsr   r+   r   hasattrr.   rd   rO   r   r   rs   r-   enter_contextr,   _save)rg   filename_or_streamr  r  r  r  r  r  r  r  r   r!  r"  r  r   r#  r$  orphansstackstreamfilenames                        rG   rA   zExtend_Pdf.save  s]   ( "gd4H$&O!%!8!8!3  ..0$WI .N N  	 [  	E)62+&'9:!"4cEkD6HI#$OPP 23mT:&:DAM)$*A*A8L,,-=h-GHJJ#+'+%9!1$7#5"3#!%&t]DATI!1!1#   	  	  	s   CD**D3decode_leveljson_stream_datafile_prefixc                  |t         j                  k(  r0|s.t        |t        t        z        rt        |      }nt        d      t               5 }t        |d      r|}t        |       nLt        |t        t        z  t        z        st        d      |j                  t        t	        |                  }| j                  ||||       ddd       y# 1 sw Y   yxY w)a  Write this PDF as qpdf JSON (the ``qpdf --json-output`` format, version 2).

        This is the whole-document JSON serialization, distinct from
        :meth:`pikepdf.Object.to_json` which serializes a single object. The output
        can be read back with :meth:`Pdf.from_qpdf_json`.

        Args:
            filename_or_stream: A filename or writable binary stream.
            decode_level: How much to decode (uncompress) stream data in the JSON.
                Use :attr:`StreamDecodeLevel.none` to preserve stream data exactly.
            json_stream_data: How stream data is represented:
                :attr:`JSONStreamData.inline` (base64 in the JSON),
                :attr:`JSONStreamData.file` (written to external files using
                ``file_prefix``), or :attr:`JSONStreamData.none` (omitted).
            file_prefix: Required when ``json_stream_data`` is
                :attr:`JSONStreamData.file`; each stream is written to a file named
                ``{file_prefix}-{object_number}``.
        zsfile_prefix is required when json_stream_data is JSONStreamData.file and a stream (rather than a filename) is givenrB   r'  r2  N)r   filerd   rO   r   r   r   r*  r.   r   rs   r+  r,   _write_qpdf_json)rg   r-  r3  r4  r5  r/  r0  s          rG   write_qpdf_jsonzExtend_Pdf.write_qpdf_json0  s    4 ~222;,cDj9!"45  
 [ 	E)62+&'9:!"4cEkD6HI#$OPP,,-=dCU>V-WX!!)!1'	 " 	 	 	s   A<CCc                    t               5 }t        | d      r| }d| }n&|j                  t        | d            }t	        |       }t        j                  ||      cddd       S # 1 sw Y   yxY w)a  Create a new Pdf from qpdf JSON, as written by :meth:`Pdf.write_qpdf_json`.

        The JSON must be a complete representation of a PDF (``qpdf --json-output``
        version 2 or higher). To merge JSON into an existing Pdf, use
        :meth:`Pdf.update_from_qpdf_json` instead.

        Args:
            filename_or_stream: A filename or readable binary stream containing
                qpdf JSON.
        rC   stream rbdescriptionN)r   r*  r+  openrO   r%   _from_qpdf_json)r-  r/  r0  r>  s       rG   from_qpdf_jsonzExtend_Pdf.from_qpdf_jsonb  ss     [ 	HE)62+ 'x0,,T2Dd-KL!"45&&v;G	H 	H 	Hs   AA&&A/c                    t               5 }t        |d      r|}d| }n&|j                  t        |d            }t	        |      }| j                  ||       ddd       y# 1 sw Y   yxY w)ac  Update this Pdf from qpdf JSON, as written by :meth:`Pdf.write_qpdf_json`.

        Objects present in this Pdf but absent from the JSON are left unchanged.
        See :meth:`Pdf.from_qpdf_json` to create a new Pdf instead.

        Args:
            filename_or_stream: A filename or readable binary stream containing
                qpdf JSON.
        rC   r;  r<  r=  N)r   r*  r+  r?  rO   _update_from_qpdf_json)rg   r-  r/  r0  r>  s        rG   update_from_qpdf_jsonz Extend_Pdf.update_from_qpdf_jsonw  sv     [ 	IE)62+ 'x0,,T2Dd-KL!"45''K'H	I 	I 	Is   AA""A+)passwordhex_passwordignore_xref_streamssuppress_warningsattempt_recoveryinherit_page_attributesaccess_modeallow_overwriting_inputc                  t        | t              r| j                  d      rt        d       t        | t        t
        z        rt        d      d }	d}
d }|ri	 t        |        t        |       }t        |d      5 }t               }	t        j                  ||	       |	j                  d       d d d        t        |      }nDt        | d      rt        | d	      r| }	d
|	 }n$t        | d      }	t        |       }t        |       }d}
	 t!        |	       t#        j$                  |	|||||||||

      }|r|	nd |_        ||_        |S # t        $ r}t        d      |d }~ww xY w# 1 sw Y   xY w# t&        $ r |	|
r|	j)                           w xY w)Ns   %PDF-zIt looks like you called with Pdf.open(data) with a bytes-like object containing a PDF. This will probably fail because this function expects a filename or opened file-like object. Instead, please use Pdf.open(BytesIO(data)).r'  FzO"allow_overwriting_input=True" requires "open" first argument to be a file pathr<  r   rC   rB   r;  T)	rE  rF  rG  rH  rI  rJ  rK  r>  closing_stream)rd   r   
startswithr   r   r   rs   r   r   r?  r   shutilcopyfileobjrB   rO   r*  r.   r%   _open	Exceptionr   r   r&  )r-  rE  rF  rG  rH  rI  rJ  rK  rL  r0  rN  original_filenameerrorpdf_filer>  rE   s                   rG   r?  zExtend_Pdf.open  s    (%05G5R5R6
 + (#+6 GHH"&$)-"'( !%%7 8'. ( ""8V4A
 /0K'0W6
 (F#F8,K,d3F $%7 801K!N	"6*))!)$7"3!1(?''-C  %<&!2
W   (  >  	!n	s0   E :2E *E, 	EEE E),FNNr   r7   )r   r7   )TTF)r   r   r   r   r   r   r   r3   )   F)r   r   r   r   r   r1   rc   )r   r   r   r:   )r   ztuple[Numeric, Numeric]r   r$   )r   r%   r?   z$Iterable[int] | range | slice | Noner   zLiteral['preserve', 'strip']r   r   r   None)r   r2   )r   r0   )r  Callable[[int], None] | Noner   z	list[str])"r-  zPath | str | BinaryIO | Noner  r   r  r   r  str | tuple[str, int]r  r]  r  r   r  r   r  zStreamDecodeLevel | Noner  r"   r   r   r!  r   r"  r   r  r\  r   zEncryption | bool | Noner#  r   r$  r   r   r[  )
r-  Path | str | BinaryIOr3  r'   r4  r   r5  rO   r   r[  )r-  r^  r   r%   )r-  r^  r   r[  )r-  r^  rE  zstr | bytesrF  r   rG  r   rH  r   rI  r   rJ  r   rK  r   rL  r   r   r%   )$r   r   r   r   r   r   r   propertyr   setterdeleterr   r   r   r   r   r   r   r   r   r   r  r"   r   rA   r'   generalizedr   inliner9  staticmethodrA  rD  r   r   r?  rp   rI   rG   r   r   '  sV   ! !  % % ^^, , __& & '+#	
#
 
 	

 

A/ 7E"3"	"* 7;-9
 /9-9-9 4-9
 ,-9 
-9^%
 & & 5 5 8<4	8 <@G  "-//1%)!%8</?/H/H"'15/3!&!&%G8G 	G
 G +G -G #G G 6G -G  G G G /G  -!G" #G$ %G& 
'GZ +<*G*G+9+@+@010 (	0
 )0 0 
0d H H(I&  !#"$)"&!%(,","4"4(-L1L L 	L
 "L  L L "&L  L "&L 
L LrI   r   c                  :    e Zd ZdddZedd       Zedd       Zy)	Extend_ObjectMappingNc                0    	 | |   S # t         $ r |cY S w xY wrc   )KeyError)rg   keyr   s      rG   getzExtend_ObjectMapping.get  s%    	9 	N	s    c                d    t        |t              rt        |      }t        j                  | |      S rc   )rd   r8   rO   r*   _cpp__contains__rg   ri  s     rG   __contains__z!Extend_ObjectMapping.__contains__  s(    c4 c(C..tS99rI   c                d    t        |t              rt        |      }t        j                  | |      S rc   )rd   r8   rO   r*   _cpp__getitem__rm  s     rG   __getitem__z Extend_ObjectMapping.__getitem__  s(    c4 c(C--dC88rI   rc   )r   zT | Noner   zObject | T | None)ri  
Name | strr   r   )ri  rr  r   r9   )r   r   r   rj  r   rn  rq  rp   rI   rG   rf  rf    s/     : :
 9 9rI   rf  c                    t        t              5  | j                  r
	 d d d        y 	 d d d        	 t        |       }|j                  ry 	 t        d      # 1 sw Y   .xY w# t        $ r}t        d      |d }~ww xY w)Nzobject is not a rectangle)r   AttributeErroris_rectangler6   rS  r   )objpdfobjes      rG   check_is_boxry    s    	.	!  =s  0
11   =451<=s"   AA! A!	A;*A66A;c                  b   e Zd Zed        Zej
                  d        Zed        Zej
                  d        Zed        Zej
                  d        Zed        Zej
                  d        Zed	        Z	e	j
                  d
        Z	ed#d       Z
e
j
                  d$d       Z
eddd%d       Zed&d       Zd'd(dZed&d       Zed)d       Z	 d*ddd	 	 	 	 	 	 	 	 	 	 	 d+dZ	 	 	 	 	 	 	 	 	 	 	 	 d,dZ	 d*dddd	 	 	 	 	 	 	 	 	 	 	 d-dZ	 d*ddd	 	 	 	 	 	 	 	 	 d.dZddd/dZd*d0d Zd! Zd1d"Zy)2Extend_Pagec                $    | j                  d      S )NT)_get_mediaboxrf   s    rG   mediaboxzExtend_Page.mediabox  s    !!$''rI   c                8    t        |       || j                  d<   y )Nz	/MediaBoxry  rv  rg   values     rG   r~  zExtend_Page.mediabox      U %rI   c                &    | j                  dd      S NTF)_get_artboxrf   s    rG   artboxzExtend_Page.artbox  s    e,,rI   c                8    t        |       || j                  d<   y )Nz/ArtBoxr  r  s     rG   r  zExtend_Page.artbox  s    U#rI   c                &    | j                  dd      S r  )_get_bleedboxrf   s    rG   bleedboxzExtend_Page.bleedbox  s    !!$..rI   c                8    t        |       || j                  d<   y )Nz	/BleedBoxr  r  s     rG   r  zExtend_Page.bleedbox  r  rI   c                &    | j                  dd      S r  )_get_cropboxrf   s    rG   cropboxzExtend_Page.cropbox        u--rI   c                8    t        |       || j                  d<   y )Nz/CropBoxr  r  s     rG   r  zExtend_Page.cropbox      U$rI   c                &    | j                  dd      S r  )_get_trimboxrf   s    rG   trimboxzExtend_Page.trimbox"  r  rI   c                8    t        |       || j                  d<   y )Nz/TrimBoxr  r  s     rG   r  zExtend_Page.trimbox&  r  rI   c                "    | j                         S )a  The page's clockwise rotation in degrees, normalized to ``[0, 360)``.

        Unlike the raw ``page.Rotate`` attribute, this property reports the
        *effective* rotation: it resolves a ``/Rotate`` value inherited from the
        page tree and reports ``0`` when no rotation is set, instead of raising.
        Assigning to this property sets the absolute rotation; to rotate
        relative to the current value, use :meth:`rotate` with ``relative=True``.

        .. versionadded:: 10.9
        )_get_rotationrf   s    rG   rotationzExtend_Page.rotation+  s     !!##rI   c                *    | j                  |d       y )NFrelative)rotate)rg   angles     rG   r  zExtend_Page.rotation9  s    EE*rI   Fr  c                  |r@t        |      dkD  rt        ddt        |      z    d      t        dt        d       |d   }| j	                  |t        |             y)	a  Rotate this page.

        If ``relative`` is ``False`` (the default), set the page's rotation to
        ``angle``. If ``relative`` is ``True``, add ``angle`` to the page's
        current rotation. ``angle`` must be a multiple of ``90``; a positive
        angle rotates the page clockwise.

        Args:
            angle: Rotation angle in degrees, a multiple of ``90``.
            relative: If ``True``, add ``angle`` to the current rotation; if
                ``False``, set the rotation to ``angle``.

        .. deprecated:: 10.9
            Passing ``relative`` as a positional argument is deprecated; pass it
            as a keyword argument instead, e.g. ``page.rotate(90, relative=True)``.
        rN   z2rotate() takes at most 2 positional arguments but z were givenzPassing 'relative' as a positional argument to Page.rotate() is deprecated; pass it as a keyword argument instead, e.g. page.rotate(90, relative=True). Positional support will be removed in pikepdf 11.   
stacklevelr   N)r   rs   r   DeprecationWarning
_cpprotater   )rg   r  r  argss       rG   r  zExtend_Page.rotate=  sj    * 4y1}H3t9}o[2  ) # AwHtH~.rI   c                >    t        dt        d       | j                  S )a  Return images directly referenced by this page's resources.

        .. deprecated:: 10.9
            Use :meth:`get_images` instead. This property reports only images
            referenced directly by the page and silently omits images nested
            inside form XObjects. Because it is not visually obvious when a page's
            content is wrapped in a form XObject, this often appears as if a page
            "has no images" when it clearly does. :meth:`get_images` recurses into
            form XObjects by default.
        zPage.images is deprecated and will be removed in a future version. Use Page.get_images() instead, which by default also finds images nested inside form XObjects.r  r  )r   r  _imagesrf   s    rG   imageszExtend_Page.imagesc  s%     	+ 	
 ||rI   Tc                6    |r| j                   S | j                  S )aW  Return the images used by this page.

        Args:
            recursive: If True (the default), also report images nested inside
                form XObjects referenced by this page, recursing to any depth.
                This is usually what you want, since a page's visible content is
                often drawn entirely through one or more form XObjects. If two
                images in different XObject scopes happen to share a resource
                name, only one of them is reported. If False, report only images
                referenced directly by this page's resources.
        )_images_recursiver  )rg   	recursives     rG   
get_imageszExtend_Page.get_imagesx  s     )))||rI   c                    | j                   S rc   )_form_xobjectsrf   s    rG   form_xobjectszExtend_Page.form_xobjects  s    """rI   c                "   t         j                  | j                  vr/t               | j                  _        | j                  j                  S t	        | j                  j                  t              st        d      | j                  j                  S )Nz.Page /Resources exists but is not a dictionary)r8   r   rv  r7   rd   rs   rf   s    rG   	resourceszExtend_Page.resources  sd    >>)!+DHH xx!!! DHH..
;LMMxx!!!rI   Nr  )prefixreplace_existingc               j   | j                   }||vrt               ||<   ||rt        d      |t        j                  |      }|j                         j                         D ],  }t        |t              s||v s|r||= t        d| d       |j                  | j                        ||   |<   |S )Nz$Must specify one of name= or prefix=)r  zName z" already exists in page /Resources)
r  r7   r   r8   randomas_dictvaluesrd   with_same_owner_asrv  )rg   resres_typerQ   r  r  r  res_dicts           rG   add_resourcezExtend_Page.add_resource  s     NN	9$",,IhCDD<;;f-D!))+224 	WHh
3x# $uTF2T%UVV	W %($:$:488$D	(D!rI   c                .   d }t        |t              r|j                         }nt        |t              rJ|j	                  t
        j                        t
        j                  k(  rt        |      j                         }nrt        |t              rb|j	                  t
        j                        t
        j                  k(  r2|j	                  t
        j                        t
        j                  k(  r|}|t        d      |t        | j                        }| j                  |t
        j                        }| j                  |||||      }	|r&| j!                  dd       | j!                  dd       | j!                  |	|       | j#                          |S )Nz<other object is not something we can convert to Form XObject)allow_shrinkallow_expands   q
Tprepends   Q
F)rd   r$   as_form_xobjectr7   rj  r8   r   r:   XObjectSubtypeFormrs   r&   r  r  calc_form_xobject_placementcontents_addcontents_coalesce)
rg   rw   rectunder
push_stackshrinkexpandformxformx_placed_namecss
             rG   _over_underlayzExtend_Page._over_underlay  sH    eT"))+Ez*uyy/Ctyy/PK//1Euf%		$))$4		$,,'4994E=N  <T\\*D --eT\\B--$df . 
 fd3fe4"e,   rI   )r  r  r  c               0    | j                  ||d|||      S )NFr  r  r  r  r  )rg   rw   r  r  r  r  s         rG   add_overlayzExtend_Page.add_overlay  s.     ""! # 
 	
rI   )r  r  c               0    | j                  ||dd||      S )NTFr  r  )rg   rw   r  r  r  s        rG   add_underlayzExtend_Page.add_underlay  s)     ""4tfV # 
 	
rI   r  c               (    | j                  ||      S )Nr  )_contents_add)rg   contentsr  s      rG   r  zExtend_Page.contents_add  s    !!(G!<<rI   c                v    |t         j                  f}| j                  j                  |j                  |      S )N)rx   )r8   rt   rv  r|   )rg   rw   rx   s      rG   r|   zExtend_Page.emplace  s2     >kk^Fxx		&99rI   c                p    t        | j                        j                  ddd      j                  ddd      S )Nr7   r$   rN   z(Type="/Page")r  )r   rv  replacerf   s    rG   __repr__zExtend_Page.__repr__  s/    NW\61-W%r1-	
rI   c                B   i }ddh}|r|D ch c]	  }||v s| }}|r|D ch c]	  }||vs| }}t        |       }d|v r||d<   d|v r=t        t        t              5  t	        |d      j                  d      |d<   d d d        |S |S c c}w c c}w # 1 sw Y   |S xY w)Nr   r   r   r   )rH   r   rT   r   r_   r   )rg   r   r   r   bundlerl   pagedatas          rG   r   zExtend_Page._repr_mimebundle_  s    #_5!'8A1<a8F8!'<A1G+;a<F<#D)&&.D"#f$+\: Q(/%(@(G(G(P_%Qt 9<
Qs    	B
B
	BBBB)r   r   )r  r   r   r[  )r  r   r  r   r  r   r   r[  )r   r*   )T)r  r   r   r*   rX  rc   )r  r9   r  r8   rQ   Name | Noner  rO   r  r   r   r8   )r  Rectangle | Noner  r   r  r   r  r   r  r   r   r8   )rw   Object | Pager  r  r  r   r  r   r  r   r   r8   )
rw   r  r  r  r  r   r  r   r   r8   )r  zStream | bytesr  r   )rw   r$   rx   r   rW  )r   r   r   r_  r~  r`  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r  r  r|   r  r   rp   rI   rG   r{  r{    s   ( ( __& & - - ]]$ $ / / __& & . . ^^% % . . ^^% % $ $ __+ + BG #/ #/J  (  # # " " !	 !%  	   
<(! (! 	(!
 (! (! (! 
(!Z "&

  

 

 
 
 
 

* "&


 



 


 

 

 


 IN =:
rI   r{  c                      e Zd Zd Zy)Extend_Tokenc                <    d| j                    d| j                   dS )Nzpikepdf.Token(, ))type_	raw_valuerf   s    rG   r  zExtend_Token.__repr__  s     

|2dnn-=Q??rI   N)r   r   r   r  rp   rI   rG   r  r    s    @rI   r  c                       e Zd Zd Zd ZddZy)Extend_Rectanglec           	     p    d| j                    d| j                   d| j                   d| j                   d	S )Nzpikepdf.Rectangle(r  r  )llxllyurxuryrf   s    rG   r  zExtend_Rectangle.__repr__#  s4    #DHH:RzDHH:RzQRSSrI   c                p    t        | j                  | j                  | j                  | j                  f      S rc   )hashr  r  r  r  rf   s    rG   __hash__zExtend_Rectangle.__hash__&  s&    TXXtxx488<==rI   c                F    t        dd| j                  | j                        S )a)  Returns the origin-centred bounding box that encloses this rectangle.

        Create a new rectangle with the same width and height as this one, but located
        at the origin (0, 0).

        Bounding boxes represent independent coordinate systems, such as for Form
        XObjects.
        r   )r&   widthheightrf   s    rG   to_bboxzExtend_Rectangle.to_bbox)  s     Atzz4;;77rI   N)r   r&   )r   r   r   r  r  r  rp   rI   rG   r  r  !  s    T>	8rI   r  c                  8    e Zd ZddZd	dZd
dZd ZddZd Zy)Extend_Attachmentsc                B    | j                  |      }|t        |      |S rc   )_get_filespecrh  )rg   rl   filespecs      rG   rq  zExtend_Attachments.__getitem__7  s'    %%a(1+rI   c                    t        |t              r| j                  ||      S |j                  s||_        | j	                  ||      S rc   )rd   r   _attach_datar1  _add_replace_filespec)rg   rl   vs      rG   __setitem__zExtend_Attachments.__setitem__=  s@    a$$Q**zzAJ))!Q//rI   c                $    | j                  |      S rc   )_remove_filespec)rg   rl   s     rG   __delitem__zExtend_Attachments.__delitem__D  s    $$Q''rI   c                4    t        | j                               S rc   )r   _get_all_filespecsrf   s    rG   __len__zExtend_Attachments.__len__G  s    4**,--rI   c              #  @   K   | j                         E d {    y 7 wrc   )r  rf   s    rG   __iter__zExtend_Attachments.__iter__J  s     **,,,s   c                     dt        |        dS )Nz<pikepdf._core.Attachments: >)r   rf   s    rG   r  zExtend_Attachments.__repr__M  s    -d4j\;;rI   N)rl   rO   r   r   )rl   rO   r  zAttachedFileSpec | bytesr   r[  )rl   rO   r   r[  )r   zIterator[str])	r   r   r   rq  r  r  r	  r  r  rp   rI   rG   r  r  5  s     0(.-<rI   r  c                  r    e Zd Zeddd	 	 	 	 	 	 	 dd       Zed	d       Zej                  d
d       Zd Zy)Extend_AttachedFileSpecr  N)r>  relationshipc                  |t         j                  }t        j                  t	        |            \  }}|d}t        |t              st        |      }|j                         }t        | |j                         |t	        |j                        |t        t        j                  j                  |j                              t        t        j                  j                  |j                              |      S )Nr  )r>  r1  	mime_typecreation_datemod_dater  )r8   Unspecified	mimetypes
guess_typerO   rd   r   statr   r[   rQ   r5   datetimefromtimestampst_ctimest_mtime)rE   pathr>  r  mime_r  s          rG   from_filepathz%Extend_AttachedFileSpec.from_filepathS  s     ++L&&s4y1a<D$%:Dyy{OO#^)!!//> %X%6%6%D%DT]]%ST%
 	
rI   c                T    | j                   j                  t        j                        S rc   )rv  rj  r8   AFRelationshiprf   s    rG   r  z$Extend_AttachedFileSpec.relationships  s    xx||D//00rI   c                z    || j                   t        j                  = y || j                   t        j                  <   y rc   )rv  r8   r"  r  s     rG   r  z$Extend_AttachedFileSpec.relationshipw  s-    =,,-,1DHHT(()rI   c                t    | j                   rd| j                   d| j                  dS d| j                  dS )Nz$<pikepdf._core.AttachedFileSpec for z, description r  z,<pikepdf._core.AttachedFileSpec description )r1  r>  rf   s    rG   r  z Extend_AttachedFileSpec.__repr__~  sL    ==6t}}6G H#//2!5 >d>N>N=QQRSSrI   )rE   r%   r  z
Path | strr>  rO   r  r  )r   r  )r  r  )	r   r   r   rd  r   r_  r  r`  r  rp   rI   rG   r  r  Q  st    
 $(


 	

 "
 
> 1 1 2 2TrI   r  c                      e Zd Zedd       Zej
                  d	d       Zedd       Zej
                  d	d       Zd
dZd Zy)Extend_AttachedFilec                F    | j                   sy t        | j                         S rc   )_creation_dater4   rf   s    rG   r  z!Extend_AttachedFile.creation_date  s    ""t2233rI   c                $    t        |      | _        y rc   )r5   r(  r  s     rG   r  z!Extend_AttachedFile.creation_date  s    -e4rI   c                F    | j                   sy t        | j                         S rc   )	_mod_dater4   rf   s    rG   r  zExtend_AttachedFile.mod_date  s    ~~t~~..rI   c                $    t        |      | _        y rc   )r5   r+  r  s     rG   r  zExtend_AttachedFile.mod_date  s    (/rI   c                6    | j                   j                         S rc   )rv  r[   rf   s    rG   r[   zExtend_AttachedFile.read_bytes  s    xx""$$rI   c                    d| j                   j                   d| j                   d| j                   d| j                   d| j
                   dS )Nz"<pikepdf._core.AttachedFile objid=z size=z mime_type=z creation_date=z
 mod_date=r  )rv  objgensizer  r  r  rf   s    rG   r  zExtend_AttachedFile.__repr__  sT    00A		{ S(8J8J7K La)	
rI   N)r   zdatetime.datetime | None)r  zdatetime.datetime)r   r   )	r   r   r   r_  r  r`  r  r[   r  rp   rI   rG   r&  r&    sd    4 4
 5 5 / /
 __0 0%
rI   r&  c                      e Zd Zd Zd Zd Zej                  Zej                  Zej                  Z	ej                  Z
ej                  Zej                  Zy)Extend_NameTreec                4    t        | j                               S rc   r   _as_maprf   s    rG   re   zExtend_NameTree.keys      ''rI   c                4    t        | j                               S rc   r
   r5  rf   s    rG   r  zExtend_NameTree.values      $,,.))rI   c                4    t        | j                               S rc   r   r5  rf   s    rG   itemszExtend_NameTree.items      ((rI   Nr   r   r   re   r  r<  r	   rj  poppopitemclearupdate
setdefaultrp   rI   rG   r2  r2    U    (*) 

C


C$$G  E""F**JrI   r2  c                      e Zd Zd Zd Zd Zej                  Zej                  Zej                  Z	ej                  Z
ej                  Zej                  Zy)Extend_NumberTreec                4    t        | j                               S rc   r4  rf   s    rG   re   zExtend_NumberTree.keys  r6  rI   c                4    t        | j                               S rc   r8  rf   s    rG   r  zExtend_NumberTree.values  r9  rI   c                4    t        | j                               S rc   r;  rf   s    rG   r<  zExtend_NumberTree.items  r=  rI   Nr>  rp   rI   rG   rF  rF    rD  rI   rF  )rD   r$   r   r   )rU   r   rV   r   r   r   )r\   zbytes | memoryviewr]   zLiteral['svg']r   r   rZ  )e__doc__
__future__r   r  r  rP  collections.abcr   r   r   r   r   r	   r
   
contextlibr   r   r   decimalr   ior   pathlibr   
subprocessr   tempfiler   typingr   r   r   r   warningsr   r   r   pikepdf._augmentsr   r   pikepdf._corer   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   pikepdf._exceptionsr+   pikepdf._ior,   r-   r.   pikepdf.modelsr/   r0   r1   r2   pikepdf.models.metadatar3   r4   r5   pikepdf.objectsr6   r7   r8   r9   r:   __all__r   r   r;   r<   objectr   rH   rX   r_   ra   r   rf  ry  r{  r  r  r  r  r&  r2  registerrF  rp   rI   rG   <module>r_     sE   #      ; :     ' < < 1 <    $ 0 W W K K Q Q C C
 
)S%
1CL 8% 
&s/ s/ s/l 
#o o od 
.9 9 9(
2 
$[ [ [| 
%@ @ @
 
)8 8 8& 
+< < <6 

2T 2T 2Tj 
,
 
 
@ 
(+ + +$    ! 
*+ + +$   
 #rI   