
    Ng?N                         d 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j        e          Z G d de	j                  Zd	 Z	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ G d d          ZdS ))PdfPagePdfColorScheme    N)PdfiumError)	PdfBitmap)PdfTextPage)	PdfObjectc                       e Zd ZdZ fdZed             Zed             Zd Z	d Z
d Zd Zd	 Zd
 Zd$dZd Zd$dZd Zd$dZd Zd$dZd Zd$dZd Zd Zd Zd Zd Zd Zd%dZej         fdZ!d dd!de"j#        dd"fd#Z$ xZ%S )&r   z
    Page helper class.
    
    Attributes:
        raw (FPDF_PAGE): The underlying PDFium page handle.
        pdf (PdfDocument): Reference to the document this page belongs to.
    c                     |||c| _         | _        | _        t                                          t
          j        | j                   d S N)rawpdfformenvsuper__init__r   _close_impl)selfr   r   r   	__class__s       S/var/www/html/ai-engine/env/lib/python3.11/site-packages/pypdfium2/_helpers/page.pyr   zPdfPage.__init__   s>    +.W($(DL,dl;;;;;    c                 \    |rt          j        | |           t          j        |            d S r   )pdfium_cFORM_OnBeforeClosePageFPDF_ClosePage)r   r   s     r   r   zPdfPage._close_impl"   s4     	:+C999$$$$$r   c                     | j         S r   )r   r   s    r   parentzPdfPage.parent)   s     xr   c                 *    t          j        |           S )z`
        Returns:
            float: Page width (horizontal size), in PDF canvas units.
        )r   FPDF_GetPageWidthFr   s    r   	get_widthzPdfPage.get_width/   s    
 *4000r   c                 *    t          j        |           S )z_
        Returns:
            float: Page height (vertical size), in PDF canvas units.
        )r   FPDF_GetPageHeightFr   s    r   
get_heightzPdfPage.get_height6   s    
 +D111r   c                 R    |                                  |                                 fS )zb
        Returns:
            (float, float): Page width and height, in PDF canvas units.
        )r   r"   r   s    r   get_sizezPdfPage.get_size=   s#    
   $//"3"344r   c                 J    t           j        t          j        |                    S )zO
        Returns:
            int: Clockwise page rotation in degrees.
        )pdfium_iRotationToDegreesr   FPDFPage_GetRotationr   s    r   get_rotationzPdfPage.get_rotationG   s    
 )8+H+N+NPPr   c                 P    t          j        | t          j        |                    dS )z\
        Define the absolute, clockwise page rotation (0, 90, 180, or 270 degrees).
        N)r   FPDFPage_SetRotationr&   RotationToConst)r   rotations     r   set_rotationzPdfPage.set_rotationN   s%     	%dH,DX,NOOOOOr   c                     t                      t                      t                      t                      f\  }}}} || ||||          }|s|r
 |            nd S |j        |j        |j        |j        fS r   )c_floatvalue)	r   box_funcfallback_funcfallback_okleftbottomrighttopoks	            r   _get_boxzPdfPage._get_boxU   st    #*99giiGII#M feSXdD&%55 	>'2<MMOOO=
