o
     Zh                    @   s  d dl 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mZmZmZmZmZmZmZmZmZmZ ddlmZmZmZmZmZ dd	lmZ dd
l m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'm(Z(m)Z)m*Z*m+Z+m,Z, ddl-m.Z/ ddl-m0Z1 ddl-m2Z3 ddl-m4Z5 ddl6m7Z7m8Z8 ddl9m:Z: ddl;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZI z
d dlJmKZK dZLW n eMy   eNZKdZLY nw dZOde
dePdeeP deFfddZQde
dePdeeFeRf ddfddZSde
dePddfd d!ZTdePd"eeP deUfd#d$ZVG d%d& d&ZWeG d'd( d(ZXG d)d* d*eeX ZYG d+d, d,e>ZZG d-d. d.eeZ Z[d/e>d0eeP d1eeP deeeP eeP f fd2d3Z\dS )4    N)	dataclass)Decimal)BytesIO)Path)AnyCallableDictIterableIteratorListLiteralOptionalSequenceSetTupleUnioncastoverload   )build_char_mapbuild_font_width_mapcompute_font_widthget_actual_str_keyunknown_char_map)PdfCommonDocProtocol)OrientationNotFoundError_layout_modecrlf_space_checkget_display_strget_text_operandsmult)CompressedTransformationMatrixTransformationMatrixType_human_readable_byteslogger_warningmatrix_multiply)AnnotationDictionaryAttributes)ImageAttributes)PageAttributes)	Resources)PageSizeNotDefinedErrorPdfReadError_xobj_to_image)ArrayObjectContentStreamDictionaryObjectEncodedStreamObjectFloatObjectIndirectObject
NameObject
NullObjectNumberObject	PdfObjectRectangleObjectStreamObjectTextStringObjectis_null_or_none)ImageFTcropboxselfnamedefaultsreturnc                 C   sn   |  |}t|tr|S t|r |D ]}|  |}|d ur nqt|tr+| j|}t|}t| || |S N)get
isinstancer8   r;   r3   pdf
get_object_set_rectangle)r>   r?   r@   retvald rJ   B/var/www/html/lang_env/lib/python3.10/site-packages/pypdf/_page.py_get_rectanglem   s   



rL   valuec                 C   s   t |}|| |< d S rB   r4   )r>   r?   rM   rJ   rJ   rK   rG   }   s   rG   c                 C   s
   | |= d S rB   rJ   )r>   r?   rJ   rJ   rK   _delete_rectangle      
rO   fallbackc                    s&   t  fddfddfddS )Nc                    s   t |  S rB   )rL   r>   rQ   r?   rJ   rK   <lambda>       z,_create_rectangle_accessor.<locals>.<lambda>c                    s   t |  |S rB   )rG   r>   rM   r?   rJ   rK   rT      rU   c                    s
   t |  S rB   )rO   rR   rW   rJ   rK   rT      s   
 )property)r?   rQ   rJ   rS   rK   _create_rectangle_accessor   s
   

rY   c                
   @   sD  e Zd ZdZd%deddfddZedefdd	Ze	d
edefddZ
d&ddZd'dededd fddZ	d(dee dee dd fddZdedd fddZdefddZed)dee d edee fd!d"Ze	d)deeef d edeeef fd#d"Z	d)deeeef ee f d edeeeef ee f fd$d"ZdS )*Transformationu  
    Represent a 2D transformation.

    The transformation between two coordinate systems is represented by a 3-by-3
    transformation matrix with the following form::

        a b 0
        c d 0
        e f 1

    Because a transformation matrix has only six elements that can be changed,
    it is usually specified in PDF as the six-element array [ a b c d e f ].

    Coordinate transformations are expressed as matrix multiplications::

                                 a b 0
     [ x′ y′ 1 ] = [ x y 1 ] ×   c d 0
                                 e f 1


    Example:
        >>> from pypdf import Transformation
        >>> op = Transformation().scale(sx=2, sy=3).translate(tx=10, ty=20)
        >>> page.add_transformation(op)

    r   r   r   r   r   r   ctmrA   Nc                 C   s
   || _ d S rB   r\   )r>   r\   rJ   rJ   rK   __init__   rP   zTransformation.__init__c                 C   s@   | j d | j d df| j d | j d df| j d | j d dffS )z
        Return the transformation matrix as a tuple of tuples in the form:

        ((a, b, 0), (c, d, 0), (e, f, 1))
        r   r               r]   rR   rJ   rJ   rK   matrix   s   zTransformation.matrixrc   c                 C   s@   | d d | d d | d d | d d | d d | d d fS )a  
        Compresses the transformation matrix into a tuple of (a, b, c, d, e, f).

        Args:
            matrix: The transformation matrix as a tuple of tuples.

        Returns:
            A tuple representing the transformation matrix as (a, b, c, d, e, f)

        r   r   r_   rJ   )rc   rJ   rJ   rK   compress   s   





zTransformation.compressmc                 C   s   t t| j|j}t |S )a  
        Apply one transformation to another.

        Args:
            m: a Transformation to apply.

        Returns:
            A new ``Transformation`` instance

        Example:
            >>> from pypdf import Transformation
            >>> op = Transformation((1, 0, 0, -1, 0, height)) # vertical mirror
            >>> op = Transformation().transform(Transformation((-1, 0, 0, 1, width, 0)))  # horizontal mirror
            >>> page.add_transformation(op)

        )rZ   rd   r%   rc   )r>   re   r\   rJ   rJ   rK   	transform   s   zTransformation.transformr   txtyc                 C   s<   | j }t|d |d |d |d |d | |d | fdS )z
        Translate the contents of a page.

        Args:
            tx: The translation along the x-axis.
            ty: The translation along the y-axis.

        Returns:
            A new ``Transformation`` instance

        r   r   r_   r`   ra   rb   r]   )r\   rZ   )r>   rg   rh   re   rJ   rJ   rK   	translate   s   6zTransformation.translatesxsyc                 C   sx   |du r|du rt d|du r|}|du r|}|dusJ |dus$J |ddfd|dfdf}tt| j|}t|S )a  
        Scale the contents of a page towards the origin of the coordinate system.

        Typically, that is the lower-left corner of the page. That can be
        changed by translating the contents / the page boxes.

        Args:
            sx: The scale factor along the x-axis.
            sy: The scale factor along the y-axis.

        Returns:
            A new Transformation instance with the scaled matrix.

        Nz!Either sx or sy must be specifiedr   r   r   r   )
ValueErrorrZ   rd   r%   rc   )r>   rj   rk   opr\   rJ   rJ   rK   scale   s   zTransformation.scalerotationc                 C   sT   t |}t |t |dft | t |dfdf}tt| j|}t|S )z
        Rotate the contents of a page.

        Args:
            rotation: The angle of rotation in degrees.

        Returns:
            A new ``Transformation`` instance with the rotated matrix.

        r   rl   )mathradianscossinrZ   rd   r%   rc   )r>   rp   rn   r\   rJ   rJ   rK   rotate  s   
zTransformation.rotatec                 C   s   d| j  dS )NzTransformation(ctm=)r]   rR   rJ   rJ   rK   __repr__#  s   zTransformation.__repr__Fpt	as_objectc                 C      d S rB   rJ   r>   rx   ry   rJ   rJ   rK   apply_on&     zTransformation.apply_onc                 C   rz   rB   rJ   r{   rJ   rJ   rK   r|   *  s   c                 C   s   |rt nt}|t|d | jd  t|d | jd   | jd  |t|d | jd  t|d | jd   | jd  f}t|trIt|S |S )a^  
        Apply the transformation matrix on the given point.

        Args:
            pt: A tuple or list representing the point in the form (x, y).
            as_object: If True, return items as FloatObject, otherwise as plain floats.

        Returns:
            A tuple or list representing the transformed point in the form (x', y')

        r   r   r_   ra   r`   rb   )r2   floatr\   rD   list)r>   rx   ry   typpt1rJ   rJ   rK   r|   0  s
   88)r[   )re   rZ   rA   rZ   )r   r   NNF)__name__
