a
    �˜ëj\  ã                   @   sº   d Z ddlZddlZddlZ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 ddlmZ ejZe e¡ZG dd„ de
jƒZd	d
„ Zddd„ZG dd„ dƒZdd„ ZdS ))ÚPdfPageÚPdfColorSchemeé    N)ÚPdfiumError)Ú	PdfBitmap)ÚPdfTextPage)Ú	PdfObjectc                       s  e Zd ZdZ‡ fdd„Zedd„ ƒZedd„ ƒZdd	„ Z	d
d„ Z
dd„ Zdd„ Zdd„ Zdd„ Zd?dd„Zdd„ Zd@dd„Zdd„ ZdAdd„Zdd „ ZdBd!d"„Zd#d$„ ZdCd%d&„Zd'd(„ Zd)d*„ Zd+d,„ Zd-d.„ Zd/d0„ Zd1d2„ ZdDd6d7„Zej fd8d9„Z!d:d5d;de"j#d3d<fd=d>„Z$‡  Z%S )Er   ah  
    Page helper class.
    
    Attributes:
        raw (FPDF_PAGE):
            The underlying PDFium page handle.
        pdf (PdfDocument):
            Reference to the document this page belongs to.
        formenv (PdfFormEnv | None):
            Formenv handle, if the parent pdf had an active formenv at the time of page retrieval. None otherwise.
    c                    s(   || _ || _|| _tƒ  tj| j¡ d S ©N)ÚrawÚpdfÚformenvÚsuperÚ__init__r   Ú_close_impl)Úselfr	   r
   r   ©Ú	__class__© úV/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/pypdfium2/_helpers/page.pyr   "   s    zPdfPage.__init__c                 C   s   |rt  | |¡ t  | ¡ d S r   )Úpdfium_cZFORM_OnBeforeClosePageZFPDF_ClosePage)r	   r   r   r   r   r   )   s    zPdfPage._close_implc                 C   s   | j S r   )r
   ©r   r   r   r   Úparent0   s    zPdfPage.parentc                 C   s
   t  | ¡S )z`
        Returns:
            float: Page width (horizontal size), in PDF canvas units.
        )r   ZFPDF_GetPageWidthFr   r   r   r   Ú	get_width5   s    zPdfPage.get_widthc                 C   s
   t  | ¡S )z_
        Returns:
            float: Page height (vertical size), in PDF canvas units.
        )r   ZFPDF_GetPageHeightFr   r   r   r   Ú
get_height<   s    zPdfPage.get_heightc                 C   s   |   ¡ |  ¡ fS )zb
        Returns:
            (float, float): Page width and height, in PDF canvas units.
        )r   r   r   r   r   r   Úget_sizeC   s    zPdfPage.get_sizec                 C   s$   t  | ¡}|dkrtdƒ‚tj| S )zO
        Returns:
            int: Clockwise page rotation in degrees.
        éÿÿÿÿzFailed to get page rotation.)r   ZFPDFPage_GetRotationr   Úpdfium_iZRotationToDegrees)r   Zraw_rotationr   r   r   Úget_rotationM   s    
zPdfPage.get_rotationc                 C   s   t  | tj| ¡ dS )z\
        Define the absolute, clockwise page rotation (0, 90, 180, or 270 degrees).
        N)r   ZFPDFPage_SetRotationr   ÚRotationToConst)r   Úrotationr   r   r   Úset_rotationW   s    zPdfPage.set_rotationc           	      C   sR   t ƒ t ƒ t ƒ t ƒ f\}}}}|| ||||ƒ}|s>|r:|ƒ S d S |j|j|j|jfS r   )Úc_floatÚvalue)	r   Zbox_funcZfallback_funcÚfallback_okÚleftÚbottomÚrightÚtopÚokr   r   r   Ú_get_box^   s
    zPdfPage._get_boxTc                 C   s   |   tjdd„ |¡S )aø  
        Returns:
            (float, float, float, float) | None:
            The page MediaBox in PDF canvas units, consisting of four coordinates (usually x0, y0, x1, y1).
            If MediaBox is not defined, returns ANSI A (0, 0, 612, 792) if ``fallback_ok=True``, None otherwise.
        
        .. admonition:: Known issue

            Due to quirks in PDFium, all ``get_*box()`` functions except :meth:`.get_bbox` do not inherit from parent nodes in the page tree (as of PDFium 5418).
        c                   S   s   dS )N)r   r   id  i  r   r   r   r   r   Ú<lambda>r   ó    z&PdfPage.get_mediabox.<locals>.<lambda>)r(   r   ZFPDFPage_GetMediaBox©r   r"   r   r   r   Úget_mediaboxg   s    zPdfPage.get_mediaboxc                 C   s   t  | ||||¡ dS )zn
        Set the page's MediaBox by passing four :class:`float` coordinates (usually x0, y0, x1, y1).
        N)r   ZFPDFPage_SetMediaBox©r   ÚlÚbÚrÚtr   r   r   Úset_mediaboxt   s    zPdfPage.set_mediaboxc                 C   s   |   tj| j|¡S )zc
        Returns:
            The page's CropBox (If not defined, falls back to MediaBox).
        )r(   r   ZFPDFPage_GetCropBoxr,   r+   r   r   r   Úget_cropboxz   s    zPdfPage.get_cropboxc                 C   s   t  | ||||¡ dS )z)
        Set the page's CropBox.
        N)r   ZFPDFPage_SetCropBoxr-   r   r   r   Úset_cropbox�   s    zPdfPage.set_cropboxc                 C   s   |   tj| j|¡S )zc
        Returns:
            The page's BleedBox (If not defined, falls back to CropBox).
        )r(   r   ZFPDFPage_GetBleedBoxr3   r+   r   r   r   Úget_bleedbox‡   s    zPdfPage.get_bleedboxc                 C   s   t  | ||||¡ dS )z*
        Set the page's BleedBox.
        N)r   ZFPDFPage_SetBleedBoxr-   r   r   r   Úset_bleedboxŽ   s    zPdfPage.set_bleedboxc                 C   s   |   tj| j|¡S )zb
        Returns:
            The page's TrimBox (If not defined, falls back to CropBox).
        )r(   r   ZFPDFPage_GetTrimBoxr3   r+   r   r   r   Úget_trimbox”   s    zPdfPage.get_trimboxc                 C   s   t  | ||||¡ dS )z)
        Set the page's TrimBox.
        N)r   ZFPDFPage_SetTrimBoxr-   r   r   r   Úset_trimbox›   s    zPdfPage.set_trimboxc                 C   s   |   tj| j|¡S )za
        Returns:
            The page's ArtBox (If not defined, falls back to CropBox).
        )r(   r   ZFPDFPage_GetArtBoxr3   r+   r   r   r   Ú
get_artbox¡   s    zPdfPage.get_artboxc                 C   s   t  | ||||¡ dS )z(
        Set the page's ArtBox.
        N)r   ZFPDFPage_SetArtBoxr-   r   r   r   Ú
set_artbox¨   s    zPdfPage.set_artboxc                 C   s4   t  ¡ }t  | |¡}|s tdƒ‚|j|j|j|jfS )zz
        Returns:
            The bounding box of the page (the intersection between its media box and crop box).
        z Failed to get page bounding box.)r   ZFS_RECTFZFPDF_GetPageBoundingBoxr   r#   r$   r%   r&   )r   Zrectr'   r   r   r   Úget_bbox¯   s
    zPdfPage.get_bboxc                 C   s.   t  | ¡}|stdƒ‚t|| ƒ}|  |¡ |S )zY
        Returns:
            PdfTextPage: A new text page handle for this page.
        zFailed to load text page.)r   ZFPDFText_LoadPager   r   Z_add_kid)r   Zraw_textpageÚtextpager   r   r   Úget_textpage¾   s    


zPdfPage.get_textpagec                 C   sZ   |j rtdƒ‚|jr(|j| jur(tdƒ‚t | |¡}|s@tdƒ‚| ¡  | |_ | j|_dS )a¾  
        Insert a pageobject into the page.
        
        The pageobject must not belong to a page yet. If it belongs to a PDF, the target page must be part of that PDF.
        
        Position and form are defined by the object's matrix.
        If it is the identity matrix, the object will appear as-is on the bottom left corner of the page.
        
        Parameters:
            pageobj (PdfObject): The pageobject to insert.
        zAThe pageobject you attempted to insert already belongs to a page.zBThe pageobject you attempted to insert belongs to a different PDF.zFailed to insert object.N)ÚpageÚ
ValueErrorr
   r   ZFPDFPage_InsertObjectr   Z_detach_finalizer©r   Zpageobjr'   r   r   r   Ú
insert_objË   s    zPdfPage.insert_objc                 C   s~   |j | urtdƒ‚|jdkrF|jdus*J ‚t |j|¡}d\|_|_n|jdu sTJ ‚t | |¡}|sltdƒ‚d|_ | ¡  dS )a#  
        Remove a pageobject from the page.
        As of PDFium 5692, detached pageobjects may be only re-inserted into existing pages of the same document.
        If the pageobject is not re-inserted into a page, its ``close()`` method may be called.
        
        Note:
            If the object's :attr:`~.PdfObject.type` is :data:`FPDF_PAGEOBJ_TEXT`, any :class:`.PdfTextPage` handles to the page should be closed before removing the object.
        
        Parameters:
            pageobj (PdfObject): The pageobject to remove.
        z@The pageobject you attempted to remove is not part of this page.r   N)r   NzFailed to remove pageobject.)	r>   r?   ÚlevelÚ	containerr   ZFPDFFormObj_RemoveObjectZFPDFPage_RemoveObjectr   Z_attach_finalizerr@   r   r   r   Ú
remove_objå   s    

zPdfPage.remove_objc                 C   s   t  | ¡}|stdƒ‚dS )zê
        Generate page content to apply additions, removals or modifications of pageobjects.
        
        If page content was changed, this function should be called once before saving the document or re-loading the page.
        z Failed to generate page content.N)r   ZFPDFPage_GenerateContentr   )r   r'   r   r   r   Úgen_content  s    
zPdfPage.gen_contentNé   r   c              	   c   sÜ   |rt j}t j}|}n&t j}t j}| }|r<|j| ur<tdƒ‚||ƒ}	|	dk rTtdƒ‚t|	ƒD ]z}
|||
ƒ}|svtdƒ‚t	|| | j
|||d�}|rš|j|v r |V  |jt jkr\||d k r\| j||||d |d�E dH  q\dS )	a¸  
        Iterate through the pageobjects on this page.
        
        Parameters:
            filter (list[int] | None):
                An optional list of pageobject types to filter (:attr:`FPDF_PAGEOBJ_*`).
                Any objects whose type is not contained will be skipped.
                If None or empty, all objects will be provided, regardless of their type.
            max_depth (int):
                Maximum recursion depth to consider when descending into Form XObjects.
            textpage (PdfTextPage | None):
                Text page to pass through to any :class:`.PdfTextObj` instances.
        
        Yields:
            :class:`.PdfObject`: A pageobject.
        z0The given textpage does not belong to this page.r   z$Failed to get number of pageobjects.zFailed to get pageobject.)r>   r
   rC   rB   r<   é   )ÚfilterÚ	max_depthÚformrB   r<   N)r   ZFPDFFormObj_CountObjectsZFPDFFormObj_GetObjectZFPDFPage_CountObjectsZFPDFPage_GetObjectr>   r?   r   Úranger   r
   ÚtypeZFPDF_PAGEOBJ_FORMÚget_objects)r   rH   rI   rJ   rB   r<   Zcount_objectsZ
get_objectr   Z	n_objectsÚiZraw_objZ
helper_objr   r   r   rM     s6    
ûzPdfPage.get_objectsc                 C   s0   | j stdƒ‚t | |¡}|tjkr,tdƒ‚|S )aƒ  
        Flatten form fields and annotations into page contents.
        
        Attention:
            * :meth:`~.PdfDocument.init_forms` must have been called on the parent pdf, before the page was retrieved, for this method to work. In other words, :attr:`.PdfPage.formenv` must be non-null.
            * Flattening may invalidate existing handles to the page, so you'll want to re-initialize these afterwards.
        
        Parameters:
            flag (int): PDFium flattening target (:attr:`FLAT_*`)
        Returns:
            int: PDFium flattening status (:attr:`FLATTEN_*`). :attr:`FLATTEN_FAIL` is handled internally.
        zFpage.flatten() requires prior pdf.init_forms(), before page retrieval.z,Failed to flatten annotations / form fields.)r   ÚRuntimeErrorr   ZFPDFPage_FlattenZFLATTEN_FAILr   )r   ÚflagÚrcr   r   r   ÚflattenG  s    
zPdfPage.flattenrG   )r   r   r   r   Fc                    s¶  t  |  ¡ ˆ  ¡}	t  |  ¡ ˆ  ¡}
|dv r6|
|	 }	}
‡ fdd„|D ƒ}|	|d  |d  }|
|d  |d  }tdd	„ ||fD ƒƒrŽtd
ƒ‚t| fi |¤Ž\}}}}|dur¼|r¼|tjO }|||||d�}| 	|dd||¡ |d  |d  |	|
t
j| f}|| g|¢|‘R }|du �r&tj|Ž  nZtjdd�}t
 |dt¡ | |¡}tjg |¢|‘|‘R Ž }|tjk�svJ dƒ‚t | ¡ |�r¢| j�r¢tj| jg|¢R Ž  t | ¡|f|_|S )a  
        Rasterize the page to a :class:`.PdfBitmap`.
        
        Parameters:
            
            scale (float):
                A factor scaling the number of pixels per PDF canvas unit. This defines the resolution of the image.
                To convert a DPI value to a scale factor, multiply it by the size of 1 canvas unit in inches (usually 1/72in). [#user_unit]_
            
            rotation (int):
                Additional rotation in degrees (0, 90, 180, or 270).
            
            crop (tuple[float, float, float, float]):
                Amount to cut off from view (left, bottom, right, top), in PDF canvas units.
                Rendering crop applies on bitmap level (i.e. after rotation), unlike changing the page cropbox using :meth:`.set_cropbox`.
                Negative crop is not supported (though no exception will be raised). It may produce a larger canvas but not actually expand the rendering area, as of PDFium 7825.
            
            may_draw_forms (bool):
                If True, render form fields (provided the document has forms and :meth:`~.PdfDocument.init_forms` was called).
            
            bitmap_maker (typing.Callable):
                Callback function used to create the :class:`.PdfBitmap`.
            
            fill_color (tuple[int, int, int, int]):
                Color the bitmap will be filled with before rendering. This uses RGBA syntax regardless of the pixel format used, with values from 0 to 255.
                If the fill color is not opaque (i.e. has transparency), ``{BGR,RGB}A`` will be used.
            
            grayscale (bool):
                If True, render in grayscale mode.
            
            optimize_mode (None | str):
                Page rendering optimization mode (None, "lcd", "print").
            
            draw_annots (bool):
                If True, render page annotations.
            
            no_smoothtext (bool):
                If True, disable text anti-aliasing. Overrides ``optimize_mode="lcd"``.
            
            no_smoothimage (bool):
                If True, disable image anti-aliasing.
            
            no_smoothpath (bool):
                If True, disable path anti-aliasing.
            
            force_halftone (bool):
                If True, always use halftone for image stretching.
            
            limit_image_cache (bool):
                If True, limit image cache size.
            
            rev_byteorder (bool):
                If True, render with reverse byte order, leading to ``RGB{A/x}`` output rather than ``BGR{A/x}``.
                Other pixel formats are not affected.
            
            prefer_bgrx (bool):
                If True, use 4-byte ``{BGR/RGB}x`` rather than 3-byte ``{BGR/RGB}`` (i.e. add an unused byte).
                Other pixel formats are not affected.
            
            maybe_alpha (bool):
                If True, use a pixel format with alpha channel (i.e. ``{BGR/RGB}A``) if page content has transparency.
                This is recommended for performance in these cases, but as page-dependent format selection can be unexpected, it is not enabled by default.
            
            force_bitmap_format (int | None):
                If given, override automatic pixel format selection and enforce use of the given format (one of the :attr:`FPDFBitmap_*` constants). In this case, you should not pass any other format selection options, except potentially *rev_byteorder*.
            
            extra_flags (int):
                Additional PDFium rendering flags. May be combined with bitwise OR (``|`` operator).
            
            color_scheme (PdfColorScheme | None):
                A custom pdfium color scheme. Note that this may flatten different colors into one, so the usability of this is limited.
            
            fill_to_stroke (bool):
                If a *color_scheme* is given, whether to only draw borders around fill areas using the `path_stroke` color, instead of filling with the `path_fill` color.
        
        Returns:
            PdfBitmap: Bitmap of the rendered page.
        
        .. admonition:: Format selection
            
            This is the format selection hierarchy used by :meth:`.render`, from lowest to highest priority:
            
            * default: ``BGR``
            * ``prefer_bgrx=True``: ``BGRx``
            * ``grayscale=True``: ``L``
            * ``maybe_alpha=True``: ``BGRA`` if the page has transparency, else the format selected otherwise
            * ``fill_color[3] < 255``: ``BGRA`` (background color with transparency)
            * ``force_bitmap_format=...`` -> any supported by pdfium
            
            Additionally, ``rev_byteorder=True`` will swap ``BGR{A/x}`` to ``RGB{A/x}`` if applicable.
        
        .. [#user_unit] Since PDF 1.6, pages may define an additional user unit factor. In this case, 1 canvas unit is equivalent to ``user_unit * (1/72)`` inches. PDFium does not currently provide an API to get the user unit, so this is not taken into account.
        )éZ   i  c                    s   g | ]}t  |ˆ  ¡‘qS r   )ÚmathÚceil)Ú.0Úc©Úscaler   r   Ú
<listcomp>Ï  r*   z"PdfPage.render.<locals>.<listcomp>r   é   rG   é   c                 s   s   | ]}|d k V  qdS )rG   Nr   )rV   Údr   r   r   Ú	<genexpr>Ò  r*   z!PdfPage.render.<locals>.<genexpr>zCrop exceeds page dimensionsN)ÚformatÚrev_byteorder)ÚversionZNeedToPauseNowz0Progressive render return code indicates failure)rT   rU   r   r   Úanyr?   Ú_parse_renderoptsr   ZFPDF_CONVERT_FILL_TO_STROKEZ	fill_rectr   r   ZFPDF_RenderPageBitmapZIFSDK_PAUSEZset_callbackÚ_pause_noopÚconvertZ*FPDF_RenderPageBitmapWithColorScheme_StartZFPDF_RENDER_FAILEDZFPDF_RenderPage_Closer   ZFPDF_FFLDrawÚweakrefÚrefZ_render_args)r   rY   r   ZcropZmay_draw_formsZbitmap_makerZcolor_schemeZfill_to_strokeÚkwargsZ	src_widthZ
src_heightÚwidthÚheightÚ	cl_formatr`   Ú
fill_colorÚflagsZbitmapZpos_argsZrender_argsÚpauseÚfpdf_csÚstatusr   rX   r   Úrendera  s8    i

 