FL%+syAAr   Tc                 F    |                      t          j        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.
        Note:
            Due to quirks in PDFium's public API, all ``get_*box()`` functions except :meth:`.get_bbox`
            do not inherit from parent nodes in the page tree (as of PDFium 5418).
        c                      dS )N)r   r   id  i   r=   r   r   <lambda>z&PdfPage.get_mediabox.<locals>.<lambda>i   s    DT r   )r:   r   FPDFPage_GetMediaBoxr   r4   s     r   get_mediaboxzPdfPage.get_mediabox^   s"     }}X:<T<TVabbbr   c                 6    t          j        | ||||           dS )zn
        Set the page's MediaBox by passing four :class:`float` coordinates (usually x0, y0, x1, y1).
        N)r   FPDFPage_SetMediaBoxr   lbrts        r   set_mediaboxzPdfPage.set_mediaboxk   #     	%dAq!Q77777r   c                 N    |                      t          j        | j        |          S )zc
        Returns:
            The page's CropBox (If not defined, falls back to MediaBox).
        )r:   r   FPDFPage_GetCropBoxrA   r@   s     r   get_cropboxzPdfPage.get_cropboxq   s     
 }}X94;LkZZZr   c                 6    t          j        | ||||           dS )z)
        Set the page's CropBox.
        N)r   FPDFPage_SetCropBoxrD   s        r   set_cropboxzPdfPage.set_cropboxx   #     	$T1aA66666r   c                 N    |                      t          j        | j        |          S )zc
        Returns:
            The page's BleedBox (If not defined, falls back to CropBox).
        )r:   r   FPDFPage_GetBleedBoxrM   r@   s     r   get_bleedboxzPdfPage.get_bleedbox~   s     
 }}X:D<LkZZZr   c                 6    t          j        | ||||           dS )z*
        Set the page's BleedBox.
        N)r   FPDFPage_SetBleedBoxrD   s        r   set_bleedboxzPdfPage.set_bleedbox   rJ   r   c                 N    |                      t          j        | j        |          S )zb
        Returns:
            The page's TrimBox (If not defined, falls back to CropBox).
        )r:   r   FPDFPage_GetTrimBoxrM   r@   s     r   get_trimboxzPdfPage.get_trimbox   s     
 }}X94;K[YYYr   c                 6    t          j        | ||||           dS )z)
        Set the page's TrimBox.
        N)r   FPDFPage_SetTrimBoxrD   s        r   set_trimboxzPdfPage.set_trimbox   rQ   r   c                 N    |                      t          j        | j        |          S )za
        Returns:
            The page's ArtBox (If not defined, falls back to CropBox).
        )r:   r   FPDFPage_GetArtBoxrM   r@   s     r   
get_artboxzPdfPage.get_artbox   s     
 }}X8$:JKXXXr   c                 6    t          j        | ||||           dS )z(
        Set the page's ArtBox.
        N)r   FPDFPage_SetArtBoxrD   s        r   
set_artboxzPdfPage.set_artbox   s#     	#D!Q155555r   c                     t          j                    }t          j        | |          }|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   FS_RECTFFPDF_GetPageBoundingBoxr   r5   r6   r7   r8   )r   rectr9   s      r   get_bboxzPdfPage.get_bbox   sS    
  ""-dD99 	B@AAA	4;
DH==r   c                     t          j        |           }|st          d          t          ||           }|                     |           |S )zY
        Returns:
            PdfTextPage: A new text page handle for this page.
        zFailed to load text page.)r   FPDFText_LoadPager   r   _add_kid)r   raw_textpagetextpages      r   get_textpagezPdfPage.get_textpage   sQ    
  1$77 	;9:::|T22hr   c                     |j         rt          d          |j        r|j        | j        urt          d          t          j        | |           |                                 | |_         | j        |_        dS )a  
        Insert a page object into the page.
        
        The page object must not belong to a page yet. If it belongs to a PDF, this page must be part of the 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 page object to insert.
        zAThe pageobject you attempted to insert already belongs to a page.zBThe pageobject you attempted to insert belongs to a different PDF.N)page
ValueErrorr   r   FPDFPage_InsertObject_detach_finalizer)r   pageobjs     r   
insert_objzPdfPage.insert_obj   s     < 	b`aaa; 	cGKtx77abbb&tW555!!###hr   c                     |j         | urt          d          t          j        | |          }|st	          d          d|_         |                                 dS )ab  
        Remove a page object from the page.
        As of PDFium 5692, detached page objects may be only re-inserted into existing pages of the same document.
        If the page object is not re-inserted into a page, its ``close()`` method may be called.
        
        Parameters:
            pageobj (PdfObject): The page object to remove.
        zAThe page object you attempted to remove is not part of this page.zFailed to remove pageobject.N)rp   rq   r   FPDFPage_RemoveObjectr   _attach_finalizer)r   rt   r9   s      r   
remove_objzPdfPage.remove_obj   sh     <t##`aaa+D':: 	><===!!#####r   c                 P    t          j        |           }|st          d          dS )z
        Generate page content to apply additions, removals or modifications of page objects.
        
        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   FPDFPage_GenerateContentr   )r   r9   s     r   gen_contentzPdfPage.gen_content   s8     .t44 	B@AAA	B 	Br   N   r   c              #     K   |rt           j        }t           j        }|}nt           j        }t           j        }| } ||          }|dk     rt          d          t          |          D ]}	 |||	          }
|
t          d          t          |
| | j        |          }| 	                    |           |r	|j
        |v r|V  |j
        t           j        k    r+||dz
  k     r"|                     |||