__module____qualname____doc__r!   r^   rX   r"   rc   staticmethodrd   rf   r~   ri   r   ro   ru   strrw   r   r   boolr|   r   r   rJ   rJ   rJ   rK   rZ      sL    

"

rZ   c                   @   s   e Zd ZU dZdZeed< 	 dZeed< 	 dZ	e
e ed< 	 dZe
e ed< 	 d	ed
eddfddZdefddZdefddZdS )	ImageFilez
    Image within the PDF file. *This object is not designed to be built.*

    This object should not be modified except using :func:`ImageFile.replace` to replace the image with a new one.
     r?       dataNimageindirect_reference	new_imagekwargsrA   c                 K   s8  t rtdddlm} ddlm} ddlm}m} | j	du r#t
dt| j	jds.t
d	t|ts7t
d
t }|j|dfi | ||}|jd jd j	dusUJ |jd jd j	 | j	jj| j	jd < | j	t|| j	 _	|t|| j	 \}	}
}|	dusJ | jd| jd |	 | _|
| _|| _dS )a  
        Replace the image with a new PIL image.

        Args:
            new_image (PIL.Image.Image): The new PIL image to replace the existing image.
            **kwargs: Additional keyword arguments to pass to `Image.save()`.

        Raises:
            TypeError: If the image is inline or in a PdfReader.
            TypeError: If the image does not belong to a PdfWriter.
            TypeError: If `new_image` is not a PIL Image.

        Note:
            This method replaces the existing image with a new image.
            It is not allowed for inline images or images within a PdfReader.
            The `kwargs` parameter allows passing additional parameters
            to `Image.save()`, such as quality.

        z]pillow is required to do image extraction. It can be installed via 'pip install pypdf[image]'r   )	PdfReaderr,   )r0   r7   NzCannot update an inline image.Z_id_translatedz4Cannot update an image not belonging to a PdfWriter.znew_image shall be a PIL ImageZPDFr   .)pil_not_importedImportError_readerr   filtersr-   genericr0   r7   r   	TypeErrorhasattrrE   rD   r<   r   savepagesimagesrF   _objectsidnumr   r?   rfindr   r   )r>   r   r   r   r-   r0   r7   breader	extensionbyte_streamimgrJ   rJ   rK   replaced  s>   




zImageFile.replacec                 C   s&   | j j d| j dtt| j dS )Nz(name=z, data: rv   )	__class__r   r?   r#   lenr   rR   rJ   rJ   rK   __str__  s   &zImageFile.__str__c                 C   s"   |   d d dt| j d S )Nz, hash: rv   )r   hashr   rR   rJ   rJ   rK   rw     s   "zImageFile.__repr__)r   r   r   r   r?   r   __annotations__r   bytesr   r   r<   r   r3   r   r   r   rw   rJ   rJ   rJ   rK   r   H  s   
 9r   c                	   @   s>  e Zd ZdZdeg eeeee f  f deeeee ee f ge	f ddfddZ
defdd	Zdeeeee f  fd
dZdeeeeee f e	f  fddZedeeeee f de	fddZededee	 fddZdeeeeee ee f dee	ee	 f fddZdee	 fddZdefddZdS )VirtualListImagesz
    Provides access to images referenced within a page.
    Only one copy will be returned if the usage is used on the same page multiple times.
    See :func:`PageObject.images` for more details.
    ids_functionget_functionrA   Nc                 C      || _ || _d| _d S Nr   )r   r   current)r>   r   r   rJ   rJ   rK   r^        
zVirtualListImages.__init__c                 C   s   t |  S rB   )r   r   rR   rJ   rJ   rK   __len__  s   zVirtualListImages.__len__c                 C      |   S rB   r   rR   rJ   rJ   rK   keys     zVirtualListImages.keysc                    s    fdd   D S )Nc                    s   g | ]}| | fqS rJ   rJ   .0xrR   rJ   rK   
<listcomp>      z+VirtualListImages.items.<locals>.<listcomp>r   rR   rJ   rR   rK   items  s   zVirtualListImages.itemsindexc                 C   rz   rB   rJ   r>   r   rJ   rJ   rK   __getitem__  r}   zVirtualListImages.__getitem__c                 C   rz   rB   rJ   r   rJ   rJ   rK   r     r}   c                    s   |    t|tr)t|t|  } fdd|D  t| }| fdd| jS t|tt	t
fr6| |S t|ts?tdt }|dk rK||7 }d|  krX|k s]td td|  | S )Nc                    s   g | ]} | qS rJ   rJ   r   lstrJ   rK   r         z1VirtualListImages.__getitem__.<locals>.<listcomp>c                      s    S rB   rJ   rJ   r   rJ   rK   rT     s    z/VirtualListImages.__getitem__.<locals>.<lambda>zInvalid sequence indices typer   Sequence index out of range)r   rD   slicerangeindicesr   typer   r   r   tupleintr   
IndexError)r>   r   r   clslen_selfrJ   r   rK   r     s$   


c                 c   "    t t| D ]}| | V  qd S rB   r   r   r>   irJ   rJ   rK   __iter__     zVirtualListImages.__iter__c                 C   (   dd t |  D }dd| dS )Nc                 S   s    g | ]\}}d | d| qS )ZImage_=rJ   )r   r   nrJ   rJ   rK   r     s     z-VirtualListImages.__str__.<locals>.<listcomp>[, ])	enumerater   joinr>   prJ   rJ   rK   r        zVirtualListImages.__str__)r   r   r   r   r   r   r   r   r   r   r^   r   r   r   r   r   r   r   r   r
   r   r   rJ   rJ   rJ   rK   r     s.    
	&"