zPdfPage.render)T)T)T)T)T)NrF   Nr   N)&Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Ústaticmethodr   Úpropertyr   r   r   r   r   r   r(   r,   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r=   rA   rD   rE   rM   r   ZFLAT_NORMALDISPLAYrR   r   Z
new_nativerq   Ú__classcell__r   r   r   r   r      sJ   



	




!
6ør   c                 C   s>   |d dk s|r t  | ¡r t jS |r*t jS |r4t jS t jS d S )Nr\   éÿ   )r   ZFPDFPage_HasTransparencyZFPDFBitmap_BGRAÚFPDFBitmap_GrayZFPDFBitmap_BGRxZFPDFBitmap_BGR)r>   rl   Ú	grayscaleÚprefer_bgrxÚmaybe_alphar   r   r   Ú_auto_bitmap_formatð  s    r~   ©ry   ry   ry   ry   FTc                 C   sî   |d u rt | ||||ƒ}n|}|tjkr,d}
|}|r>|tjO }|rL|tjO }|rZ|tjO }|rh|tjO }|rv|tjO }|r„|tjO }|	r’|tj	O }|
r |tj
O }|râ| ¡ }|dkrÀ|tjO }n"|dkrÔ|tjO }ntd|› �ƒ‚||
||fS )NFZlcdÚprintzInvalid optimize_mode )r~   r   rz   ZFPDF_GRAYSCALEZ
FPDF_ANNOTZFPDF_RENDER_NO_SMOOTHTEXTZFPDF_RENDER_NO_SMOOTHIMAGEZFPDF_RENDER_NO_SMOOTHPATHZFPDF_RENDER_FORCEHALFTONEZFPDF_RENDER_LIMITEDIMAGECACHEZFPDF_REVERSE_BYTE_ORDERÚlowerZFPDF_LCD_TEXTZFPDF_PRINTINGr?   )r>   rl   r{   Zoptimize_modeZdraw_annotsZno_smoothtextZno_smoothimageZno_smoothpathZforce_halftoneZlimit_image_cacher`   r|   r}   Zforce_bitmap_formatÚextra_flagsrk   rm   r   r   r   rc   ý  s<    








rc   c                   @   s(   e Zd ZdZdd„ Zdd„ Zdd„ ZdS )	r   z�
    Rendering color scheme.
    Each color shall be provided as a list of values for red, green, blue and alpha, ranging from 0 to 255.
    c                 C   s   t ||||d�| _d S )N)Zpath_fill_colorZpath_stroke_colorZtext_fill_colorZtext_stroke_color)ÚdictÚcolors)r   Z	path_fillZpath_strokeZ	text_fillZtext_stroker   r   r   r   <  s    þzPdfColorScheme.__init__c                 C   s   t | ƒj› d| j› d�S )Nz(**ú))rL   rr   r„   r   r   r   r   Ú__repr__B  s    zPdfColorScheme.__repr__c                 C   s4   t  ¡ }| j ¡ D ]\}}t||t ||¡ƒ q|S )z\
        Returns:
            The color scheme as :class:`FPDF_COLORSCHEME` object.
        )r   ZFPDF_COLORSCHEMEr„   ÚitemsÚsetattrr   Zcolor_tohex)r   r`   ro   Úkeyr!   r   r   r   re   E  s    zPdfColorScheme.convertN)rr   rs   rt   ru   r   r†   re   r   r   r   r   r   6  s   r   c                 C   s   dS )NFr   )Úargr   r   r   rd   P  s    rd   )r   FNTFFFFFFFFNr   )Ú__all__rT   ÚctypesÚloggingrf   Zpypdfium2.rawr	   r   Zpypdfium2.internalZinternalr   Zpypdfium2._helpers.miscr   Zpypdfium2._helpers.bitmapr   Zpypdfium2._helpers.textpager   Zpypdfium2._helpers.pageobjectsr   r    Ú	getLoggerrr   ÚloggerZAutoCloseabler   r~   rc   r   rd   r   r   r   r   Ú<module>   sD   
   ^              ñ
9