|dz             E d{V  dS )a?  
        Iterate through the page objects on this page.
        
        Parameters:
            filter (list[int] | None):
                An optional list of page object 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.
        
        Yields:
            :class:`.PdfObject`: A page object.
        r   z%Failed to get number of page objects.NzFailed to get page object.)rp   r   level   )filter	max_depthformr   )r   FPDFFormObj_CountObjectsFPDFFormObj_GetObjectFPDFPage_CountObjectsFPDFPage_GetObjectr   ranger   r   rk   typeFPDF_PAGEOBJ_FORMget_objects)r   r   r   r   r   count_objects
get_objectr   	n_objectsiraw_obj
helper_objs               r   r   zPdfPage.get_objects   s^     $  	$=M!7JFF$:M!4JF!M&))	q==EFFFy!! 	 	A j++G!">???"7485QQQJMM*%%% !Z_66    ("<<<STATAT++# )"!AI	 ,         	 	r   c                 n    t          j        | |          }|t           j        k    rt          d          |S )a3  
        Attempt to flatten annotations and form fields into the page contents.
        
        Parameters:
            flag (int): PDFium flattening target (:attr:`FLAT_*`)
        Returns:
            int: PDFium flattening status (:attr:`FLATTEN_*`). :attr:`FLATTEN_FAIL` is handled internally.
        z,Failed to flatten annotations / form fields.)r   FPDFPage_FlattenFLATTEN_FAILr   )r   flagrcs      r   _flattenzPdfPage._flatten-  s8     &tT22&&&LMMM	r   r   )r   r   r   r   Fc                    t          j        |                                 z            }	t          j        |                                 z            }
|dv r|
|	}
}	fd|D             }|	|d         z
  |d         z
  }|
|d         z
  |d         z
  }t	          d ||fD                       rt          d          t          di |\  }}}}||r|t          j        z  } |||||
          }|	                    dd|||           || |d          |d          |	|
t          j        |         |f}|t          j        |  n|t          j        d          }t          j        |dd            |                    |          }t          j        g |||R  }|t          j        k    sJ t          j        |            |r| j        rt          j        | j        g|R   |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 in PDF canvas units to cut off from page borders (left, bottom, right, top). Crop is applied after rotation.
                
            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`.
                
            color_scheme (PdfColorScheme | None):
                An optional, custom rendering color scheme.
                
            fill_to_stroke (bool):
                If True and rendering with custom color scheme, fill paths will be stroked.
                
            fill_color (tuple[int, int, int, int]):
                Color the bitmap will be filled with before rendering (RGBA values from 0 to 255).
                
            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 instead of ``BGR(A/X)``.
                Other pixel formats are not affected.
                
            prefer_bgrx (bool):
                If True, prefer four-channel over three-channel pixel formats, even if the alpha byte is unused.
                Other pixel formats are not affected.
                
            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).
                
            extra_flags (int):
                Additional PDFium rendering flags. May be combined with bitwise OR (``|`` operator).
        
        Returns:
            PdfBitmap: Bitmap of the rendered page.
        
        .. [#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 currently does not have an API to get the user unit, so this is not taken into account.
        )Z   i  c                 >    g | ]}t          j        |z            S r=   )mathceil).0cscales     r   
<listcomp>z"PdfPage.render.<locals>.<listcomp>  s'    111q	!E'""111r   r   r}   r      c              3   "   K   | ]
}|d k     V  dS )r   Nr=   )r   ds     r   	<genexpr>z!PdfPage.render.<locals>.<genexpr>  s&      ..q1u......r   zCrop exceeds page dimensionsN)formatrev_byteorder)versionNeedToPauseNowc                     dS )NFr=   )_s    r   r>   z PdfPage.render.<locals>.<lambda>  s    U r   r=   )r   r   r   r"   anyrq   _parse_renderoptsr   FPDF_CONVERT_FILL_TO_STROKE	fill_rectr&   r,   FPDF_RenderPageBitmapIFSDK_PAUSEset_callbackconvert*FPDF_RenderPageBitmapWithColorScheme_StartFPDF_RENDER_DONEFPDF_RenderPage_Closer   FPDF_FFLDraw)r   r   r-   cropmay_draw_formsbitmap_makercolor_schemefill_to_strokekwargs	src_width
src_heightwidthheight	cl_formatr   
fill_colorflagsbitmaprender_argspausefpdf_csstatuss    `                    r   renderzPdfPage.renderB  s3   j Yt~~//5899	Yt005899
y  $.	zI1111D111d1g%Q/d1g%Q/..ufo..... 	=;<<<6G6Q6Q&6Q6Q3	=*e$.$X99EeVI][[[Aufj999td1gXQxJPXPhiqPrtyz*K888 (333E!%)9??KKK"**=99GHf+fW^f`efffFX66666*4000 	>dl 	>!$,=====r   )T)Nr}   Nr   )&__name__
__module____qualname____doc__r   staticmethodr   propertyr   r   r"   r$   r)   r.   r:   rA   rI   rM   rP   rT   rW   rZ   r]   r`   rc   rh   rn   ru   ry   r|   r   r   FLAT_NORMALDISPLAYr   r   
new_nativer   __classcell__)r   s   @r   r   r      sS        < < < < <
 % % \%   X
1 1 12 2 25 5 5Q Q QP P PB B Bc c c c8 8 8[ [ [ [7 7 7[ [ [ [8 8 8Z Z Z Z7 7 7Y Y Y Y6 6 6	> 	> 	>
 
 
  0$ $ $(B B B0 0 0 0h %7    . !$/"x x x x x x x xr   r   c                     | d         dk     rt           j        S |rt           j        S |rt           j        S t           j        S )Nr      )r   FPDFBitmap_BGRAFPDFBitmap_GrayFPDFBitmap_BGRxFPDFBitmap_BGR)r   	grayscaleprefer_bgrxs      r   _auto_bitmap_formatr     sG     	1''	 '''	 '''&&r   r   r   r   r   FTc                    |t          | ||
          }n|}|t          j        k    rd}	|}|r|t          j        z  }|r|t          j        z  }|r|t          j        z  }|r|t          j        z  }|r|t          j        z  }|r|t          j        z  }|r|t          j	        z  }|	r|t          j
        z  }|rR|                                }|dk    r|t          j        z  }n(|dk    r|t          j        z  }nt          d|           ||	| |fS )NFlcdprintzInvalid optimize_mode )r   r   r   FPDF_GRAYSCALE