r   c                       s  e Zd ZU dZd ed< 		ddee dee ddfddZde	fd	d
Z
def fddZedefddZe			ddee deeedf deeedf dd fddZ			ddee deee  deee  deeeee f  fddZ	ddeeee ee f dee defddZedefddZdededefdd Zde eef fd!d"Z!ede	fd#d$Z"e"j#d%eddfd&d$Z"dd'd(Z$d)e	dd fd*d+Z%	,dd-ed.ed/ed0e&dee eef e eef f f
d1d2Z'ed3e(d4e eef dee de(fd5d6Z)ed7edee d8e*de(fd9d:Z+dee fd;d<Z,dee( fd=d>Z-d?ede(e.e/f ddfd@dAZ0	,ddCd dDe&dEe&ddfdFdGZ1			,	BddCd dHee2ege(f  d8ee* dEe&dDe&ddfdIdJZ3			,	BddCd dHee2ege(f  d8ee* dEe&dDe&ddfdKdLZ4dCd d8ee* ddfdMdNZ5	,	BddCd d8ee*e6f dEe&dDe&ddf
dOdPZ7	BddCd dQedEe&dDe&ddf
dRdSZ8	,	BddCd dTedEe&dDe&ddf
dUdVZ9	,	BddCd dWedXedEe&dDe&ddfdYdZZ:	Bdd8ee6e*f dDe&ddfd[d\Z;d]ed^eddfd_d`Z<daeddfdbdcZ=dededdfdddeZ>ddge	ddfdhdiZ?edee	 fdjdkZ@defdldmZAdneeee e	ef f e eef eee f doedpedqedeeeef f
drdsZBdtedueeeeCf  dvee dwee dneeee e	ef f e eef eee f dxee	dyf dpedze&d{ee2eeeeegdf  dqed|e eef deee&e eef f fd}d~ZDddeEjFdddfdededxee	dyf dqedee dee2eeeegdf  dee2eeeegdf  d{ee2eeeeegdf  defddZGde eeHjIf fddZJ	,		,		dde&dede&deeK dedefddZLddddddddedxee	ee	dyf f dqedee2eeeegdf  dee2eeeegdf  d{ee2eeeeegdf  deMd dedefddZN					dde.dxee	dyf dqedee2eeeegdf  dee2eeeegdf  d{ee2eeeeegdf  defddZOdeePe ePe f fddZQeReEjSdZT	 eRdeEjSfZU	 eRddeEjSfZV	 eRddeEjSfZW	 eRddeEjSfZX	 edee/ fddZYeYj#dee/ ddfddZY  ZZS )
PageObjecta#  
    PageObject represents a single page within a PDF file.

    Typically these objects will be created by accessing the
    :attr:`pages<pypdf.PdfReader.pages>` property of the
    :class:`PdfReader<pypdf.PdfReader>` class, but it is
    also possible to create an empty page with the
    :meth:`create_blank_page()<pypdf._page.PageObject.create_blank_page>` static method.

    Args:
        pdf: PDF file the page belongs to.
        indirect_reference: Stores the original indirect reference to
            this object in its source PDF

    Zoriginal_pageNrE   r   rA   c                 C   sR   t |  || _d | _|| _t|s$|d usJ d| tt |  i | _	d S )Nmypy)
r0   r^   rE   inline_imagesr   r;   updater   rF   _font_width_maps)r>   rE   r   rJ   rJ   rK   r^     s   

zPageObject.__init__c                 C   s   t ttdd |  D fS )z
        Used to detect modified object.

        Note: this function is overloaded to return the same results
        as a DictionaryObject.

        Returns:
            Hash considering type and value.

        c                 s   s     | ]\}}||  fV  qd S rB   )hash_binr   kvrJ   rJ   rK   	<genexpr>  s    z&PageObject.hash_bin.<locals>.<genexpr>)r   r0   r   r   rR   rJ   rJ   rK   r     s   zPageObject.hash_binc                    s   t   }|dt|  7 }|S )Ns   %d)superhash_value_dataid)r>   r   r   rJ   rK   r     s   
zPageObject.hash_value_datac                 C   s   |  tjdS )a  
        A read-only positive number giving the size of user space units.

        It is in multiples of 1/72 inch. Hence a value of 1 means a user
        space unit is 1/72 inch, and a value of 3 means that a user
        space unit is 3/72 inch.
        r   )rC   PGZ	USER_UNITrR   rJ   rJ   rK   	user_unit  s   	zPageObject.user_unitwidthheightc                 C   s   t | }|ttjtd |ttjt  |ttjt  |du s+|du rK| durIt	| j
dkrI| j
t	| j
d  }|jj}|jj}nt|ttjtdd||f |S )aC  
        Return a new blank page.

        If ``width`` or ``height`` is ``None``, try to get the page size
        from the last page of *pdf*.

        Args:
            pdf: PDF file the page is within.
            width: The width of the new page expressed in default user
                space units.
            height: The height of the new page expressed in default user
                space units.

        Returns:
            The new blank page

        Raises:
            PageSizeNotDefinedError: if ``pdf`` is ``None`` or contains
                no page

        z/PageNr   r   )r   __setitem__r4   r   ZTYPEZPARENTr5   	RESOURCESr0   r   r   mediaboxr   r   r*   MEDIABOXr8   )rE   r   r   pageZlastpagerJ   rJ   rK   create_blank_page#  s   
zPageObject.create_blank_pageobjancest
call_stackc                 C   sD  |d u rg }t |dd }||v rg S || | jd u r!|  | _|d u r'| }|d u r-g }g }tj|vs?tjtt	|tj vrM| jd u rFg S t
| j S |tj tj  }|D ]5}t|| tscqY|| tj dkr~|t|dkrv|ng || qY|| || g ||| qY| jd usJ |t
| j  |S )Nr   /Imager   )getattrappendr   _get_inline_imagesr   r   RESXOBJECTr   r0   r   r   rF   rD   r9   IAZSUBTYPEr   extend_get_ids_image)r>   r   r   r   Z_ir   Zx_objectorJ   rJ   rK   r  Q  s6   



$"zPageObject._get_ids_imager   c                 C   sT  |d u r	t t| }t|trt|}t|tr!t|dkr!|d }zt tt t|tj t	j
 }W n tyG   |d dkrD|d dksE Y nw t|tr|d dkrq|d dkrq| jd u rc|  | _| jd u rltd| j| S tt t|| }|d d \}}t|dd   | ||d || jdS |dd  }| |t t||d  S )Nr   r   ~r   zNo inline image can be foundr_   r?   r   r   r   )r   r0   rD   r   r   r   r   r   r   r  r  KeyErrorr   r   r   r-   r   r   
_get_image)r>   r   r   ZxobjsZimgdr   r   ZidsrJ   rJ   rK   r
  u  s@   






zPageObject._get_imagec                 C   s   t | j| jS )aH  
        Read-only property emulating a list of images on a page.

        Get a list of all images on the page. The key can be:
        - A string (for the top object)
        - A tuple (for images within XObject forms)
        - An integer

        Examples:
            * `reader.pages[0].images[0]`        # return first image
            * `reader.pages[0].images['/I0']`    # return image '/I0'
            * `reader.pages[0].images['/TP1','/Image1']` # return image '/Image1' within '/TP1' XObject form
            * `for img in reader.pages[0].images:` # loops through all objects

        images.keys() and images.items() can be used.

        The ImageFile has the following properties:

            * `.name` : name of the object
            * `.data` : bytes of the object
            * `.image` : PIL Image Object
            * `.indirect_reference` : object reference

        and the following methods:
            `.replace(new_image: PIL.Image.Image, **kwargs)` :
                replace the image in the pdf with the new image
                applying the saving parameters indicated (such as quality)

        Example usage:

            reader.pages[0].images[0].replace(Image.open("new_image.jpg"), quality=20)

        Inline images are extracted and named ~0~, ~1~, ..., with the
        indirect_reference set to None.

        )r   r  r
  rR   rJ   rJ   rK   r     s   &zPageObject.imagesr   r   c                 C   s   zGt i ddddddddd	d
ddddddddddddddddddddd
d
ddddddddtt| }W |S  ttfy~   t|t r{ztt| d d }tt|| }W Y |S  tyz   td| d| w Y |S w )z%Translate values used in inline imagez/Gz/DeviceGrayz/RGBz
/DeviceRGBz/CMYKz/DeviceCMYK/Iz/Indexedz/AHxz/ASCIIHexDecodez/A85z/ASCII85Decodez/LZW
/LZWDecodez/Fl/FlateDecodez/RL/RunLengthDecodez/CCF/CCITTFaxDecodez/DCT
/DCTDecode)r  r  r  r  r  
/Resources/ColorSpacezCannot find resource entry z for )r4   r   r   r   r	  rD   r0   r+   )r>   r   r   resrJ   rJ   rK   _translate_value_inline_image  sv   	
#
z(PageObject._translate_value_inline_imagec                    s    }t|r
i S g }|dusJ d|jD ] \}}|dkr,||d |d d q|dv r7t|dqi }t|D ]\}}|d	 t|d	 d
}|d  D ]g\ }	 dv r\qSt|	t	rnt
 fdd|	D }	n |	}	ti dddddddddddddddddddd dddddddddddddddd d!    |vr|	| < qSt||d"< t|d" \}
}}td#| d#|
 ||dd$|d#| d#< q>|S )%z8Load inline images. Entries will be identified as `~1~`.Nr   s   INLINE IMAGEsettingsr   )r  __streamdata__)s   BIs   EIs   IDzM operator met whereas not expected, please share use case with pypdf dev teamr  )r  /Length>   r  z/Lc                    s   g | ]}  |qS rJ   )r  r   r   r>   rJ   rK   r     r   z1PageObject._get_inline_images.<locals>.<listcomp>z/BPCz/BitsPerComponentz/CSr  z/Dz/Decodez/DPz/DecodeParmsz/Fz/Filterz/Hz/Heightz/Wz/Widthr  /Interpolatez/Intentz/IM
/ImageMask)r  r  objectr  r  )get_contentsr;   
operationsr   r+   r   r   r   rD   r   r.   r  r4   r1   Zinitialize_from_dictionaryr-   r   )r>   contentZ	imgs_dataparamopefilesnumiiinitr   r   r   r   rJ   r  rK   r     s   

	
zPageObject._get_inline_imagesc                 C   s$   |  tjd}t|tr|S | S )z
        The visual rotation of the page.

        This number has to be a multiple of 90 degrees: 0, 90, 180, or 270 are
        valid values. This property does not affect ``/Contents``.
        r   )rC   r   ROTATErD   r   rF   )r>   Z
rotate_objrJ   rJ   rK   rp   .  s   zPageObject.rotationrc                 C   s*   t t|d d d d | ttj< d S )N-   Z   h  )r6   r   r4   r   r%  )r>   r&  rJ   rJ   rK   rp   9  s   *c              	   C   s*  | j  }d| _ t| j}t t|j|jd   t|j|j	d   
|}||j}||j}|t|d |d  t|d |d  }| |d dD ]@}|| v rt| | }||j}||j}tt|d |d t|d |d t|d |d t|d |d f| t|< qRdS )z
        Apply the rotation of the page to the content and the media/crop/...
        boxes.

        It is recommended to apply this function before page merging.
        r   r_   r   F)z	/MediaBox/CropBox	/BleedBox/TrimBox/ArtBoxN)rp   r8   r   rZ   ri   r~   leftr   bottomr   ru   r|   
lower_leftupper_rightminadd_transformationmaxr4   )r>   r&  mbtrsfr   pt2r   ZrrrJ   rJ   rK   transfer_rotation_to_content=  s6   
(,z'PageObject.transfer_rotation_to_contentanglec                 C   s0   |d dkr
t dt| j| | ttj< | S )z
        Rotate a page clockwise by increments of 90 degrees.

        Args:
            angle: Angle to rotate the page. Must be an increment of 90 deg.

        Returns:
            The rotated PageObject

        r(  r   z'Rotation angle must be a multiple of 90)rm   r6   rp   r4   r   r%  )r>   r9  rJ   rJ   rK   ru   `  s   zPageObject.rotateTres1res2resourcenew_res1c              	      sh  zt | jts	J | jj}t|d}W n ttfy"   d }d}Y nw dtdttt	f f fdd}|rEt
   ||t
   ntt
||  tt
||t
  i }D ]S}	||	\}
}t|
}|	|
krp|||	< |s|r|	| |< z	 | j |< W n ty   Y nw |	 |< t  }   |D ]
}|d  |d < qq\ |fS )	N_add_objectFbase_keyrA   c                    sV    | }| }d}| v r'  ||kr|dfS |  d| }|d7 }| v s|dfS )a  
            Find a key that either doesn't already exist or has the same value
            (indicated by the bool)

            Args:
                base_key: An index is added to this to get the computed key

            Returns:
                A tuple (computed key, bool) where the boolean indicates
                if there is a resource of the given computed_key with the same
                value.

            r   T-r   F)raw_get)r?  rM   Zcomputed_keyidxZnew_resZpage2resrJ   rK   compute_unique_key  s   
z7PageObject._merge_resources.<locals>.compute_unique_keyr   r   )rD   r   r3   rE   r   AssertionErrorAttributeErrorr   r   r   r0   r   rC   rF   r   r4   rA  clonesortedr   clear)r>   r:  r;  r<  r=  rE   Zis_pdf_writerrD  Z
rename_reskeyZ
unique_keyZ
same_valueZnewnamer   elrJ   rC  rK   _merge_resourcesp  sN    !zPageObject._merge_resourcesstreamrenamec                 C   s   |s| S t | |} | jD ]D\}}t|tr,t|D ]\}}t|tr*|||||< qqt|trH| D ]\}}t|trF|||||< q5qt	dt
| | S )NzType of operands is )r/   r  rD   r   r   r4   rC   dictr   r	  r   )rM  rN  rE   operands	_operatorr   rn   rJ   rJ   rK   _content_stream_rename  s$   




z!PageObject._content_stream_renamecontentsr\   c                 C   s*   t | |} | jddd |D dg | S )zHAdd transformation matrix at the beginning of the given contents stream.r   c                 S      g | ]}t |qS rJ   )r2   r   rJ   rJ   rK   r     r   z9PageObject._add_transformation_matrix.<locals>.<listcomp>   cm)r/   r  insert)rS  rE   r\   rJ   rJ   rK   _add_transformation_matrix  s   
z%PageObject._add_transformation_matrixc                 C   sH   t j| v r"| t j  }t|trddd |D S tt| S dS )z
        Return the page contents as bytes.

        Returns:
            The ``/Contents`` object as bytes, or ``None`` if it doesn't exist.

        r   c                 s   s    | ]	}|   V  qd S rB   )rF   get_datar   rJ   rJ   rK   r     s    z4PageObject._get_contents_as_bytes.<locals>.<genexpr>N)	r   CONTENTSrF   rD   r   r   r   r1   rX  )r>   r   rJ   rJ   rK   _get_contents_as_bytes  s   