FPDF_ANNOTFPDF_RENDER_NO_SMOOTHTEXTFPDF_RENDER_NO_SMOOTHIMAGEFPDF_RENDER_NO_SMOOTHPATHFPDF_RENDER_FORCEHALFTONEFPDF_RENDER_LIMITEDIMAGECACHEFPDF_REVERSE_BYTE_ORDERlowerFPDF_LCD_TEXTFPDF_PRINTINGrq   )r   r   optimize_modedraw_annotsno_smoothtextno_smoothimageno_smoothpathforce_halftonelimit_image_cacher   r   force_bitmap_formatextra_flagsr   r   s                  r   r   r     sX     "'
I{KK		'	H,,,E )(( %$$ 433 544 433 433 877 211 G%++--E!!X++EEg%%X++EEEmEEFFF mZ66r   c                       e Zd ZdZd Z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                 6    t          ||||          | _        d S )N)path_fill_colorpath_stroke_colortext_fill_colortext_stroke_color)dictcolors)r   	path_fillpath_stroke	text_filltext_strokes        r   r   zPdfColorScheme.__init__  s&    %%
 
 
r   c           	          t          j                    }| j                                        D ])\  }}t	          ||t          j        ||                     *|S )z\
        Returns:
            The color scheme as :class:`FPDF_COLORSCHEME` object.
        )r   FPDF_COLORSCHEMEr   itemssetattrr&   color_tohex)r   r   r   keyr1   s        r   r   zPdfColorScheme.convert  s\    
 +--+++-- 	N 	NJCGS("6um"L"LMMMMr   N)r   r   r   r   r   r   r=   r   r   r   r     s<         

 
 
    r   r   )r   FNTFFFFFFFNr   )__all__r   ctypesloggingpypdfium2.rawr   r   pypdfium2.internalinternalr&   pypdfium2._helpers.miscr   pypdfium2._helpers.bitmapr   pypdfium2._helpers.textpager   pypdfium2._helpers.pageobjectsr   r0   	getLoggerr   loggerAutoCloseabler   r   r   r   r=   r   r   <module>r     sa   (                % % % % % % / / / / / / / / / / / / 3 3 3 3 3 3 4 4 4 4 4 4
.		8	$	$f f f f fx% f f fR
' 
' 
' *!"47 47 47 47n         r   