z!PageObject._get_contents_as_bytesc                 C   s`   t j| v r.z	tt| jj}W n ty   d}Y nw | t j }t|r%dS | }t	||S dS )u   
        Access the page contents.

        Returns:
            The ``/Contents`` object, or ``None`` if it does not exist.
            ``/Contents`` is optional, as described in §7.7.3.3 of the PDF Reference.

        N)
r   rY  r   r3   r   rE   rF  r;   rF   r/   )r>   rE   r   Zresolved_objectrJ   rJ   rK   r    s   
	

zPageObject.get_contentsr  c              	      s  t  dr
 jdu r| ttj< dS t tjdtr: tj D ]}zt  j	|jj
d < W q" ty9   Y q"w t|trJt fdd|D }t|rztj vrUdS  jdus\J  tj jdusfJ t  jjj	 tj jj
d <  tj= nVt  tjddsz jj| ttj< W n= ty   | ttj< Y n.w |dusJ d tj j|_z| jjj	|jj
d < W n ty   | ttj< Y nw d _dS )z
        Replace the page contents with the new content and nullify old objects
        Args:
            content: new content; if None delete the content field.
        r   Nr   c                 3   s    | ]
} j j|V  qd S rB   )r   rE   r>  )r   r   rR   rJ   rK   r   !  s    z.PageObject.replace_contents.<locals>.<genexpr>r   )r   r   r4   r   rY  rD   rC   r.   r5   r   r   rF  r;   rE   r>  r   )r>   r  r  rJ   rR   rK   replace_contents  sZ   




zPageObject.replace_contentsFpage2expandoverc                 C   s   | j |||d dS )a  
        Merge the content streams of two pages into one.

        Resource references (e.g. 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.

        Args:
            page2: The page to be merged into this one. Should be
                an instance of :class:`PageObject<PageObject>`.
            over: set the page2 content over page1 if True (default) else under
            expand: If True, the current page dimensions will be
                expanded to accommodate the dimensions of the page to be merged.

        )r^  r]  N)_merge_page)r>   r\  r]  r^  rJ   rJ   rK   
merge_pageG  s   zPageObject.merge_pagepage2transformationc              	   C   s  zt | jts	J t| jjdr| |||||W S W n ttfy&   Y nw t }i }zt	t| t
j  }W n tyD   t }Y nw zt	t|t
j  }	W n ty]   t }	Y nw t }
| |fD ]}t
j|v r{|t
j }t |tr{|
| qetjtjtjtjtjtjtjfD ]}| ||	|\}}|r||t|< || qttt|tjt   t|	tjt  |ttj< t }| ! }|d ur|"  |#| |! }|d ur3t$|t%}|j&'dt(t)|j*|j+|j,|j-gdf |j&'dg df |j&'dg df |d ur||}t./||| j}|"  |r-|#| n|'d| |r<| 0|| | 1t2|| j || tt
j< |
| tt
j< d S )Nr>  r      rer      Wr_      n)3rD   r   r3   r   rE   _merge_page_writerrE  rF  r0   r   r   r   rF   r	  r.   ANNOTSr  r  EXT_G_STATEFONTr  COLOR_SPACEPATTERNSHADING
PROPERTIESrL  r4   r   rH  setrC   PROC_SETunionr  isolate_graphics_stater   r   MERGE_CROP_BOXr  rV  mapr2   r.  r/  r   r   r   rR  _expand_mediaboxr[  r/   )r>   r\  ra  r\   r^  r]  Znew_resourcesrN  original_resourcespage2resourcesZ
new_annotsr   annotsr  new	newrenamenew_content_arrayoriginal_contentpage2contentrectrJ   rJ   rK   r_  ]  s   






	




	
zPageObject._merge_pagec              	   C   s   t | jtsJ | jj}i }tj| vrt | ttj< tt| tj 	 }tj|vr.t }	n
tt|tj 	 }	t
jt
jt
jt
jt
jt
jt
jfD ] }
|
|	v rh|
|vrYt |t|
< | ||	|
d\}}|| qHt
j|	v rt
j|vr{t |tt
j< tt|t
j }tt|	t
j D ]}||vr|| q|  tj|v rtj| vrt | ttj< tt| tj 	 }|d u rt }nt|}tt|tj D ]}|	 }|j|ddd}tt|d }||d |d fd}||d |d	 fd}tt|d |d t|d |d t|d |d t|d |d f|td< d
|v rctt|d
 }t||d |d fd||d |d	 fd ||d |d fd ||d |d fd |td
< z|j|d td< W n
 tyx   Y nw z| j|td< ||j W q ty   Y qw t }|   }|d ur|!  || |  }|d ur t"|t#}|j$%dt&t'|j(|j)|j*|j+gdf |j$%dg df |j$%dg df |d ur||}t,-||| j}|!  |r|| n|%d| |r	| .|| | /| d S )NF)/Pz/StructParent/ParentT)Zignore_fieldsZforce_duplicatez/Rectr   r   r_   r`   z/QuadPointsra   rb         z/Popupr~  r}  rb  rc  rd  )0rD   r   r3   rE   r   r   r0   r4   r   rF   r  rg  rh  r  ri  rj  rk  rl  rL  r   rn  r.   r   sortrf  rZ   rG  r|   r2  r4  r	  rF  r  rp  r   rq  r  rV  rr  r2   r.  r/  r   r   r   rR  rs  r[  )r>   r\  ra  r\   r^  r]  rE   rN  rt  ru  r  _rx  Zarrr   rv  r6  aZaar&  r   r7  qry  rz  r{  r|  rJ   rJ   rK   re    s   

	









	
zPageObject._merge_page_writerc              	      st  | j j | j j | j j | j j f}|j j |j j |j j |j j |j j |j j |j j |j j f d urntdd D t fddtdddD }t fddtdddD }n ddd } ddd }t|t|f}t	|t	|f}t|d |d t|d |d f}t	|d |d t	|d	 |d f}|| j _
|| j _d S )
Nc                 s       | ]}t |V  qd S rB   r~   r   rJ   rJ   rK   r   i      z.PageObject._expand_mediabox.<locals>.<genexpr>c                 3   s<    | ]}d   |  d  |d    d  V  qdS )r   r_   r   ra   NrJ   r   r   Zcorners2r\   rJ   rK   r   j  
    *
r      r_   c                 3   s<    | ]}d   |  d  |d     d  V  qdS )r   r`   rb   NrJ   r  r  rJ   rK   r   n  r  r   r`   )r   r.  
as_numericr/  righttopr   r   r2  r4  r0  r1  )r>   r\  r\   Zcorners1new_xnew_yZ	lowerleftZ
upperrightrJ   r  rK   rs  U  s@   















$zPageObject._expand_mediaboxc                    s0   t  tr j |  fdd || dS )a  
        Similar to :meth:`~pypdf._page.PageObject.merge_page`, but a transformation
        matrix is applied to the merged stream.

        Args:
          page2: The page to be merged into this one.
          ctm: a 6-element tuple containing the operands of the
                 transformation matrix
          over: set the page2 content over page1 if True (default) else under
          expand: Whether the page should be expanded to fit the dimensions
            of the page to be merged.

        c                    s   t | jtt S rB   )r   rW  rE   r   r!   )Zpage2Contentr\   r\  rJ   rK   rT     s    z3PageObject.merge_transformed_page.<locals>.<lambda>N)rD   rZ   r\   r_  )r>   r\  r\   r^  r]  rJ   r  rK   merge_transformed_page  s   
z!PageObject.merge_transformed_pagero   c                 C   s"   t  ||}| |||| dS )a  
        Similar to :meth:`~pypdf._page.PageObject.merge_page`, but the stream to be merged
        is scaled by applying a transformation matrix.

        Args:
          page2: The page to be merged into this one.
          scale: The scaling factor
          over: set the page2 content over page1 if True (default) else under
          expand: Whether the page should be expanded to fit the
            dimensions of the page to be merged.

        N)rZ   ro   r  )r>   r\  ro   r^  r]  rn   rJ   rJ   rK   merge_scaled_page  s   zPageObject.merge_scaled_pagerp   c                 C   s    t  |}| |||| dS )a  
        Similar to :meth:`~pypdf._page.PageObject.merge_page`, but the stream to be merged
        is rotated by applying a transformation matrix.

        Args:
          page2: The page to be merged into this one.
          rotation: The angle of the rotation, in degrees
          over: set the page2 content over page1 if True (default) else under
          expand: Whether the page should be expanded to fit the
            dimensions of the page to be merged.

        N)rZ   ru   r  )r>   r\  rp   r^  r]  rn   rJ   rJ   rK   merge_rotated_page  s   zPageObject.merge_rotated_pagerg   rh   c                 C   s"   t  ||}| |||| dS )a  
        Similar to :meth:`~pypdf._page.PageObject.merge_page`, but the stream to be
        merged is translated by applying a transformation matrix.

        Args:
          page2: the page to be merged into this one.
          tx: The translation on X axis
          ty: The translation on Y axis
          over: set the page2 content over page1 if True (default) else under
          expand: Whether the page should be expanded to fit the
            dimensions of the page to be merged.

        N)rZ   ri   r  )r>   r\  rg   rh   r^  r]  rn   rJ   rJ   rK   merge_translated_page  s   z PageObject.merge_translated_pagec              	      s  t trj|  }|dur!t|| j}|  | | |r| j	j
 | j	j | j	j
 | j	j | j	j | j	j | j	j | j	j g tdd D  fddtdddD } fd	dtdddD }t|t|f| j	_t|t|f| j	_dS dS )
ab  
        Apply a transformation matrix to the page.

        Args:
            ctm: A 6-element tuple containing the operands of the
                transformation matrix. Alternatively, a
                :py:class:`Transformation<pypdf.Transformation>`
                object can be passed.

        See :doc:`/user/cropping-and-transforming`.

        Nc                 s   r  rB   r  r   rJ   rJ   rK   r     r  z0PageObject.add_transformation.<locals>.<genexpr>c                    s8   g | ]}d   |  d  |d    d  qS )r   r_   r   ra   rJ   r  Zcornersr\   rJ   rK   r         *z1PageObject.add_transformation.<locals>.<listcomp>r   r  r_   c                    s8   g | ]}d   |  d  |d     d  qS )r   r`   rb   rJ   r  r  rJ   rK   r   
  r  )rD   rZ   r\   r  r   rW  rE   rp  r[  r   r.  r  r/  r  r  r   r   r2  r0  r4  r1  )r>   r\   r]  r  r  r  rJ   r  rK   r3    s6   











zPageObject.add_transformationrj   rk   c           
      C   s  |  |dd|ddf | j||| _| j||| _| j||| _| j||| _| j||| _tj| v r| tj }t	|t
r|D ]E}| }tj|v r|tj }t	|t
rtt|d | |d< tt|d | |d< tt|d | |d< tt|d | |d< qDtj| v r| tj }t	|t
r|d d }n|d }tt|d | t|d | t|d | t|d | f}	t	|t
r|	| ttj td td< dS |	| ttj td< dS dS )ax  
        Scale a page by the given factors by applying a transformation matrix
        to its content and updating the page size.

        This updates the various page boundaries (mediabox, cropbox, etc.)
        and the contents of the page.

        Args:
            sx: The scaling factor on horizontal axis.
            sy: The scaling factor on vertical axis.

        r   r   r_   r`   z/BBoxN)r3  r   ro   r=   bleedboxtrimboxartboxr   rf  rD   r.   rF   ADAZRectr2   r~   ZVPr8   r4   r6   )
r>   rj   rk   annotations
annotationZannotation_objZ	rectangleZviewportZbboxZscaled_bboxrJ   rJ   rK   ro     sL   









zPageObject.scalefactorc                 C   s   |  || dS )z
        Scale a page by the given factor by applying a transformation matrix to
        its content and updating the page size.

        Args:
            factor: The scaling factor (for both X and Y axis).

        N)ro   )r>   r  rJ   rJ   rK   scale_byH  s   	zPageObject.scale_byc                 C   s0   |t | jj }|t | jj }| || dS )z
        Scale a page to the specified dimensions by applying a transformation
        matrix to its content and updating the page size.

        Args:
            width: The new width.
            height: The new height.

        N)r~   r   r   r   ro   )r>   r   r   rj   rk   rJ   rJ   rK   scale_toS  s   
zPageObject.scale_tor   levelc                 C   sz   |   }|dur;||}z||jjj|jjd < W dS  ty:   | jdur6t| jjdr6| | Y dS t	dw dS )a   
        Compress 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".
        Nr   r>  z Page must be part of a PdfWriter)
r  Zflate_encoder   rE   r   r   rF  r   r[  rm   )r>   r  r  Zcontent_objrJ   rJ   rK   compress_content_streamsa  s    

z#PageObject.compress_content_streamsc                 C   s:   | j du rdS z| j jj}|| W S  ty   Y dS w )z
        Read-only property which returns the page number within the PDF file.

        Returns:
            Page number; None if the page is not attached to a PDF.

        N)r   rE   r   r   rm   )r>   r   rJ   rJ   rK   page_numberx  s   
	
zPageObject.page_numberc              	   C   sR  d}t | d  | jdjD ](\}}|dkr dd |d D }ng }||dd	 d| |  d
 7 }q|d7 }z_| tj d D ]T}||d
 7 }|| tj d |  d
 7 }z| tj d | d  }||d
 7 }W n	 t	yx   Y nw z|| tj d | d 
  d
 7 }W qC t	y   Y qCw W |S  ty   |d7 }Y |S w )Nr   	/Contentsr      TJc                 S   s   g | ]	}t |tr|qS rJ   )rD   r   r   rJ   rJ   rK   r     s    z1PageObject._debug_for_extract.<locals>.<listcomp>r   utf-8 
z
=============================
/Fontz	/Encodingz
/ToUnicodezNo Font
)r/   rF   rE   r  decoder   rw   r   r   	ExceptionrX  r	  )r>   outr   rn   sfoZenc_reprrJ   rJ   rK   _debug_for_extract  sX   
*
zPageObject._debug_for_extractcmaptext_operands	font_sizespace_widthc                 C   s   d}|d }|| j vrD|d d u ri }d}|}	|	d |d< ntd|d |d }t|d |d }t||}	|	dkr<|}	|||	f| j |< | j | d }| j | d }| j | d }	|rp|D ]}
|
|krh||	7 }q]|t||
7 }q]|| || |fS )Nr   r_   r`   r  defaultr   )r   r   r   r   )r>   r  r  r  r  font_widths	font_nameZfont_width_mapZ
space_charZactual_space_widthcharrJ   rJ   rK   _get_actual_font_widths  s0   	

z"PageObject._get_actual_font_widthstextrP  	cm_matrix	tm_matrixorientations.rtl_dirvisitor_textactual_str_sizec              	   C   st   t |||||\}}|r||7 }nt||||||||	\}}| ||||
\}|d< |d< |d  |7  < |||fS )Nr  
str_height
str_widths)r   r   r  )r>   r  rP  r  r  r  r  r  r  r  r  r  r  Zis_str_operandsr  rJ   rJ   rK   
_handle_tj  s&   



zPageObject._handle_tj)r   r(             i@content_keyvisitor_operand_beforevisitor_operand_afterc	                    s  dddi z |}	t tj|	vr|	d  }	t tj|	vstt|	tj }
W n
 ty2   Y dS w d|
v rM|
d  }rMtt|D ]
}t||||< qBdi ddfzt|t	r_||  n|}t|t
slt
||d}W n ttfyy   Y dS w g d	g d	g g d	g d	g d	g d	d
d
dddddd d
dtdtfdd	dtdtt ddf 	
fdd}|jD ]Y\}}|dur||| |dkr|dg  |d| n.|dkr|d|d g |d|d g |dg  |d|dd  n	|d kr_d! }|r^|d D ]4}t|t	tfr9|d|g t|ttttfr\tt||kr\r\d" d#kr\|dd#g q)n|d$krs|d%|d  g |d&| n|d'kr7 durd( 
 zd" d)krd)7 durd)d( 
 W n
 ty   Y nw z_z2|
d* }||d  d+ d,kr||d  |||7 durd( 
 W n  ty } ztd-|d  d.| t W Y d}~nd}~ww W d  nd  w ||| |dur.||| qԈ7 dkrGdurGd( 
 S )/a  
        See extract_text for most arguments.

        Args:
            content_key: indicate the default key where to extract data
                None = the object; this allows reusing the function on an XObject
                default = "/Content"

        r   Fr~  r  charmapZNotInitializedNr         ?        r  r  r  r  r  g     @@r  )r  r  r  g      (@r  rA   c                 S   s   | d S )Ni  rJ   )r  rJ   rJ   rK   compute_str_widthsO  r   z4PageObject._extract_text.<locals>.compute_str_widthsoperatorrP  c                    s  d}| dkr(g d7 d urd 
 d    d S | dkrJ7 d ur>d 
 d    n| dkr\
 f n| dkr}z \
 W n ty|   g dY nw | d	kr7 d urd 
 dztd
d |d d D W n ty   g dY nw     nX| dkr|rt|d d ndnF| dkrdt|r|d nd n4| dkrtd d d d  }t|r|d nd
 |  n| dkrwdkr"7 d ur"d 
 d    z|d  }|d |d |d |d f|d W n tyc   t	d t	d d|d  d ft	d Y nw zt|d 
W n tyv   Y nw | dkrt|d t|d }}d  |d  |d   7  < d  |d  |d   7  < 	d }dd< n]| dkrdd |d d D 	d }dd< nB| dkrd   d  8  < d   d  8  < 	d }dd< n| dkr
|
\nd S | dv rXz2tfff
|	d  d! \dkrJ    W d S W d S  tyW   Y d S w d S )"Nr  s   BTr  r`   r   s   ET   q   QrU  c                 S   rT  rJ   r  r   operandrJ   rJ   rK   r     r   zGPageObject._extract_text.<locals>.process_operation.<locals>.<listcomp>r  s   Tzr   d   r     Tw   TLr_   s   Tfra   r   z???   Tdrb   r     Tmc                 S   rT  rJ   r  r  rJ   rJ   rK   r     r      T*   Tj>   r  r  r  r  r  r  )copyr   popr  r    r~   rq   sqrtr	  r   r  r   r   )r  rP  r  Zscale_xZchar_map_tuplerg   rh   ZTLZ_actual_str_sizeZ_space_widthZ
char_scaler  Zcm_prevZcm_stackr  Zcmapsr  r  Zmemo_cmZmemo_tmr  outputr  r>   Zspace_scaler  r  Ztm_prevr  rJ   rK   process_operationR  s&  	
 



$$








z3PageObject._extract_text.<locals>.process_operation   'r  r     "r  r   s   Tcr   r_   r  gffffff?r   r  s   TDr  r  s   Dor`   r  /XObject/Subtyper   z!Impossible to decode XFormObject z: )r4   r   r   rF   r   r0   r  r   rD   r   r/   rF  r	  r~   r   r   r   r  r   r6   r2   absr   extract_xform_textr$   r   r  )r>   r   rE   r  r  r  r  r  r  objrresources_dictZfontfr  r  rP  r  Z_confirm_space_widthrn   Zxobj	exceptionrJ   r  rK   _extract_text  s  	
H ,













zPageObject._extract_textc                 C   s   | }i }|duraz|t j }W n ty   i }Y nw d|v rI| jdurI|d D ] }t|d| ^ }}dd | D }tjg ||R  ||< q(z|d  }W n ty\   d}Y nw |dus|S )z
        Get fonts formatted for "layout" mode text extraction.

        Returns:
            Dict[str, Font]: dictionary of _layout_mode.Font instances keyed by font name

        Nr  r  c                 S   s@   i | ]\}}|t |tr| nt |trd d |D n|qS )c                 S   s   g | ]}|  qS rJ   )rF   )r   _vrJ   rJ   rK   r   f  r   z<PageObject._layout_mode_fonts.<locals>.<dictcomp>.<listcomp>)rD   r3   rF   r.   r   rJ   rJ   rK   
<dictcomp>c  s    
z1PageObject._layout_mode_fonts.<locals>.<dictcomp>r~  )	r   r   r	  rE   r   r   r   FontrF   )r>   r  fontsr  r  r  Zfont_dict_objZ	font_dictrJ   rJ   rK   _layout_mode_fontsP  s,   		zPageObject._layout_mode_fonts      ?r   space_verticallyscale_weightstrip_rotated
debug_pathfont_height_weightc                 C   s   |   }|rddl}|d|j|ddd dd tt| d	  | jd
j	}t
||||}	|	s5dS t
|	|}
t
|	|}t
|
|||S )aQ  
        Get text preserving fidelity to source PDF text layout.

        Args:
            space_vertically: include blank lines inferred from y distance + font
                height. Defaults to True.
            scale_weight: multiplier for string length when calculating weighted
                average character width. Defaults to 1.25.
            strip_rotated: Removes text that is rotated w.r.t. to the page from
                layout mode output. Defaults to True.
            debug_path (Path | None): if supplied, must target a directory.
                creates the following files with debug information for layout mode
                functions if supplied:
                  - fonts.json: output of self._layout_mode_fonts
                  - tjs.json: individual text render ops with corresponding transform matrices
                  - bts.json: text render ops left justified and grouped by BT/ET operators
                  - bt_groups.json: BT/ET operations grouped by rendered y-coord (aka lines)
                Defaults to None.
            font_height_weight: multiplier for font height when calculating
                blank lines. Defaults to 1.

        Returns:
            str: multiline string containing page text in a fixed width format that
                closely adheres to the rendered layout in the source pdf.

        r   Nz
fonts.jsonr_   c                 S   s   t | dt| S )Nto_dict)r   r   )r   rJ   rJ   rK   rT     s    z.PageObject._layout_mode_text.<locals>.<lambda>)indentr  r  r  r   r   )r  jsonjoinpath
write_textdumpsiterr/   rF   rE   r  r   Ztext_show_operationsZy_coordinate_groupsZfixed_char_widthZfixed_width_page)r>   r  r  r  r  r  r  r  opsZ	bt_groupsZ	ty_groups
char_widthrJ   rJ   rK   _layout_mode_textt  s(   "

zPageObject._layout_mode_textplain)r  r  r  r  r  extraction_modeargsr  r   layoutr   c          
   
   O   s  |dvrt d| d|dkr@dD ]}	t |	 r"td|	 dt q| j|dd	|d
d|dd	|d|dddS t|dkrt|d trt|dkrjt|d t	t
fra|d }n	td|d  t|dkrt|d tt
fr~|d }n>td|d  n4t|d t	t
fr|d }t|dkrt|d tt
fr|d }ntd|d  n	td|d  t|t
r|f}| | | j||tj|||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.

        Arabic and Hebrew are extracted in the correct order.
        If required a custom RTL range of characters can be defined;
        see function set_custom_rtl.

        Additionally you can provide visitor methods to get informed on all
        operations and all text objects.
        For example in some PDF files this can be useful to parse tables.

        Args:
            orientations: list of orientations extract_text will look for
                default = (0, 90, 180, 270)
                note: currently only 0 (up),90 (turned left), 180 (upside down),
                270 (turned right)
                Silently ignored in "layout" mode.
            space_width: force default space width
                if not extracted from font (default: 200)
                Silently ignored in "layout" mode.
            visitor_operand_before: function to be called before processing an operation.
                It has four arguments: operator, operand-arguments,
                current transformation matrix and text matrix.
                Ignored with a warning in "layout" mode.
            visitor_operand_after: function to be called after processing an operation.
                It has four arguments: operator, operand-arguments,
                current transformation matrix and text matrix.
                Ignored with a warning in "layout" mode.
            visitor_text: function to be called when extracting some text at some position.
                It has five arguments: text, current transformation matrix,
                text matrix, font-dictionary and font-size.
                The font-dictionary may be None in case of unknown fonts.
                If not None it may e.g. contain key "/BaseFont" with value "/Arial,Bold".
                Ignored with a warning in "layout" mode.
            extraction_mode (Literal["plain", "layout"]): "plain" for legacy functionality,
                "layout" for experimental layout mode functionality.
                NOTE: orientations, space_width, and visitor_* parameters are NOT respected
                in "layout" mode.

        kwargs:
            layout_mode_space_vertically (bool): include blank lines inferred from
                y distance + font height. Defaults to True.
            layout_mode_scale_weight (float): multiplier for string length when calculating
                weighted average character width. Defaults to 1.25.
            layout_mode_strip_rotated (bool): layout mode does not support rotated text.
                Set to False to include rotated text anyway. If rotated text is discovered,
                layout will be degraded and a warning will result. Defaults to True.
            layout_mode_debug_path (Path | None): if supplied, must target a directory.
                creates the following files with debug information for layout mode
                functions if supplied:

                  - fonts.json: output of self._layout_mode_fonts
                  - tjs.json: individual text render ops with corresponding transform matrices
                  - bts.json: text render ops left justified and grouped by BT/ET operators
                  - bt_groups.json: BT/ET operations grouped by rendered y-coord (aka lines)
            layout_mode_font_height_weight (float): multiplier for font height when calculating
                blank lines. Defaults to 1.

        Returns:
            The extracted text

        r  zInvalid text extraction mode ''r  )r  r  r  z	Argument z is ignored in layout modeZlayout_mode_space_verticallyTZlayout_mode_scale_weightr  Zlayout_mode_strip_rotatedZlayout_mode_debug_pathZlayout_mode_font_height_weightr   )r  r  r  r  r  r   r`   r_   zInvalid positional parameter ra   )rm   localsr$   r   r  rC   r   rD   r   r   r   r   r~   r  rE   r   rY  )
r>   r  r  r  r  r  r  r  r   visitorrJ   rJ   rK   extract_text  s`   P









zPageObject.extract_textr   r(  r  r)  xformc              
   C   s   |  || j||d|||S )a\  
        Extract text from an XObject.

        Args:
            xform:
            orientations:
            space_width:  force default space width (if not extracted from font (default 200)
            visitor_operand_before:
            visitor_operand_after:
            visitor_text:

        Returns:
            The extracted text

        N)r  rE   )r>   r
  r  r  r  r  r  rJ   rJ   rK   r  9	  s   zPageObject.extract_xform_textc                 C   sB   |   }t|tsJ t }t }t|||\}}|| }||fS )z
        Get the names of embedded fonts and unembedded fonts.

        Returns:
            A tuple (set of embedded fonts, set of unembedded fonts)

        )rF   rD   r0   rm  _get_fonts_walk)r>   r   r  ZembeddedZ
unembeddedrJ   rJ   rK   
_get_fonts\	  s   zPageObject._get_fontsrJ   r*  r+  r,  r-  c                 C   s   d| vrd S t t| d S )N/Annots)r   r.   rR   rJ   rJ   rK   r  	  s   zPageObject.annotationsrM   c                 C   s&   |du r| t d= dS || t d< dS )z
        Set the annotations array of the page.

        Typically you do not want to set this value, but append to it.
        If you append to it, remember to add the object first to the writer
        and only add the indirect object.
        Nr  rN   rV   rJ   rJ   rK   r  	  s   	r   )NNNrB   )rA   N)T)FT)NNTF)TFr   )r   )Tr  TNr   )r	  r  NNN)[r   r   r   r   r   r   r   r3   r^   r   r   r   r   rX   r~   r   r   r   r   r   r0   r   r   r   r  r   r   r
  r   r   r7   r  r   r   rp   setterr8  ru   r   rL  r/   rR  r!   rW  rZ  r  r1   r.   r[  r`  r   r_  re  rs  rZ   r  r  r  r  r3  ro   r  r  r  r  r  r  r:   r  r   rY  r  r   r  r  r   r  r   r  r  r   r  rY   r   r   r=   r  r  r  r  __classcell__rJ   rJ   r   rK   r     s  
 

/


'
&'(C

#
Q

<

s
 	
/

!




26&&
$&
	


(
	

  [&
@	

 

# r   c                   @   s   e Zd Zdeg ef deegef ddfddZdefddZed	edefd
dZ	ed	e
dee fddZ	d	eee
f deeee f fddZ	d	eee
f ddfddZdee fddZdefddZdS )_VirtualListlength_functionr   rA   Nc                 C   r   r   )r  r   r   )r>   r  r   rJ   rJ   rK   r^   	  r   z_VirtualList.__init__c                 C   r   rB   )r  rR   rJ   rJ   rK   r   	  r   z_VirtualList.__len__r   c                 C   rz   rB   rJ   r   rJ   rJ   rK   r   	  r}   z_VirtualList.__getitem__c                 C   rz   rB   rJ   r   rJ   rJ   rK   r   	  r}   c                    s   t |trt|t  t}| j fddS t |ts&tdt}|dk r2||7 }d|  kr?|k sDt	d t	d
|S )Nc                    s    |   S rB   rJ   )rB  r   r>   rJ   rK   rT   	  rU   z*_VirtualList.__getitem__.<locals>.<lambda>z!Sequence indices must be integersr   r   )rD   r   r   r   r   r   r   r   r   r   r   )r>   r   r   r   rJ   r  rK   r   	  s   


c           	      C   s  t |tr"tt|t|  }|  |  |D ]}| |= qd S t |ts+t	dt| }|dk r7||7 }d|  krD|k sIt
d t
d| | j}|d usTJ tt| dd }d}|d urtt| }zTtt|d |}tt|d |= d}z|d usJ |jj|= W n	 ty   Y nw d|v rttt|d d	 |td< ttt|d dkr|j}|dd }W n ty   |rtd
| Y d S w |d used S d S )NzIndex must be integersr   zIndex out of ranger~  Tz/KidsFz/Countr   zPage not found in page tree: )rD   r   r   r   r   r   r  reverser   r   r   r   r   r0   rF   rC   r.   r   rE   Zflattened_pagesr  r6   r4   rm   r+   )	r>   r   r&  r   r   indparentfirstr   rJ   rJ   rK   __delitem__	  s^   


z_VirtualList.__delitem__c                 c   r   rB   r   r   rJ   rJ   rK   r   	  r   z_VirtualList.__iter__c                 C   r   )Nc                 S   s   g | ]}d | dqS )zPageObject(rv   rJ   r  rJ   rJ   rK   r   	  r   z(_VirtualList.__str__.<locals>.<listcomp>r   r   r   )r   r  r   r   rJ   rJ   rK   r   	  r   z_VirtualList.__str__)r   r   r   r   r   r   r^   r   r   r   r   r   r   r  r
   r   r   r   rJ   rJ   rJ   rK   r  	  s*    

	

/r  r   fntembc                    s  ddt ddf fdd}d| v r/dtt | d v r/tt tt | d d D ]}|| q(d	| v rvdtt | d	 v rQtt tt | d	 d  D ]}|| qJd
tt | d	 v rvtt tt | d	 d
  D ]}ttt |   qhd| v rtt| d D ]}ttt |   qd| v rtt tt | d d dd
krttt tt | d d    fS tt tt | d d D ]}ttt |  qĈ fS )a  
    Get the set of all fonts and all embedded fonts.

    Args:
        obj: Page resources dictionary
        fnt: font
        emb: embedded fonts

    Returns:
        A tuple (fnt, emb)

    If there is a key called 'BaseFont', that is a font that is used in the document.
    If there is a key called 'FontName' and another key in the same dictionary object
    that is called 'FontFilex' (where x is null, 2, or 3), then that fontname is
    embedded.

    We create and add to two sets, fnt = fonts used and emb = fonts embedded.

    )z	/FontFilez
/FontFile2z
/FontFile3r  rA   Nc              
      s   t t   d v rt t d  d v sGd v r(t fddD sGd v rmdt tt t d d  v rot fddD rqzt t d  W d S  tyl   d	t t d
  d  Y d S w d S d S d S )Nz	/BaseFontz
/CharProcs/FontDescriptorc                 3   s"    | ]}|t t d  v V  qdS )r  N)r   r0   r   r  rJ   rK   r   #
  s    
z8_get_fonts_walk.<locals>.process_font.<locals>.<genexpr>/DescendantFontsr   c              
   3   s:    | ]}|t tt tt t d  d  d v V  qdS )r  r   r  N)r   r0   r.   rF   r   r  rJ   rK   r   .
  s    	
(r  rv   )r   r0   rF   addr   anyr.   r	  r  r  r  Zfontkeysr  rK   process_font
  s6   	"z%_get_fonts_walk.<locals>.process_fontz/DRr  r  r  r  z/APz/Nz/Type)r0   r   valuesr  rF   r.   rC   )r   r  r  r!  r  r   r  rJ   r   rK   r  	  sL   (

r  )]rq   dataclassesr   decimalr   ior   pathlibr   typingr   r   r   r	   r
   r   r   r   r   r   r   r   r   r   Z_cmapr   r   r   r   r   Z
_protocolsr   Z_text_extractionr   r   r   r   r   r    Z_utilsr!   r"   r#   r$   r%   	constantsr&   r  r'   r  r(   r   r)   r  errorsr*   r+   r   r-   r   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   Z	PIL.Imager<   r   r   r  rq  r   rL   r~   rG   rO   rX   rY   rZ   r   r   r   r  r  rJ   rJ   rJ   rK   <module>   sx   @ @" ;[?               M^