U
    :vhj}                 
   @   sD  d dl Z d dlZd dlZd dlZd dl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mZ d dlmZ d dlmZ d dlmZ d dlmZ d d	lmZ d d
lmZmZmZmZmZmZ zd dlm Z  d dl!m"Z" W n e#k
r   d\Z Z"Y nX zd dl$m%Z% W n. e#k
rF   e&d G dd dZ%Y nX ddl'm(Z( ddl)m*Z*m+Z+m,Z,m-Z- ddl.m/Z/m0Z0 ddl1m2Z2m3Z3m4Z4 ddl5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z= ddl>m?Z? ddl@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZY ddlZm[Z[m\Z\m]Z] ddl^m_Z_m`Z`maZambZbmcZcmdZd ddlemfZf ddlgmhZh ddlimjZjmkZkmlZlmmZm ddlnmoZompZpmqZqmrZr dd lsmtZt dd!lumvZvmwZwmxZxmyZy dd"lzm{Z{ dd#l|m}Z}m~Z~mZmZmZmZmZmZ dd$lmZ dd%lmZ dd&lmZ dd'lmZmZ dd(lmZmZmZ dd)lmZmZ dd*lmZmZ dd+lmZ dd,lmZmZ dd-lmZmZ d.Zd/d0d1d2d3d4ZeeZee jZed5 ZdeLjeLjeLjd6ZG d7d8 d8eZdId9d:Zd;d< ZG d=d> d>efeZe2eje _d?d@iZd>dAdBd:dCdDdEdFdGdHg
ZdS )J    N)defaultdict)contextmanager)datetimetimezonewraps)isclose)Number)splitext)Path)CallableDictIterator
NamedTupleOptionalUnion)pkcs12)signerNN)ImagezFPillow could not be imported - fpdf2 will not be able to add any imagec                   @   s   e Zd ZdS )r   N)__name__
__module____qualname__ r   r   -/tmp/pip-unpacked-wheel-dvf6lv8i/fpdf/fpdf.pyr   +   s   r      )	URIAction)DEFAULT_ANNOT_FLAGSAnnotationDictPDFAnnotationPDFEmbeddedFile)BidiParagraphauto_detect_base_direction) WarnOnDeprecatedModuleAttributesget_stack_levelsupport_deprecated_txt_arg)	DeviceRGBDrawingContextGraphicsStateDictRegistryGraphicsStylePaintedPathPoint	Transformconvert_to_device_color)StandardSecurityHandler)AccessPermissionAlignAngleAnnotationFlagAnnotationNameCharVPosCornerEncryptionMethodFileAttachmentAnnotationNameMethodReturnValuePageLabelStyle
PageLayoutPageModePageOrientationPathPaintRulePDFResourceTypeRenderStyleTextDirectionTextEmphasisTextMarkupTypeTextModeWrapModeXPosYPosOutputIntentSubType)FPDFExceptionFPDFPageFormatExceptionFPDFUnicodeEncodingException)CoreFont
CORE_FONTSFontFace	TextStyle
TitleStyleTTFFont)GraphicsStateMixin)	HTML2FPDF)
ImageCache	ImageInfoRasterImageInfoVectorImageInfo)SUPPORTED_IMAGE_FILTERSget_img_info
load_imagepreload_image)LinearizedOutputProducer)FragmentMultiLineBreakTextLineTotalPagesSubstitutionFragment)OutlineSection)ZOOM_CONFIGSOutputProducerPDFPagePDFPageLabelResourceCatalogstream_content_for_raster_imagePDFICCProfileOutputIntentDictionary)FPDFRecorder)	Signature)StructureTreeBuilder)Percent	SVGObject)DestinationXYZPDFArrayPDFDate)Tabledraw_box_borders)TextRegionMixinTextColumns)
Transition)UnicodeScriptget_unicode_script)get_scale_factorPaddingz2.8.3)QO@g33333@)
ףp=@rz   )gףp=
Oz@r{   )d  i  )r|   i  )a3Za4Za5letterZlegalfont)defaultZsingle
continuousZtwoc                   @   sF   e Zd ZU eed< eed< eed< eed< dZeed< dZe	ed< d	S )
ToCPlaceholderrender_function
start_pageypage_orientationr   pagesTreset_page_indicesN)
r   r   r   r   __annotations__intstrr   r   boolr   r   r   r   r      s   
r   c              
   C   s   t | tr.|  } | tkr"t|  S t| dd|dkrBt| ddz| d | | d | fW S  tk
r } z"|  d| }td| |W 5 d}~X Y nX dS )	aO  Return page width and height size in points.

    Throws FPDFPageFormatException

    `format` can be either a 2-tuple or one of 'a3', 'a4', 'a5', 'letter', or
    'legal'.

    If format is a tuple, then the return value is the tuple's values
    given in the units specified on this document in the constructor,
    multiplied by the corresponding scale factor `k`, taken from instance
    variable `self.k`.

    If format is a string, the (width, height) tuple returned is in points.
    For a width and height of 8.5 * 11, 72 dpi is assumed, so the value
    returned is (8.5 * 72, 11 * 72), or (612, 792). Additional formats can be
    added by adding fields to the `PAGE_FORMATS` dictionary with a
    case insensitive key (the name of the new format) and 2-tuple value of
    (width, height) in dots per inch with a 72 dpi resolution.
    T)unknownN)Zoner   r   z, zArguments must be numbers: )
isinstancer   lowerPAGE_FORMATSrI   	Exception)formatkeargsr   r   r   get_page_format   s    
r   c                    s   t   fdd}|S )z$Decorator to protect drawing methodsc                    s2   | j s"|ds"|ds"td | f||S )Ndry_run
split_only/No page open, you need to call add_page() first)pagegetrH   selfr   kwargsfnr   r   wrapper   s    zcheck_page.<locals>.wrapperr   )r   r   r   r   r   
check_page   s    r   c                       s
  e Zd ZdZdZdZdZdZdZe	
de	jZdZd	Ze	
d
Ze	
dZeZd` fdd	Zdeje dfddZdd Zdd ZeedddZeedddZee dddZ!e!j"d d Z!ed!d" Z#dae$e%e%e%e&e%d#d$d%Z'ed&d' Z(ed(d) Z)ed*d+ Z*d,d- Z+dbd/d0Z,d1d2 Z-d3d4 Z.d5d6 Z/dcd8d9Z0ed:d; Z1d<d= Z2ddd?d@Z3deee4e5e%e6f e%e%dAdBdCZ7edDdE Z8e8j"dFdE Z8dGdH Z9dIdJ Z:dKdL Z;dMdN Z<dOdP Z=dQdR Z>dSdT Z?dUdV Z@dfdWdXZAdYdZ ZBd[d\ ZCd]d^ ZDdgd`daZEeFdhe5e%eGf e%eHdbdcddZIdie%e%eeJeKe5e%eGf e%eHdfdgdhZLdidj ZMdjdkdlZNdmdn ZOdodp ZPdqdr ZQdsdt ZRdkdudvZSdldwdxZTdmdydzZUdnd{d|ZVd}d~ ZWdd ZXeYeFdoddZZeYeFdd Z[dd Z\eYd7d7e]j^dfddZ_dpddZ`dqddZadd ZbeFdd ZceFdrddZdeFdsddZeeFdtddZfeFduddZgdd ZheFdvddZidd ZjeFdwddZkeFdxddZleFdyddZmeFdzddZnd{ddZod|ddZpd}ddZqd~e5e%ef dddZrdd ZsdddZtdd Zudd ZvdddZwdddZxdddZyeFdddZzdddÄZ{eFddde|fddńZ}eFdddǄZ~eFdddɄZeFdd˄ ZeYdddτZeYddф ZeFdddӄZeFdddՄZeFedddׄZeFdddلZeFeYdddۄZeFeYddd݄ZeFeYdd߄ ZeFeYdd ZdddZdd Zedd ZeFeddded7dejddeddejejfddZdd7ejejddedddf	eeJe5e%eHf eeee%eed	ddZdd Zdd Zdd ZdddZe%eee dddZdd Zdd Zdd Zdd ZeYd d ZeFedded7ejdddeddddejejejdejdd7fedddZeFeddededejfeJe%e%eedddZeFddddddd	ddddejdfee% ee% eeHeJee5ee%f eJeJeJeeed
ddZeFdddZdedddZdd ZdeedddZdd ZdddZeYdd Zdd ZeFddd Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zdd-ddddejejffd.d/ZeFd0d-ddddejejffd1d2ZŐd3d4 ZƐd5d6 Zǐd7d8 ZȐdd9d:Zɐdd;d<Zʐd=d> ZeFedd?d@ZeFeddCdDZeFeYdEdF ZeFeYdGdH ZeFeYdIdJ ZeYdKdL ZeYdMdN ZeFdeeHeedOdPdQZԐddRdSZeFddTdUZeYeאdVdWdXZeYeِdYdZd[ZeFeYd\d] Zdededefd^d_Z݇  ZS (  FPDFzPDF Generation classz**__z~~z--\z^\[([^][]+)\]\(([^()]+)\)(.*)$NTz/(GS\d+) gsz
/I(\d+) DoportraitmmA4
DEPRECATEDc                    s^  |dkrt jdtt d t   d| _d| _i | _i | _	i | _
g | _t | _d| _d| _d| _|   d| _d| _d| _d| _d| _d| _d| _t | _d| _g | _d| _d| _d| _i | _ d| _!d| _"i | _#d	| _$d
ddd| _%t&|| _'d| _(d| _)d| _*d| _+d| _,d| _-d| _.d| _/d| _0| j1| _2| j3| _4| j5| _6d| _7t8dddd| _9d| j' | _:t;j<| _=t>|| j'\| _?| _@| A|| j?| j@ | jB| _Cd| j' }d\| _D| _E| _F| _G| H|| | jF| jG | _D| _E|d | _I| Jdd|  | Kd d| _Ld| _Md| _Nd| _OtPQtRjS| _Td| _Ug | _Vd| _Wd| _XtY | _Zd| _[t\ | _]t^t_| _`d| _adS )ak  
        Args:
            orientation (str): possible values are "portrait" (can be abbreviated "P")
                or "landscape" (can be abbreviated "L"). Default to "portrait".
            unit (str, int, float): possible values are "pt", "mm", "cm", "in", or a number.
                A point equals 1/72 of an inch, that is to say about 0.35 mm (an inch being 2.54 cm).
                This is a very common unit in typography; font sizes are expressed in this unit.
                If given a number, then it will be treated as the number of points per unit.  (eg. 72 = 1 in)
                Default to "mm".
            format (str): possible values are "a3", "a4", "a5", "letter", "legal" or a tuple
                (width, height) expressed in the given unit. Default to "a4".
            font_cache_dir (Path or str): [**DEPRECATED since v2.5.1**] unused
        r   zV"font_cache_dir" parameter is deprecated since v2.5.1, unused and will soon be removed
stacklevelFr   NT   latin-1Z	helveticaZcouriertimes)ZarialZ
couriernewZtimesnewroman    d   dashgapphaseg/$?gbX<@)r   r   r   r   g      $@Z	fullwidthz1.3)bwarningswarnDeprecationWarningr$   super__init__Zsingle_resources_objectr   r   fontslinksembedded_filesrS   image_cache	in_footer_in_unbreakable_lasthalias_nb_pages_anglexmp_metadatapage_durationpage_transitionallow_images_transparencyoversized_imagesoversized_images_ratiork   struct_buildertoc_placeholder_outlinein_toc_rendering_toc_allow_page_insertion_toc_inserted_pages_output_intents	_sign_keytitlesection_title_stylescore_fonts_encodingfont_aliasesrx   r   font_family
font_style	underlinestrikethroughfont_size_ptfont_stretchingchar_spacingcurrent_fontcurrent_font_is_set_on_pageDEFAULT_DRAW_COLOR
draw_colorDEFAULT_FILL_COLOR
fill_colorZDEFAULT_TEXT_COLOR
text_colorpage_backgrounddictdash_pattern
line_widthrC   FILL	text_moder   dw_ptdh_pt_set_orientationcur_orientationdef_orientationxr   l_margint_marginset_marginsc_marginset_auto_page_breakset_display_mode
_page_modeZviewer_preferencescompresspdf_versionr   nowr   utccreation_date_security_handler_fallback_font_ids_fallback_font_exact_match_current_draw_contextr(    _drawing_graphics_state_registry_record_text_quad_pointsre   _resource_catalogr   list_text_quad_pointsbuffer)r   orientationunitr   Zfont_cache_dirmargin	__class__r   r   r      s    





zFPDF.__init__Fc                 C   s   t | |||||d| _dS )a  
        Activate encryption of the document content.

        Args:
            owner_password (str): mandatory. The owner password allows to perform any change on the document,
                including removing all encryption and access permissions.
            user_password (str): optional. If a user password is set, the content of the document will be encrypted
                and a password prompt displayed when a user opens the document.
                The document will only be displayed after either the user or owner password is entered.
            encryption_method (fpdf.enums.EncryptionMethod, str): algorithm to be used to encrypt the document.
                Defaults to RC4.
            permissions (fpdf.enums.AccessPermission): specify access permissions granted
                when the document is opened with user access. Defaults to ALL.
            encrypt_metadata (bool): whether to also encrypt document metadata (author, creation date, etc.).
                Defaults to False.
        )owner_passworduser_passwordZ
permissionencryption_methodencrypt_metadataN)r.   r   )r   r  r  r  permissionsr  r   r   r   set_encryption  s    zFPDF.set_encryptionc              	   O   s4   | j | f||}|   || W 5 Q R X dS )a,  
        Parse HTML and convert it to PDF.
        cf. https://py-pdf.github.io/fpdf2/HTML.html

        Args:
            text (str): HTML content to render
            image_map (function): an optional one-argument function that map `<img>` "src" to new image URLs
            li_tag_indent (int): [**DEPRECATED since v2.7.9**]
                numeric indentation of `<li>` elements - Set `tag_styles` instead
            dd_tag_indent (int): [**DEPRECATED since v2.7.9**]
                numeric indentation of `<dd>` elements - Set `tag_styles` instead
            table_line_separators (bool): enable horizontal line separators in `<table>`. Defaults to `False`.
            ul_bullet_char (str): bullet character preceding `<li>` items in `<ul>` lists.
                Can also be configured using the HTML `type` attribute of `<ul>` tags.
            li_prefix_color (tuple, str, fpdf.drawing.DeviceCMYK, fpdf.drawing.DeviceGray, fpdf.drawing.DeviceRGB): color for bullets
                or numbers preceding `<li>` tags. This applies to both `<ul>` & `<ol>` lists.
            heading_sizes (dict): [**DEPRECATED since v2.7.9**]
                font size per heading level names ("h1", "h2"...) - Set `tag_styles` instead
            pre_code_font (str): [**DEPRECATED since v2.7.9**]
                font to use for `<pre>` & `<code>` blocks - Set `tag_styles` instead
            warn_on_tags_not_matching (bool): control warnings production for unmatched HTML tags. Defaults to `True`.
            tag_indents (dict): [**DEPRECATED since v2.8.0**]
                mapping of HTML tag names to numeric values representing their horizontal left indentation. - Set `tag_styles` instead
            tag_styles (dict[str, fpdf.fonts.TextStyle]): mapping of HTML tag names to `fpdf.TextStyle` or `fpdf.FontFace` instances
        N)HTML2FPDF_CLASSlocal_contextfeed)r   textr   r   Zhtml2pdfr   r   r   
write_html  s    
zFPDF.write_htmlc                 C   s   t | j|| _d S N)maxr   )r   versionr   r   r   _set_min_pdf_version  s    zFPDF._set_min_pdf_version)returnc                 C   s,   | j }| jr|d7 }| jr"|d7 }t|S )zIThe current text emphasis: bold, italics, underline and/or strikethrough.SU)r   r   r   rA   coerce)r   r   r   r   r   emphasis  s    zFPDF.emphasisc                 C   s   | j o| j jdkS )NZTTF)r   typer   r   r   r   is_ttf_font  s    zFPDF.is_ttf_fontc                 C   s   | j S r  )r   r   r   r   r   	page_mode  s    zFPDF.page_modec                 C   s>   t || _| jt jkr$| d n| jt jkr:| d d S )N1.61.5)r;   r  r   ZUSE_ATTACHMENTSr  ZUSE_OC)r   r"  r   r   r   r"    s
    c                 C   s
   | j  S r  )r   valuesr   r   r   r   output_intents  s    zFPDF.output_intents)subtypeoutput_condition_identifieroutput_conditionregistry_namedest_output_profileinfoc                 C   sF   |j | jkrtd|j  d t||||||| j|j < | d dS )aR  
        Adds desired Output Intent to the Output Intents array:

        Args:
            subtype (OutputIntentSubType, required): PDFA, PDFX or ISOPDF
            output_condition_identifier (str, required): see the Name in
                https://www.color.org/registry.xalter
            output_condition (str, optional): see the Definition in
                https://www.color.org/registry.xalter
            registry_name (str, optional): "https://www.color.org"
            dest_output_profile (PDFICCProfile, required/optional):
                PDFICCProfile | None # (required  if
                output_condition_identifier does not specify a standard
                production condition; optional otherwise)
            info (str, required/optional see dest_output_profile): human
                readable description of profile
        zadd_output_intent: subtype 'z' already exists.1.4N)valuer   
ValueErrorrh   r  )r   r'  r(  r)  r*  r+  r,  r   r   r   add_output_intent  s    zFPDF.add_output_intentc                 C   s   | j | j | j S )zT
        Effective page width: the page width minus its horizontal margins.
        )wr   r_marginr   r   r   r   epw  s    zFPDF.epwc                 C   s   | j | j | j S )zT
        Effective page height: the page height minus its vertical margins.
        )hr   b_marginr   r   r   r   eph  s    zFPDF.ephc                 C   s
   t | jS )z:
        Returns the total pages of the document.
        )lenr   r   r   r   r   pages_count  s    zFPDF.pages_countc                 C   s   |  || | | j| dS )z
        Sets the document right, left, top & bottom margins to the same value.

        Args:
            margin (float): margin in the unit specified to FPDF constructor
        N)r   r   auto_page_breakr   r  r   r   r   
set_margin"  s    zFPDF.set_marginc                 C   sB   |  | | j|k s | j| jkr&|| _|| _|dkr8|}|| _dS )a  
        Sets the document left, top & optionally right margins to the same value.
        By default, they equal 1 cm.
        Also sets the current FPDF.y on the page to this minimum vertical position.

        Args:
            left (float): left margin in the unit specified to FPDF constructor
            top (float): top margin in the unit specified to FPDF constructor
            right (float): optional right margin in the unit specified to FPDF constructor
        r<  N)set_left_marginr   r   r2  )r   lefttoprightr   r   r   r   ,  s    
zFPDF.set_marginsc                 C   s&   | j |k s| j | jkr|| _ || _dS )z
        Sets the document left margin.
        Also sets the current FPDF.x on the page to this minimum horizontal position.

        Args:
            margin (float): margin in the unit specified to FPDF constructor
        N)r   r   r:  r   r   r   r=  ?  s    zFPDF.set_left_marginc                 C   s
   || _ dS )z
        Sets the document top margin.

        Args:
            margin (float): margin in the unit specified to FPDF constructor
        N)r   r:  r   r   r   set_top_marginK  s    zFPDF.set_top_marginc                 C   s
   || _ dS )z
        Sets the document right margin.

        Args:
            margin (float): margin in the unit specified to FPDF constructor
        N)r2  r:  r   r   r   set_right_marginT  s    zFPDF.set_right_marginr   c                 C   s   || _ || _| j| j | _dS )ab  
        Set auto page break mode and triggering bottom margin.
        By default, the mode is on and the bottom margin is 2 cm.

        Args:
            auto (bool): enable or disable this mode
            margin (float): optional bottom margin (distance from the bottom of the page)
                in the unit specified to FPDF constructor
        N)r9  r5  r4  page_break_trigger)r   autor  r   r   r   r   ]  s    
zFPDF.set_auto_page_breakc                 C   s$   | j tjkr| j| jfS | j| jfS )zGReturn a pair (width, height) in the unit specified to FPDF constructor)r   r<   PORTRAITr   r   r   r   r   r   default_page_dimensionsk  s    

zFPDF.default_page_dimensionsc                 C   sl   t || _| jt jkr&|| _|| _n|| _|| _| j| j | _| j| j | _t	| drh| 
| j| j d S )Nr9  )r<   r  r   rE  w_pth_ptr   r1  r4  hasattrr   r9  r5  )r   r  page_width_ptpage_height_ptr   r   r   r   t  s    
zFPDF._set_orientationr   c                 C   sB   |t kst|ts|| _n|dkr0td| t||| _dS )a  
        Defines the way the document is to be displayed by the viewer.

        It allows to set the zoom level: pages can be displayed entirely on screen,
        occupy the full width of the window, use the real size,
        be scaled by a specific zooming factor or use the viewer default (configured in its Preferences menu).

        The page layout can also be specified: single page at a time, continuous display, two columns or viewer default.

        Args:
            zoom: either "fullpage", "fullwidth", "real", "default",
                or a number indicating the zooming factor to use, interpreted as a percentage.
                The zoom level set by default is "default".
            layout (fpdf.enums.PageLayout, str): allowed layout aliases are "single", "continuous", "two" or "default",
                meaning to use the viewer default mode.
                The layout set by default is "continuous".
        r   zIncorrect zoom display mode: N)ra   r   r   Z	zoom_moderH   LAYOUT_ALIASESr   page_layout)r   zoomZlayoutr   r   r   r     s
    zFPDF.set_display_mode)use_shaping_enginefeatures	directionscriptlanguagec           	   
   C   s   |sd| _ dS zddl}W n, tk
rF } ztd|W 5 d}~X Y nX |r^t|ts^td|sfi }d}|rt|tr||nt|}|tjtj	fkrtdd||||ddd| _ dS )a<  
        Enable or disable text shaping engine when rendering text.
        If features, direction, script or language are not specified the shaping engine will try
        to guess the values based on the input text.

        Args:
            use_shaping_engine: enable or disable the use of the shaping engine to process the text
            features: a dictionary containing 4 digit OpenType features and whether each feature
                should be enabled or disabled
                example: features={"kern": False, "liga": False}
            direction: the direction the text should be rendered, either "ltr" (left to right)
                or "rtl" (right to left).
            script: a valid OpenType script tag like "arab" or "latn"
            language: a valid OpenType language tag like "eng" or "fra"
        Nr   ziThe uharfbuzz package could not be imported, but is required for text shaping. Try: pip install uharfbuzzz=Features must be a dictionary. See text shaping documentationzPFPDF2 only accept ltr (left to right) or rtl (right to left) directions for now.T)rO  rP  rQ  rR  rS  fragment_directionparagraph_direction)
text_shaping	uharfbuzzImportErrorrH   r   r   r@   r  ZLTRZRTL)	r   rO  rP  rQ  rR  rS  rW  excZtext_directionr   r   r   set_text_shaping  sF    zFPDF.set_text_shapingc                 C   s   | j S r  )_page_layoutr   r   r   r   rM    s    zFPDF.page_layoutc                 C   s4   |rt |nd | _| jt jt jfkr0| d d S )Nr$  )r:   r  r[  ZTWO_PAGE_LEFTZTWO_PAGE_RIGHTr  )r   rM  r   r   r   rM    s    c                 C   s
   || _ dS )a  
        Activates or deactivates page compression.

        When activated, the internal representation of each page is compressed
        using the zlib/deflate method (FlateDecode), which leads to a compression ratio
        of about 2 for the resulting document.

        Page compression is enabled by default.

        Args:
            compress (bool): indicates if compression should be enabled
        N)r   )r   r   r   r   r   set_compression  s    zFPDF.set_compressionc                 C   s
   || _ dS )aA  
        Defines the title of the document.

        Most PDF readers will display it when viewing the document.
        There is also a related `fpdf.prefs.ViewerPreferences` entry:

            pdf.viewer_preferences = ViewerPreferences(display_doc_title=True)

        Args:
            title (str): the title
        Nr   )r   r   r   r   r   	set_title  s    zFPDF.set_titlec                 C   s   || _ |r| d dS )a  
        A language identifier specifying the natural language for all text in the document
        except where overridden by language specifications for structure elements or marked content.
        A language identifier can either be the empty text string, to indicate that the language is unknown,
        or a Language-Tag as defined in RFC 3066, "Tags for the Identification of Languages".

        Args:
            lang (str): the document main language
        r-  N)langr  )r   r_  r   r   r   set_lang  s    
zFPDF.set_langc                 C   s
   || _ dS )zz
        Defines the subject of the document.

        Args:
            subject (str): the document main subject
        N)subject)r   ra  r   r   r   set_subject  s    zFPDF.set_subjectc                 C   s
   || _ dS )zt
        Defines the author of the document.

        Args:
            author(str): the name of the author
        N)author)r   rc  r   r   r   
set_author'  s    zFPDF.set_authorc                 C   s
   || _ dS )z
        Associate keywords with the document

        Args:
            keywords (str): a space-separated list of words
        N)keywords)r   re  r   r   r   set_keywords0  s    zFPDF.set_keywordsc                 C   s
   || _ dS )z
        Defines the creator of the document.
        This is typically the name of the application that generates the PDF.

        Args:
            creator (str): name of the PDF creator
        N)creator)r   rg  r   r   r   set_creator9  s    zFPDF.set_creatorc                 C   s
   || _ dS )zProducer of documentN)producer)r   ri  r   r   r   set_producerC  s    zFPDF.set_producerc                 C   sB   | j rtdt|ts*tdt| |js8| }|| _dS )z:Sets Creation of Date time, or current time if None given.zB.set_creation_date() must always be called before .sign*() methodsz#date should be a datetime but is a N)	r   rH   r   r   	TypeErrorr  tzinfo
astimezoner   )r   dater   r   r   set_creation_dateG  s    
zFPDF.set_creation_datec                 C   s0   d|d d krt d|| _|r,| d d S )Nz	<?xpacket2   z@fpdf2 already performs XMP metadata wrapping in a <?xpacket> tagr-  )r/  r   r  )r   r   r   r   r   set_xmp_metadataS  s    zFPDF.set_xmp_metadatac                 C   s4   t jdtt d |dkr*td| d|| _dS )a  
        Defines a document option.

        Args:
            opt (str): name of the option to set
            value (str) option value

        .. deprecated:: 2.4.0
            Simply set the `FPDF.core_fonts_encoding` property as a replacement.
        zset_doc_option() is deprecated since v2.4.0 and will be removed in a future release. Simply set the `.core_fonts_encoding` property as a replacement.r   r   zUnknown document option ""N)r   r   r   r$   rH   r   )r   optr.  r   r   r   set_doc_option\  s    	zFPDF.set_doc_optionc                 C   s@   |t kr"td| ddt  || j_|dkr<| d dS )a  
        Args:
            image_filter (str): name of a the image filter to use
                when embedding images in the document, or "AUTO",
                meaning to use the best image filter given the images provided.
                Allowed values: `FlateDecode` (lossless zlib/deflate compression),
                `DCTDecode` (lossy compression with JPEG)
                and `JPXDecode` (lossy compression with JPEG2000).
        'z4' is not a supported image filter - Allowed values: r   Z	JPXDecoder$  N)rW   r/  joinr   image_filterr  )r   rw  r   r   r   set_image_filtert  s    
zFPDF.set_image_filter{nb}c                 C   s
   || _ dS )a3  
        Defines an alias for the total number of pages.
        It will be substituted as the document is closed.

        This is useful to insert the number of pages of the document
        at a time when this number is not known by the program.

        This substitution can be disabled for performances reasons, by calling `alias_nb_pages(None)`.

        Args:
            alias (str): the alias. Defaults to "{nb}".

        Notes
        -----

        When using this feature with the `FPDF.cell` / `FPDF.multi_cell` methods,
        or the `.underline` / `.strikethrough` attributes of `FPDF` class,
        the width of the text rendered will take into account the alias length,
        not the length of the "actual number of pages" string,
        which can causes slight positioning differences.
        N)str_alias_nb_pages)r   aliasr   r   r   r     s    zFPDF.alias_nb_pages)label_stylelabel_prefixlabel_startc                 C   s   d }| j | jkr"| j| j   }n| j dkr@| j| j d   }d }|sP|sP|r|r|d krd| }|d krt| }|d kr| jr| jjs| }|rtj	|ddnd }t
|||}| j| j  || d S )Nr   TZcase_sensitive)r   r   get_page_labelZ	get_styleZ
get_prefixr   r   Z	get_startr9   r  rd   set_page_label)r   r|  r}  r~  current_page_labelnew_page_labelr   r   r   r    s0    
zFPDF.set_page_labelr   )r  r   sameduration
transitionr|  r}  r~  c	                 C   s  | j rtdd| _| j}	| j}
| j}| j}| j}| j}| j	}| j
}| j}| j}| joh| joh| j| jjk}| jdkr| jr~|r|   | jdkrdn| j| j  }d}|s|s|r|rtj|ddnd}t|||}| j||||p| j|p| j|   d | j| j || | jrrt| jtrZ| j | j  | j!dd| j"| j#dd	 | j |j$  n| %| jdd| j"| j# | &d
 || _| &|| j' dd |	r| (|	|
| || _|| j)kr| &|* +  || _|| j,kr| &|* -  || _	| jr| jr| .  | j|kr>|| _| &|| j' dd |	rR| (|	|
| | j|krv|| _| &|* +  | j|kr|| _| &|* -  || _	|dkr| /| |dkr| 0| |t1ddddkr| 2|d |d |d  dS )u  
        Adds a new page to the document.
        If a page is already present, the `FPDF.footer()` method is called first.
        Then the page  is added, the current position is set to the top-left corner,
        with respect to the left and top margins, and the `FPDF.header()` method is called.

        Args:
            orientation (str): "portrait" (can be abbreviated "P")
                or "landscape" (can be abbreviated "L"). Default to "portrait".
            format (str): "a3", "a4", "a5", "letter", "legal" or a tuple
                (width, height). Default to "a4".
            same (bool): indicates to use the same page format as the previous page.
                Default to False.
            duration (float): optional page’s display duration, i.e. the maximum length of time,
                in seconds, that the page is displayed in presentation mode,
                before the viewer application automatically advances to the next page.
                Can be configured globally through the `.page_duration` FPDF property.
                As of june 2021, onored by Adobe Acrobat reader, but ignored by Sumatra PDF reader.
            transition (Transition child class): optional visual transition to use when moving
                from another page to the given page during a presentation.
                Can be configured globally through the `.page_transition` FPDF property.
                As of june 2021, onored by Adobe Acrobat reader, but ignored by Sumatra PDF reader.
            label_style (str or PageLabelStyle): Defines the numbering style for the numeric portion of each
                page label. Possible values are:
                - "D": Decimal Arabic numerals.
                - "R": Uppercase Roman numerals.
                - "r": Lowercase Roman numerals.
                - "A": Uppercase letters (A to Z for the first 26 pages, followed by AA to ZZ, etc.).
                - "a": Lowercase letters (a to z for the first 26 pages, followed by aa to zz, etc.).
            label_prefix (str): Prefix string applied to the page label, preceding the numeric portion.
            label_start (int): Starting number for the first page of a page label range.
        zCA page cannot be added on a closed document, after calling output()Fr   NTr  )new_pageFstylez2 J.2f wr   r   r   r   r   )3r  rH   r   r   r  r   r   r   r   r   r   r   r   r   r   r   r   r   _render_footerr   r  r9   r  rd   
_beginpager   r   _has_next_pager  r   r   tupleset_fill_colorrectr1  r4  	colors255image_outr   set_fontr   	serializeupperr   r   headerset_stretchingset_char_spacingr   _write_dash_pattern)r   r  r   r  r  r  r|  r}  r~  familyr  sizeZlwdcZfcZtc
stretchingr   r   Zin_toc_extra_pager  r  r   r   r   add_page  s    +	




  zFPDF.add_pagec                 C   sD   d| _ | jr|   |   |   | jr:|   |   d| _ d S )NTF)r   r   _push_local_stack_start_local_contextfooter_end_local_context_pop_local_stackr   r   r   r   r  R  s    zFPDF._render_footerc           
      C   s  |  j d7  _ | jr<| jr<|  jd7  _t| jd | _ d}|rptt ||| j d}|| j| j < |r|| d n| j| j  }| j	| _
| j| _d| _d| _d| _|r|s|rtd| d	| d
| n4|rt|| jn
| j| jf\}}	| |p| j||	 || j| j d S )Nr   T)contentsr  r  indexr$  r   r   r   zInconsistent parameters: same=z but orientation=z format=)r   r   r   r   r7  r   rc   	bytearrayr  r   r   r   r   r   r   r   r/  r   r   r   r   r   r   Zset_dimensionsrG  rH  )
r   r  r   r  r  r  r  r   rJ  rK  r   r   r   r  _  sD      zFPDF._beginpagec                 C   s   dS )a  
        Header to be implemented in your own inherited class

        This is automatically called by `FPDF.add_page()`
        and should not be called directly by the user application.
        The default implementation performs nothing: you have to override this method
        in a subclass to implement your own rendering logic.

        Note that header rendering can have an impact on the initial
        (x,y) position when starting to render the page content.
        Nr   r   r   r   r   r    s    zFPDF.headerc                 C   s   dS )al  
        Footer to be implemented in your own inherited class.

        This is automatically called by `FPDF.add_page()` and `FPDF.output()`
        and should not be called directly by the user application.
        The default implementation performs nothing: you have to override this method
        in a subclass to implement your own rendering logic.
        Nr   r   r   r   r   r    s    zFPDF.footerc                 C   s   | j S )zGet the current page numberr   r   r   r   r   page_no  s    zFPDF.page_noc                 C   s   | j | j  S r  )r   r   Z	get_labelr   r   r   r   r    s    zFPDF.get_page_labelc                 C   s>   t |||}|| jkr:|| _| jdkr:| | j   dS )a,  
        Defines the color used for all stroking operations (lines, rectangles and cell borders).
        Accepts either a single greyscale value, 3 values as RGB components, a single `#abc` or `#abcdef` hexadecimal color string,
        or an instance of `fpdf.drawing.DeviceCMYK`, `fpdf.drawing.DeviceRGB` or `fpdf.drawing.DeviceGray`.
        The method can be called before the first page is created and the value is retained from page to page.

        Args:
            r (int, tuple, fpdf.drawing.DeviceGray, fpdf.drawing.DeviceRGB): if `g` and `b` are given, this indicates the red component.
                Else, this indicates the grey level. The value must be between 0 and 255.
            g (int): green component (between 0 and 255)
            b (int): blue component (between 0 and 255)
        r   N)r-   r   r   r  r  r  )r   rgbr   r   r   r   set_draw_color  s
    

zFPDF.set_draw_colorc                 C   s>   t |||}|| jkr:|| _| jdkr:| | j   dS )a/  
        Defines the color used for all filling operations (filled rectangles and cell backgrounds).
        Accepts either a single greyscale value, 3 values as RGB components, a single `#abc` or `#abcdef` hexadecimal color string,
        or an instance of `fpdf.drawing.DeviceCMYK`, `fpdf.drawing.DeviceRGB` or `fpdf.drawing.DeviceGray`.
        The method can be called before the first page is created and the value is retained from page to page.

        Args:
            r (int, tuple, fpdf.drawing.DeviceGray, fpdf.drawing.DeviceRGB): if `g` and `b` are given, this indicates the red component.
                Else, this indicates the grey level. The value must be between 0 and 255.
            g (int): green component (between 0 and 255)
            b (int): blue component (between 0 and 255)
        r   N)r-   r   r   r  r  r   )r   r  r  r  r   r   r   r   r    s
    

zFPDF.set_fill_colorc                 C   s   t |||| _dS )a  
        Defines the color used for text.
        Accepts either a single greyscale value, 3 values as RGB components, a single `#abc` or `#abcdef` hexadecimal color string,
        or an instance of `fpdf.drawing.DeviceCMYK`, `fpdf.drawing.DeviceRGB` or `fpdf.drawing.DeviceGray`.
        The method can be called before the first page is created and the value is retained from page to page.

        Args:
            r (int, tuple, fpdf.drawing.DeviceGray, fpdf.drawing.DeviceRGB): if `g` and `b` are given, this indicates the red component.
                Else, this indicates the grey level. The value must be between 0 and 255.
            g (int): green component (between 0 and 255)
            b (int): blue component (between 0 and 255)
        N)r-   r   )r   r  r  r  r   r   r   set_text_color  s    zFPDF.set_text_colorc                 C   s8   |r|n|  |}d}| ||D ]}|| 7 }q"|S )a&  
        Returns the length of a string in user unit. A font must be selected.
        The value is calculated with stretching and spacing.

        Note that the width of a cell has some extra padding added to this width,
        on the left & right sides, equal to the .c_margin property.

        Args:
            s (str): the string whose length is to be computed.
            normalized (bool): whether normalization needs to be performed on the input string.
            markdown (bool): indicates if basic markdown support is enabled
        r   )normalize_text_preload_bidirectional_text	get_width)r   s
normalizedmarkdownr1  fragr   r   r   get_string_width  s
    zFPDF.get_string_widthc                 C   s6   || j kr2|| _ | jdkr2| || j dd dS )aF  
        Defines the line width of all stroking operations (lines, rectangles and cell borders).
        By default, the value equals 0.2 mm.
        The method can be called before the first page is created and the value is retained from page to page.

        Args:
            width (float): the width in user unit
        r   r  r  N)r   r   r  r   )r   widthr   r   r   set_line_width  s    	

zFPDF.set_line_widthc              	   C   sN   t |ttjttttdfr8t |tr0|j| _	qJ|| _	nt
dt| dS )aD  
        Sets a background color or image to be drawn every time `FPDF.add_page()` is called, or removes a previously set background.
        The method can be called before the first page is created and the value is retained from page to page.

        Args:
            background: either a string representing a file path or URL to an image,
                an io.BytesIO containing an image as bytes, an instance of `PIL.Image.Image`, drawing.DeviceRGB
                or a RGB tuple representing a color to fill the background with or `None` to remove the background
        Nzkbackground must be of type str, io.BytesIO, PIL.Image.Image, drawing.DeviceRGB, tuple or None
        got: )r   r   ioBytesIOr   r&   r  r  r  r   rk  )r   Z
backgroundr   r   r   set_page_background  s     

zFPDF.set_page_backgroundc                 c   s   | j dk	rtdt }|| _ z
|V  W 5 d| _ X |  }| jt| j| j| j| j	|f}|rn|j
||f }n
|j| }| j|D ]}| jtj|d| j q| j|D ]"}| jtjt|d| j q| | | d dS )a  
        Create a context for drawing paths on the current page.

        If this context manager is called again inside of an active context, it will
        raise an exception, as base drawing contexts cannot be nested.

        Args:
            debug_stream (TextIO): print a pretty tree of all items to be rendered
                to the provided stream. To store the output in a string, use
                `io.StringIO`.
        Nz9cannot create a drawing context while one is already openr   r-  )r   rH   r'   _current_graphic_styler   r+   r   r   r   r4  Zrender_debugrender	_GS_REGEXfinditerr  addr>   EXT_G_STATEgroupr   
_IMG_REGEXX_OBJECTr   r  r  )r   debug_streamcontextZstarting_styleZrender_argsrenderedmatchr   r   r   drawing_context  sB    


    
zFPDF.drawing_contextc              
   c   sh   | j tj|| j | }| j tj|| j}| d| d z
dV  W 5 | | j	 
  X dS )zS
        Create a context for using a shading pattern on the current page.
        z/Pattern cs /z scnN)r  r  r>   ZSHADDINGr   Zget_patternZPATTERNr  r   r  r   )r   ZshadingpatternZpattern_namer   r   r   use_patternM  s      
zFPDF.use_patternc                 C   s   t  }| j|_| j|_| j| jkr*| j|_| j| j	kr>| j|_| j
}|d |d f}|d dksl|d dkrpd }||_|d |_|S )Nr   r   r   r   r   )r)   r   Zallow_transparencyr   stroke_widthr   r   stroke_colorr   r   r   stroke_dash_patternstroke_dash_phase)r   gsZ	dash_infor   r   r   r   r  ^  s    
zFPDF._current_graphic_stylec              	   c   s@   | j |d*}t||d}||j_|V  || W 5 Q R X dS )aY  
        Create a path for appending lines and curves to.

        Args:
            x (float): Abscissa of the path starting point
            y (float): Ordinate of the path starting point
            paint_rule (PathPaintRule): Optional choice of how the path should
                be painted. The default (AUTO) automatically selects stroke/fill based
                on the path style settings.
            debug_stream (TextIO): print a pretty tree of all items to be rendered
                to the provided stream. To store the output in a string, use
                `io.StringIO`.

        r  )r   r   N)r  r*   r  
paint_ruleadd_item)r   r   r   r  r  ctxtpathr   r   r   new_pathv  s
    zFPDF.new_pathc              	   C   s&   | j |d}|| W 5 Q R X dS )aI  
        Add a pre-constructed path to the document.

        Args:
            path (drawing.PaintedPath): the path to be drawn.
            debug_stream (TextIO): print a pretty tree of all items to be rendered
                to the provided stream. To store the output in a string, use
                `io.StringIO`.
        r  N)r  r  )r   r  r  r  r   r   r   	draw_path  s    
zFPDF.draw_pathc                 C   s   t |ttfr|dkstdt |ttfr4|dks<tdt |ttfrR|dksZtdt|||d}|| jkr|| _| ||| dS )a  
        Set the current dash pattern for lines and curves.

        Args:
            dash (float): The length of the dashes in current units.

            gap (float): The length of the gaps between dashes in current units.
                If omitted, the dash length will be used.

            phase (float): Where in the sequence to start drawing.

        Omitting 'dash' (= 0) resets the pattern to a solid line.
        r   z.Dash length must be zero or a positive number.z-gap length must be zero or a positive number.z(Phase must be zero or a positive number.r   N)r   r   floatr/  r   r   r  )r   r   r   r   r  r   r   r   set_dash_pattern  s    
zFPDF.set_dash_patternc                 C   sp   |r^|r:d|| j  dd|| j  dd|| j  dd}qbd|| j  dd|| j  dd}nd}| | d S )N[z.3f z] z dz[] 0 d)r   r  )r   r   r   r   Zdstrr   r   r   r    s    2$zFPDF._write_dash_patternc              
   C   sR   |  || j dd| j| | j dd|| j dd| j| | j dd dS )a  
        Draw a line between two points.

        Args:
            x1 (float): Abscissa of first point
            y1 (float): Ordinate of first point
            x2 (float): Abscissa of second point
            y2 (float): Ordinate of second point
        r  r   m  l SNr  r   r4  )r   x1y1x2y2r   r   r   line  s    Fz	FPDF.linec                 C   s   |rt jdtt d |r*|dkr*tj}n,t|}|rV|tjkrVtd| d| d}|D ]@}| 	|d | j
 dd	| j|d
  | j
 dd	|  d}q^|r| 	d | 	d	|j  dS )a  
        Draws lines between two or more points.

        Args:
            point_list (list of tuples): List of Abscissa and Ordinate of
                                        segments that should be drawn
            fill (bool): [**DEPRECATED since v2.5.4**] Use `style="F"` or `style="DF"` instead
            polygon (bool): If true, close path before stroking, to fill the inside of the polyline
            style (fpdf.enums.RenderStyle, str): Optional style of rendering. Possible values are:

            * `D` or None: draw border. This is the default value.
            * `F`: fill
            * `DF` or `FD`: draw and fill
        zP"fill" parameter is deprecated since v2.5.4, use style="F" or style="DF" insteadr   Nz"Conflicting values provided: fill=z	 & style=mr   r  r  r   lz h)r   r   r   r$   r?   ZDFr  Dr/  r  r   r4  operator)r   
point_listfillpolygonr  r  pointr   r   r   polyline  s,    
0
zFPDF.polylinec                 C   s   | j ||d|d dS )a  
        Outputs a polygon defined by three or more points.

        Args:
            point_list (list of tuples): List of coordinates defining the polygon to draw
            fill (bool): [**DEPRECATED since v2.5.4**] Use `style="F"` or `style="DF"` instead
            style (fpdf.enums.RenderStyle, str): Optional style of rendering. Possible values are:

            * `D` or None: draw border. This is the default value.
            * `F`: fill
            * `DF` or `FD`: draw and fill
        T)r  r  r  N)r  )r   r  r  r  r   r   r   r    s    zFPDF.polygonr   c                 C   s:   t jdtt d | || | |||| |   dS )a  
        Draw a dashed line between two points.

        Args:
            x1 (float): Abscissa of first point
            y1 (float): Ordinate of first point
            x2 (float): Abscissa of second point
            y2 (float): Ordinate of second point
            dash_length (float): Length of the dash
            space_length (float): Length of the space between 2 dashes

        .. deprecated:: 2.4.6
            Use `FPDF.set_dash_pattern()` and the normal drawing operations instead.
        zdashed_line() is deprecated since v2.4.6, and will be removed in a future release. Use set_dash_pattern() and the normal drawing operations instead.r   N)r   r   r   r$   r  r  )r   r  r  r  r  Zdash_lengthZspace_lengthr   r   r   dashed_line	  s    	zFPDF.dashed_linec                 C   s~   t |}|dk	r*| ||||||| nP| || j dd| j| | j dd|| j dd| | j dd|j 	 dS )a{  
        Outputs a rectangle.
        It can be drawn (border only), filled (with no border) or both.

        Args:
            x (float): Abscissa of upper-left bounding box.
            y (float): Ordinate of upper-left bounding box.
            w (float): Width.
            h (float): Height.
            style (fpdf.enums.RenderStyle, str): Optional style of rendering. Possible values are:

            * `D` or empty string: draw border. This is the default value.
            * `F`: fill
            * `DF` or `FD`: draw and fill

            round_corners (tuple of str, tuple of fpdf.enums.Corner, bool): Optional draw a rectangle with round corners.
            Possible values are:

            *`TOP_LEFT`: a rectangle with round top left corner
            *`TOP_RIGHT`: a rectangle with round top right corner
            *`BOTTOM_LEFT`: a rectangle with round bottom left corner
            *`BOTTOM_RIGHT`: a rectangle with round bottom right corner
            *`True`: a rectangle with all round corners
            *`False`: a rectangle with no round corners

            corner_radius: Optional radius of the corners
        Fr  r   re N)r?   r  _draw_rounded_rectr  r   r4  r  )r   r   r   r1  r4  r  round_cornersZcorner_radiusr   r   r   r  &  s    
Hz	FPDF.rectc              
   C   s  |}||k r|}|dkr |d }||d kr4|| }||f }	}
|| |f }}|| || f }}||| f }}||| ||| g}|||| || g}|dkrt jjt jjt jjt jjf}tdd |D }t j|kr| j|d |d d| dd|d	 || |f}	||| f}
t j|krn| j|d
 d|  |d
 d| dd|d	 || | |f}|| || f}t j|kr| j|d d|  |d d|  d| dd|d	 || || | f}|| | || f}t j|kr*| j|d |d d|  d| dd|d	 || || f}||| | f}|jrR| j	|	|||||||
|	g	dd	 |j
r| |	d |	d
 |d |d
  | |d |d
 |d |d
  | |d |d
 |d |d
  | |d |d
 |
d |
d
  d S )Nr      r   Tc                 s   s   | ]}t |V  qd S r  )r5   r  ).0rcr   r   r   	<genexpr>f  s     z*FPDF._draw_rounded_rect.<locals>.<genexpr>   i  r  r      Z   r  )r5   Z	TOP_RIGHTr.  ZTOP_LEFTZBOTTOM_RIGHTZBOTTOM_LEFTr  arcis_fillr  is_drawr  )r   r   r   r1  r4  r  r  r  minZpoint_1Zpoint_8Zpoint_2Zpoint_3Zpoint_4Zpoint_5Zpoint_6Zpoint_7Zcoor_xZcoor_yr   r   r   r  M  sn    "*2*   zFPDF._draw_rounded_rectc                 C   s"   t |}| |||||j dS )a   
        Outputs an ellipse.
        It can be drawn (border only), filled (with no border) or both.

        Args:
            x (float): Abscissa of upper-left bounding box.
            y (float): Ordinate of upper-left bounding box.
            w (float): Width
            h (float): Height
            style (fpdf.enums.RenderStyle, str): Optional style of rendering. Possible values are:

            * `D` or empty string: draw border. This is the default value.
            * `F`: fill
            * `DF` or `FD`: draw and fill
        N)r?   r  _draw_ellipser  )r   r   r   r1  r4  r  r   r   r   ellipse  s    
zFPDF.ellipsec                 C   s  ||d  }||d  }|d }|d }	dt dd  | }
dt dd  |	 }| || | j dd| j| | j dd|| | j dd| j| | | j dd||
 | j dd| j| |	 | j dd|| j dd| j| |	 | j dd | ||
 | j dd| j| |	 | j dd|| | j dd| j| | | j dd|| | j dd| j| | j dd | || | j dd| j| | | j dd||
 | j dd| j| |	 | j dd|| j dd| j| |	 | j dd | ||
 | j dd| j| |	 | j dd|| | j dd| j| | | j dd|| | j dd| j| | j dd|  d S )	Nr   gUUUUUU?r   r  r  r   cz c )mathsqrtr  r   r4  )r   r   r   r1  r4  r  cxcyrxZryZlxZlyr   r   r   r    s$    ||zFPDF._draw_ellipsec                 C   s&   |  || || d| d| | dS )ad  
        Outputs a circle.
        It can be drawn (border only), filled (with no border) or both.

        WARNING: This method changed parameters in [release 2.8.0](https://github.com/py-pdf/fpdf2/releases/tag/2.8.0)

        Args:
            x (float): Abscissa of upper-left bounding box.
            y (float): Ordinate of upper-left bounding box.
            radius (float): Radius of the circle.
            style (str): Style of rendering. Possible values are:

            * `D` or None: draw border. This is the default value.
            * `F`: fill
            * `DF` or `FD`: draw and fill
        r   N)r  )r   r   r   radiusr  r   r   r   circle  s    zFPDF.circlec              
   C   s   |d }|| }|| }	g }
t d|d D ]b}||ttd| | t|   |	|ttd| | t|   f}|
| q*| j|
|d dS )a  
        Outputs a regular polygon with n sides
        It can be rotated
        Style can also be applied (fill, border...)

        Args:
            x (float): Abscissa of upper-left bounding box.
            y (float): Ordinate of upper-left bounding box.
            numSides (int): Number of sides for polygon.
            polyWidth (float): Width of the polygon.
            rotateDegrees (float): Optional degree amount to rotate polygon.
            style (fpdf.enums.RenderStyle, str): Optional style of rendering. Possible values are:

            * `D` or None: draw border. This is the default value.
            * `F`: fill
            * `DF` or `FD`: draw and fill
        r   r   h  r  N)ranger  cosradianssinappendr  )r   r   r   ZnumSidesZ	polyWidthZrotateDegreesr  r  ZcenterXZcenterYpointsir  r   r   r   regular_polygon  s    zFPDF.regular_polygonc                 C   s   t |}g }	td|d d D ]h}
||
d dkr6|n|t |  }||
d dkrX|n|t |  }|	||f |t d| 7 }q | j|	d|d dS )a  
        Outputs a regular star with n corners.
        It can be rotated.
        It can be drawn (border only), filled (with no border) or both.

        Args:
            x (float): Abscissa of star's centre.
            y (float): Ordinate of star's centre.
            r_in (float): radius of internal circle.
            r_out (float): radius of external circle.
            corners (int): number of star's corners.
            rotate_degrees (float): Optional degree amount to rotate star clockwise.

            style (fpdf.enums.RenderStyle, str): Optional style of rendering. Possible values are:
            * `D`: draw border. This is the default value.
            * `F`: fill.
            * `DF` or `FD`: draw and fill.
        r   r   r   r  T)r  r  N)r  r  r	  r  r
  r  r  )r   r   r   Zr_inZr_outZcornersZrotate_degreesr  thr  r  Zcorner_xZcorner_yr   r   r   star  s    
""z	FPDF.starc                     s  t |}dkr  d  d |  | dd  fdd}|}t|t| fdd} fd	d
}||}||}|s||kr|dtj 7 }n|r||kr|dtj 7 }||}|	rH| | j dd| j | j dd | |d | j dd| j|d  | j dd n4| |d | j dd| j|d  | j dd d}t	|t
t|| dtj |  }|| | }t|tddt|d d   d  d }|}||}||}t|D ]&}|}|}||7 }||}||}|d ||d   |d ||d   g}|d ||d   |d ||d   g}d}||d kr|
sd|j }| |d | j dd| j|d  | j dd|d | j dd| j|d  | j dd|d | j dd| j|d  | j dd|  q |
r||	rJ| d|j  n2| | j dd| j | j dd|j  dS )a  
        Outputs an arc.
        It can be drawn (border only), filled (with no border) or both.

        Args:
            a (float): Semi-major axis diameter.
            b (float): Semi-minor axis diameter, if None, equals to a (default: None).
            start_angle (float): Start angle of the arc (in degrees).
            end_angle (float): End angle of the arc (in degrees).
            inclination (float): Inclination of the arc in respect of the x-axis (default: 0).
            clockwise (bool): Way of drawing the arc (True: clockwise, False: counterclockwise) (default: False).
            start_from_center (bool): Start drawing from the center of the circle (default: False).
            end_at_center (bool): End drawing at the center of the circle (default: False).
            style (fpdf.enums.RenderStyle, str): Optional style of rendering. Allowed values are:

            * `D` or None: draw border. This is the default value.
            * `F`: fill
            * `DF` or `FD`: draw and fill
        Nr   c                 S   s   | t j d S )Nr  )r  pi)degr   r   r   
deg_to_radR  s    zFPDF.arc.<locals>.deg_to_radc                    sF   | d } t t |  t |   }|dk rB|dt j 7 }|S )Nr  r   r   )r  atan2r  r
  r  )angleeta)ar  r  r   r   angle_to_paramU  s
     z FPDF.arc.<locals>.angle_to_paramc                    sD    t |  }t |  }|  |  |  |  gS r  )r  r
  r  )r  Z	a_cos_etaZ	b_sin_eta)r  r  	cos_thetar  r  	sin_thetar   r   evaluatea  s
    zFPDF.arc.<locals>.evaluatec                    s@    t |  }t |  }|  |  |  |  gS r  )r  r  r
  )r  Z	a_sin_etaZ	b_cos_eta)r  r  r  r  r   r   derivative_evaluatej  s
    z%FPDF.arc.<locals>.derivative_evaluater  r  z mr   r   z l   r  r   r   zh z l )r?   r  r  r
  r  r  r  r   r4  r  ceilabsr  tanr	  r  ) r   r   r   r  start_angle	end_angler  inclination	clockwiseZstart_from_centerZend_at_centerr  r  thetar  r  Z	start_etaZend_etaZstart_pointZ
max_curvesnZd_etaalphaZeta2p2Zp2_primer  p1Zp1_primeZcontrol_point_1Zcontrol_point_2endr   )r  r  r  r  r  r  r  r   r  $  sz    "


	,,, 2((*zFPDF.arcc
           
      C   s"   |  ||||||||dd|	 dS )a  
        Outputs a solid arc. A solid arc combines an arc and a triangle to form a pie slice
        It can be drawn (border only), filled (with no border) or both.

        Args:
            x (float): Abscissa of upper-left bounding box.
            y (float): Ordinate of upper-left bounding box.
            a (float): Semi-major axis.
            b (float): Semi-minor axis, if None, equals to a (default: None).
            start_angle (float): Start angle of the arc (in degrees).
            end_angle (float): End angle of the arc (in degrees).
            inclination (float): Inclination of the arc in respect of the x-axis (default: 0).
            clockwise (bool): Way of drawing the arc (True: clockwise, False: counterclockwise) (default: False).
            style (str): Style of rendering. Possible values are:

            * `D` or None: draw border. This is the default value.
            * `F`: fill
            * `DF` or `FD`: draw and fill
        TN)r  )
r   r   r   r  r#  r$  r  r%  r&  r  r   r   r   	solid_arc  s    zFPDF.solid_arcc              	   C   sN  t |}|dkrtdt|}|  }|d }|d |d  }}t||}	||	 |d }
|
d |
d  }}|d }|d |d  }}|dkr|d }|d |d  }}t||}tj}|j	r|j
stj}n|j
r|j	stj}||j_||j_|dkr||||||| n|dkr6||||||| || W 5 Q R X dS )	u  
        Outputs a quadratic or cubic Bézier curve, defined by three or four coordinates.

        Args:
            point_list (list of tuples): List of Abscissa and Ordinate of
                                        segments that should be drawn. Should be
                                        three or four tuples. The first and last
                                        points are the start and end point. The
                                        middle point(s) are the control point(s).
            closed (bool): True to draw the curve as a closed path, False (default)
                                        for it to be drawn as an open path.
            style (fpdf.enums.RenderStyle, str): Optional style of rendering. Allowed values are:
            * `D` or None: draw border. This is the default value.
            * `F`: fill
            * `DF` or `FD`: draw and fill
        )r  r  zWpoint_list should contain 3 tuples for a quadratic curve or 4 tuples for a cubic curve.r   r   r   r  r  N)r7  r/  r?   r  r  r*   r  r=   ZSTROKE_FILL_NONZEROr  r  ZSTROKEZFILL_NONZEROr  r  
auto_closeZcurve_to)r   r  closedr  r  r  r+  r  r  Z
dummy_pathr*  r  r  Zp3Zx3Zy3Zp4Zx4Zy4r  Zruler   r   r   bezier  s>    





zFPDF.bezierc           	      C   s,  |st dtt|d  }|dkr8t d| d|dkrRtjdtt d d	t	|
 }td
d |D rt d| dtfD ]*}|sqt||  rt|| } qqtd| |dkr|j}|  | }|| jks|tkrtjd| dt d dS t| |||| j|< dS )a  
        Imports a TrueType or OpenType font and makes it available
        for later calls to the `FPDF.set_font()` method.

        You will find more information on the "Unicode" documentation page.

        Args:
            family (str): optional name of the font family. Used as a reference for `FPDF.set_font()`.
                If not provided, use the base name of the `fname` font path, without extension.
            style (str): font style. "" for regular, include 'B' for bold, and/or 'I' for italic.
            fname (str): font file name. You can specify a relative or full path.
                If the file is not found, it will be searched in `FPDF_FONT_DIR`.
            uni (bool): [**DEPRECATED since 2.5.1**] unused
        z"fname" parameter is requiredr   )z.otfz.otcz.ttfz.ttcz!Unsupported font file extension: z. add_font() used to accept .pkl file as input, but for security reasons this feature is deprecated since v2.5.1 and has been removed in v2.5.3.r   zK"uni" parameter is deprecated since v2.5.1, unused and will soon be removedr   r   c                 s   s   | ]}|d kV  qdS BINr   r  r~   r   r   r   r  I  s     z FPDF.add_font.<locals>.<genexpr>z9Unknown style provided (only B & I letters are allowed): .zTTF Font file not found: Nz!Core font or font already added 'z': doing nothing)r/  r
   r   r   r   r   r   r$   rv  sortedr  anyFPDF_FONT_DIRr   existsFileNotFoundErrorstemr   rL   rP   )	r   r  r  fnameuniextparentZfont_file_pathfontkeyr   r   r   add_font$  sF    
	
zFPDF.add_fontr  c                 C   s  |s
| j }| }t|tr"|j}dt| }tdd |D rTt	d| d|krpd| _
|dd}nd| _
d|krd| _|dd}nd| _|| jkr|| | jkrtjd	| d
| j|  dtt d | j| }n,|dkr|rtjd| dt d d}|s| j}| j |krD| j|krDt| j|rDdS || }|| jkr|tkrrtd| dt| ||| j|< || _ || _|| _| j| | _d| _dS )a;  
        Sets the font used to print character strings.
        It is mandatory to call this method at least once before printing text.

        Default encoding is not specified, but all text writing methods accept only
        unicode for external fonts and one byte encoding for standard.

        Standard fonts use `Latin-1` encoding by default, but Windows
        encoding `cp1252` (Western Europe) can be used with
        `self.core_fonts_encoding = encoding`.

        The font specified is retained from page to page.
        The method can be called before the first page is created.

        Args:
            family (str): name of a font added with `FPDF.add_font`,
                or name of one of the 14 standard "PostScript" fonts:
                Courier (fixed-width), Helvetica (sans serif), Times (serif),
                Symbol (symbolic) or ZapfDingbats (symbolic)
                If an empty string is provided, the current family is retained.
            style (str, fpdf.enums.TextEmphasis): empty string (by default) or a combination
                of one or several letters among B (bold), I (italic), S (strikethrough) and U (underline).
                Bold and italic styles do not apply to Symbol and ZapfDingbats fonts.
            size (float): in points. The default value is the current size.
        r   c                 s   s   | ]}|d kV  qdS )ZBISUNr   r3  r   r   r   r    s     z FPDF.set_font.<locals>.<genexpr>z;Unknown style provided (only B/I/S/U letters are allowed): r  TFr  zSubstituting font z by core font z< - This is deprecated since v2.7.8, and will soon be removedr   )symbolZzapfdingbatszBuilt-in font z6 only has a single 'style' and can't be bold or italicNzUndefined font: z3 - Use built-in fonts or FPDF.add_font() beforehand)r   r   r   rA   r  rv  r5  r  r6  r/  r   replacer   r   r   r   r   r   r$   r   r   r   rL   rH   rK   r   r   )r   r  r  r  r?  r   r   r   r  f  sh    




zFPDF.set_fontc                 C   s    t | j|rdS || _d| _dS )zp
        Configure the font size in points

        Args:
            size (float): font size in points
        NF)r   r   r   )r   r  r   r   r   set_font_size  s    zFPDF.set_font_sizec                 C   sF   d|j  d|dd}|r&d| d}| jtj|j | j d| _|S )z
        Set font and size for current page.
        This step is needed before adding text into page and not needed in set_font and set_font_size.
        /Fr  r   TfBT  ETT)r  r  r  r>   FONTr   r   )r   r   r   wrap_in_text_objectslr   r   r   _set_font_for_page  s    zFPDF._set_font_for_pagec                 C   s6   | j |krdS || _ | jdkr2| d|dd dS )a\  
        Sets horizontal character spacing.
        A positive value increases the space between characters, a negative value
        reduces it (which may result in glyph overlap).
        By default, no spacing is set (which is equivalent to a value of 0).

        Args:
            spacing (float): horizontal spacing in document units
        Nr   rF  r  z Tc ET)r   r   r  )r   spacingr   r   r   r    s
    


zFPDF.set_char_spacingc                 C   s6   | j |krdS || _ | jdkr2| d|dd dS )z
        Sets horizontal font stretching.
        By default, no stretching is set (which is equivalent to a value of 100).

        Args:
            stretching (float): horizontal stretching (scaling) in percents.
        Nr   rF  r  z Tz ET)r   r   r  )r   r  r   r   r   r    s
    

zFPDF.set_stretchingc                 C   sp   g }|D ]R}d}| j D ].}|dddd| kr|| d}q|std| dqt|| _|| _dS )	a;  
        Allows you to specify a list of fonts to be used if any character is not available on the font currently set.
        Detailed documentation: https://py-pdf.github.io/fpdf2/Unicode.html#fallback-fonts

        Args:
            fallback_fonts: sequence of fallback font IDs
            exact_match (bool): when a glyph cannot be rendered uing the current font,
                fpdf2 will look for a fallback font matching the current character emphasis (bold/italics).
                If it does not find such matching font, and `exact_match` is True, no fallback font will be used.
                If it does not find such matching font, and `exact_match` is False, a fallback font will still be used.
                To get even more control over this logic, you can also override `FPDF.get_fallback_font()`
        FBr   ITzUndefined fallback font: z! - Use FPDF.add_font() beforehandN)r   rB  r   r  rH   r  r   r   )r   Zfallback_fontsZexact_matchZfallback_font_idsfallback_fontfoundr?  r   r   r   set_fallback_fonts  s    



zFPDF.set_fallback_fontsnullc                 C   sL   t |dkr| jn|| j|| j  || j |d}t| jd }|| j|< |S )aO  
        Creates a new internal link and returns its identifier.
        An internal link is a clickable area which directs to another place within the document.

        The identifier can then be passed to the `FPDF.cell()`, `FPDF.write()`, `FPDF.image()`
        or `FPDF.link()` methods.

        Args:
            y (float): optional ordinate of target position.
                The default value is 0 (top of page).
            x (float): optional abscissa of target position.
                The default value is 0 (top of page).
            page (int): optional number of target page.
                -1 indicates the current page, which is the default value.
            zoom (float): optional new zoom level after following the link.
                Currently ignored by Sumatra PDF Reader, but observed by Adobe Acrobat reader.
        r<  )r?  r>  rN  r   )rn   r   rH  r   r7  r   )r   r   r   r   rN  linkZ
link_indexr   r   r   add_link	  s    
zFPDF.add_linkc                 C   sF   | j | }|dkr| jn||_| j|| j  |_|| j |_||_dS )a  
        Defines the page and position a link points to.

        Args:
            link (int): a link identifier returned by `FPDF.add_link()`.
            y (float): optional ordinate of target position.
                The default value is 0 (top of page).
            x (float): optional abscissa of target position.
                The default value is 0 (top of page).
            page (int): optional number of target page.
                -1 indicates the current page, which is the default value.
            zoom (float): optional new zoom level after following the link.
                Currently ignored by Sumatra PDF Reader, but observed by Adobe Acrobat reader.
        r<  N)r   r   page_numberrH  r   r?  r>  rN  )r   rS  r   r   r   rN  r   r   r   set_link1	  s
    
zFPDF.set_linkc              	   K   s   d\}}	|rft |tr t|}nF|| jksFtd| dt| j d| j| }	|	jsftd| dtd|| j	 | j
|| j	  || j	 || j	 ||	d|}
| j| j j|
 |d	k	r| jd
|d |
S )a  
        Puts a link annotation on a rectangular area of the page.
        Text or image links are generally put via `FPDF.cell`,
        `FPDF.write` or `FPDF.image`,
        but this method can be useful for instance to define a clickable area inside an image.

        Args:
            x (float): horizontal position (from the left) to the left side of the link rectangle
            y (float): vertical position (from the top) to the bottom side of the link rectangle
            w (float): width of the link rectangle
            h (float): height of the link rectangle
            link: either an URL or an integer returned by `FPDF.add_link`, defining an internal link to a page
            alt_text (str): optional textual description of the link, for accessibility purposes
            border_width (int): thickness of an optional black border surrounding the link.
                Not all PDF readers honor this: Acrobat renders it but not Sumatra.
        r   zLink with an invalid index: z (doc #links=)zCannot insert link z with no page number assignedLink)r   r   r  heightactiondestNz/Link)struct_typealt_text)rX  )r   r   r   r   AssertionErrorr7  rU  r/  r   r   rH  r   r   annotsr  _add_marked_content)r   r   r   r1  r4  rS  r]  r   rZ  r[  Z
link_annotr   r   r   rS  I	  s:    



 
z	FPDF.linkc           
   	   K   s   |rj|rt d|rt dt|}|d}| }W 5 Q R X |j}| }|dkrt|j	 }n|svt d|st dt
dd | jD }||krt | d	tf |||d
|}	| j|	 | d |	S )aT  
        Embed a file into the PDF document

        Args:
            file_path (str or Path): filesystem path to the existing file to embed
            bytes (bytes): optional, as an alternative to file_path, bytes content of the file to embed
            basename (str): optional, required if bytes is provided, file base name
            creation_date (datetime): date and time when the file was created
            modification_date (datetime): date and time when the file was last modified
            desc (str): optional description of the file
            compress (bool): enabled zlib compression of the file - False by default
            checksum (bool): insert a MD5 checksum of the file content - False by default

        Returns: a PDFEmbeddedFile instance, with a .basename string attribute representing the internal file name
        z+'bytes' cannot be provided with 'file_path'z.'basename' cannot be provided with 'file_path'rbNz2'bytes' is required if 'file_path' is not providedz5'basename' is required if 'file_path' is not providedc                 s   s   | ]}|  V  qd S r  )basename)r  filer   r   r   r  	  s    z"FPDF.embed_file.<locals>.<genexpr>z' has already been embedded in this file)rb  r  modification_dater-  )r/  r   openreadnamestatr   fromtimestampst_mtimerm  setr   r    r  r  )
r   	file_pathbytesrb  rd  r   Z
input_filestatsZalready_embedded_basenamesembedded_filer   r   r   
embed_filez	  sB    
zFPDF.embed_filec              
   K   sx   | j |f|}	|	d td|| j | j|| j  || j || j |	 |rVt|nd|d}
| j| j	 j
|
 |
S )a5  
        Puts a file attachment annotation on a rectangular area of the page.

        Args:
            file_path (str or Path): filesystem path to the existing file to embed
            x (float): horizontal position (from the left) to the left side of the link rectangle
            y (float): vertical position (from the top) to the bottom side of the link rectangle
            w (float): optional width of the link rectangle
            h (float): optional height of the link rectangle
            name (fpdf.enums.FileAttachmentAnnotationName, str): optional icon that shall be used in displaying the annotation
            flags (Tuple[fpdf.enums.AnnotationFlag], Tuple[str]): optional list of flags defining annotation properties
            bytes (bytes): optional, as an alternative to file_path, bytes content of the file to embed
            basename (str): optional, required if bytes is provided, file base name
            creation_date (datetime): date and time when the file was created
            modification_date (datetime): date and time when the file was last modified
            desc (str): optional description of the file
            compress (bool): enabled zlib compression of the file - False by default
            checksum (bool): insert a MD5 checksum of the file content - False by default
        FZFileAttachmentN)	file_specrg  flags)rp  Zset_globally_enclosedr   r   rH  rq  r7   r  r   r   r_  r  )r   rl  r   r   r1  r4  rg  rr  r   ro  
annotationr   r   r   file_attachment_annotation	  s    

zFPDF.file_attachment_annotationc           	      K   sb   t d|| j | j|| j  || j || j f||r<t|ndd|}| j| j j| |S )u  
        Puts a text annotation on a rectangular area of the page.

        Args:
            x (float): horizontal position (from the left) to the left side of the link rectangle
            y (float): vertical position (from the top) to the bottom side of the link rectangle
            text (str): text to display
            w (float): optional width of the link rectangle
            h (float): optional height of the link rectangle
            name (fpdf.enums.AnnotationName, str): optional icon that shall be used in displaying the annotation
            flags (Tuple[fpdf.enums.AnnotationFlag], Tuple[str]): optional list of flags defining annotation properties
            title (str): the text label that shall be displayed in the title bar of the annotation’s
                pop-up window when open and active. This entry shall identify the user who added the annotation.
        TextN)r  rg  )	r   r   rH  r3   r  r   r   r_  r  )	r   r   r   r  r1  r4  rg  r   rs  r   r   r   text_annotation	  s    
zFPDF.text_annotationc              
   K   s   | j std| js*| | | j| j |dkr8| j}|dkrF| j}|dkrT| j	}|dkrl| j
|ddd}td|| j | j|| j  || j || j f|d| j  d| jj d	| jd
dd|}| j| j j| |S )a0  
        Puts a free text annotation on a rectangular area of the page.

        Args:
            text (str): text to display
            x (float): optional horizontal position (from the left) to the left side of the link rectangle.
                Default value: None, meaning the current abscissa is used
            y (float): vertical position (from the top) to the bottom side of the link rectangle.
                Default value: None, meaning the current ordinate is used
            w (float): optional width of the link rectangle. Default value: None, meaning the length of text in user unit
            h (float): optional height of the link rectangle. Default value: None, meaning an height equal
                to the current font size
            flags (Tuple[fpdf.enums.AnnotationFlag], Tuple[str]): optional list of flags defining annotation properties
            color (tuple): a tuple of numbers in the range 0.0 to 1.0, representing a colour used for the annotation background
            border_width (float): width of the annotation border
        3No font set, you need to call set_font() beforehandNTFr  r  ZFreeText(z /Fr  r  z Tf))r  Zdefault_appearance)r   rH   r   r  rK  r   r   r   r   	font_sizer  r   r   rH  r   r  r  r   r   r_  r  )r   r  r   r   r1  r4  r   rs  r   r   r   free_text_annotation	  s4    $
zFPDF.free_text_annotationc                 K   sR   t d|| j | j|| j  || j || j fd|i|}| j| j j| |S )a  
        Puts an Action annotation on a rectangular area of the page.

        Args:
            action (fpdf.actions.Action): the action to add
            x (float): horizontal position (from the left) to the left side of the link rectangle
            y (float): vertical position (from the top) to the bottom side of the link rectangle
            w (float): width of the link rectangle
            h (float): height of the link rectangle
        ActionrZ  )r   r   rH  r   r   r_  r  )r   rZ  r   r   r1  r4  r   rs  r   r   r   
add_action*
  s    	zFPDF.add_action	Highlightr   r   r   c                 k   s`   | j rtdd| _ dV  | j D ]&\}}| j||f||||d| q$tt| _d| _ dS )u/  
        Context manager that adds a single highlight annotation based on the text lines inserted
        inside its indented block.

        Args:
            text (str): text of the annotation
            title (str): the text label that shall be displayed in the title bar of the annotation’s
                pop-up window when open and active. This entry shall identify the user who added the annotation.
            type (fpdf.enums.TextMarkupType, str): "Highlight", "Underline", "Squiggly" or "StrikeOut".
            color (tuple): a tuple of numbers in the range 0.0 to 1.0, representing a colour used for
                the title bar of the annotation’s pop-up window. Defaults to yellow.
            modification_time (datetime): date and time when the annotation was most recently modified
        zhighlight() cannot be nestedTN)quad_pointsmodification_timer   colorF)r  rH   r  itemsadd_text_markup_annotationr   r  )r   r  r  r  r  r   r   r  r   r   r   	highlightB
  s$    	
zFPDF.highlightc              	   o   s4   t jdtt d | j|| d V  W 5 Q R X d S )Nz:add_highlight() has been renamed to highlight() in v2.5.5.r   )r   r   r   r$   r  r   r   r   r   add_highlightd
  s    FPDF.add_highlightc                 K   s   |  d t|j}|dkr$| j}|dkr2| j}t|ddd }t|ddd }	t|ddd }
t|ddd }t|f||	||
| ||	 |||d|}| j	| j
| |S )u  
        Adds a text markup annotation on some quadrilateral areas of the page.

        Args:
            type (fpdf.enums.TextMarkupType, str): "Highlight", "Underline", "Squiggly" or "StrikeOut"
            text (str): text of the annotation
            quad_points (tuple): array of 8 × n numbers specifying the coordinates of n quadrilaterals
                in default user space that comprise the region in which the link should be activated.
                The coordinates for each quadrilateral are given in the order: x1 y1 x2 y2 x3 y3 x4 y4
                specifying the four vertices of the quadrilateral in counterclockwise order
            title (str): the text label that shall be displayed in the title bar of the annotation’s
                pop-up window when open and active. This entry shall identify the user who added the annotation.
            color (tuple): a tuple of numbers in the range 0.0 to 1.0, representing a colour used for
                the title bar of the annotation’s pop-up window. Defaults to yellow.
            modification_time (datetime): date and time when the annotation was most recently modified
            page (int): index of the page where this annotation is added
        r#  Nr   r   r   )r  r   r   r  rY  r  r  r  )r  rB   r  r.  r   r   r  r  r   r   r_  r  )r   r  r  r  r  r  r   r   x_miny_minx_maxy_maxrs  r   r   r   r  n
  s4    

zFPDF.add_text_markup_annotationc                    s   t  fdd|D d}t|ddd }t|ddd }t|ddd }	t|ddd }
td
||
|	| |
| ||||d	|} j j j| |S )u  
        Adds add an ink annotation on the page.

        Args:
            coords (tuple): an iterable of coordinates (pairs of numbers) defining a path
            text (str): textual description
            title (str): the text label that shall be displayed in the title bar of the annotation’s
                pop-up window when open and active. This entry shall identify the user who added the annotation.
            color (tuple): a tuple of numbers in the range 0.0 to 1.0, representing a colour used for
                the title bar of the annotation’s pop-up window. Defaults to yellow.
            border_width (float): thickness of the path stroke.
        c                 3   s,   | ]$\}}| j   j|  j  fV  qd S r  )r   r4  )r  r   r   r   r   r   r  
  s     z&FPDF.ink_annotation.<locals>.<genexpr>r   r   Nr   r   Ink)r   r   r  rY  ink_listr  border_widthr  )r  )sumr  r  r   r   r   r_  r  )r   Zcoordsr  r  r  r   r  r  r  r  r  rs  r   r   r   ink_annotation
  s*     
zFPDF.ink_annotationc                 C   s  | j std| |}| js4| | | j| j d|| j dd| j	| | j ddg}| j
tjkr|d| j
 d| jdd || j| d |d	kr| js| js| jr6| j|d
dd}|d	kr| jr|| ||| | jr|| ||| | jr6| j}|d| 8 }| |||| g }| j| jkr^|| j    |rxdg| | dg }| d| dS )a  
        Prints a character string. The origin is on the left of the first character,
        on the baseline. This method allows placing a string precisely on the page,
        but it is usually easier to use the `FPDF.cell()`, `FPDF.multi_cell() or `FPDF.write()` methods.

        Args:
            x (float): abscissa of the origin
            y (float): ordinate of the origin
            text (str): string to print
            txt (str): [**DEPRECATED since v2.7.6**] string to print

        Notes
        -----

        `text()` lacks many of the features available in `FPDF.write()`,
        `FPDF.cell()` and `FPDF.multi_cell()` like markdown and text shaping.
        rw  rF  r  r   Td Tr r  rG  r   TFrx  g?qQN)r   rH   r  r   r  rK  r   r   r   r4  r   rC   r   r  r   Zencode_textr   r   r  r  _do_underline_do_strikethroughrz  _add_quad_pointsr   r   r  r   rv  )r   r   r   r  rJ  r1  r4  Zattr_lr   r   r   r  
  sB    
*
z	FPDF.textc                 C   s   t jdtt d |dkr | j}|dkr.| j}| jdkrB| d || _|dkr|tj	d 9 }t
|}t|}|| j }| j| | j }d|dd	|dd	| dd	|dd	|d
d	|d
d| d
d	| d
d}| | dS )zR
        .. deprecated:: 2.1.0
            Use `FPDF.rotation()` instead.
        zrotate() can produces malformed PDFs and is deprecated since v2.1.0. It will be removed in a future release. Use the rotation() context manager instead.r   Nr   r  r  q .5Fr  .2F cm 1 0 0 1  cm)r   r   r   r$   r   r   r   r  r  r  r
  r  r   r4  r   r  r   r   cr  r  r  r   r   r   rotate
  s*    	




JzFPDF.rotatec                 c   s   |dkr| j }|dkr| j}|tjd 9 }t|t| }}|| j | j| | j  }}|  \ | 	|dd|dd| dd|dd|dd|dd| dd| dd dV  W 5 Q R X dS )a  
        Method to perform a rotation around a given center.
        It must be used as a context-manager using `with`:

            with rotation(angle=90, x=x, y=y):
                pdf.something()

        The rotation affects all elements which are printed inside the indented
        context (with the exception of clickable areas).

        Args:
            angle (float): angle in degrees
            x (float): abscissa of the center of the rotation
            y (float): ordinate of the center of the rotation

        Notes
        -----

        Only the rendering is altered. The `FPDF.get_x()` and `FPDF.get_y()` methods are
        not affected, nor the automatic page break mechanism.
        The rotation also establishes a local graphics state, so that any
        graphics state settings changed within will not affect the operations
        invoked after it has finished.
        Nr  r  r  r  r  r  )
r   r   r  r  r
  r  r   r4  r  r  r  r   r   r   rotation  s    
HzFPDF.rotationc                 c   s   d}|dkr| j }|dkr | j}ttt|tjd  || }ttt|tjd  || }|| j | j| | j  }}| 	 H | 
d|dd|dd|dd|dd	|dd
|dd dV  W 5 Q R X dS )a  
        Method to perform a skew transformation originating from a given center.
        It must be used as a context-manager using `with`:

            with skew(ax=15, ay=15, x=x, y=y):
                pdf.something()

        The skew transformation affects all elements which are printed inside the indented
        context (with the exception of clickable areas).

        Args:
            ax (float): angle of skew in the horizontal direction in degrees
            ay (float): angle of skew in the vertical direction in degrees
            x (float): abscissa of the center of the skew transformation
            y (float): ordinate of the center of the skew transformation
        l        Nr  z1 .5fr  z 1 r   cm 1 0 0 1 - -r  )r   r   r  r  r  r"  r  r   r4  r  r  )r   ZaxZayr   r   Zlim_valr  r  r   r   r   skewD  s    ""
4z	FPDF.skewc           
      c   s   |\}}zt |j}W n tk
r0   |}Y nX tt|d }tt|d }|| j | j	| | j  }}	| 
 Z | |dd|dd|dd|d dd|dd|	dd|dd|	dd d	V  W 5 Q R X d	S )
a+  
        Method to perform a reflection transformation over a given mirror line.
        It must be used as a context-manager using `with`:

            with mirror(origin=(15,15), angle="SOUTH"):
                pdf.something()

        The mirror transformation affects all elements which are rendered inside the indented
        context (with the exception of clickable areas).

        Args:
            origin (float, Sequence(float, float)): a point on the mirror line
            angle: (fpdf.enums.Angle): the direction of the mirror line
        r   r  r  r<  r  r  r  r  N)r1   r  r.  r/  r  r
  r  r  r   r4  r  r  )
r   originr  r   r   r'  r  r  r  r  r   r   r   mirrorf  s    

FzFPDF.mirrorc                 k   s<   | j rtd|   | jf | dV  |   |   dS )a2  
        Creates a local graphics state, which won't affect the surrounding code.
        This method must be used as a context manager using `with`:

            with pdf.local_context():
                set_some_state()
                draw_some_stuff()

        The affected settings are those controlled by GraphicsStateMixin and drawing.GraphicsStyle:

        * allow_transparency
        * auto_close
        * blend_mode
        * char_vpos
        * char_spacing
        * dash_pattern
        * denom_lift
        * denom_scale
        * draw_color
        * fill_color
        * fill_opacity
        * font_family
        * font_size
        * font_size_pt
        * font_style
        * font_stretching
        * intersection_rule
        * line_width
        * nom_lift
        * nom_scale
        * paint_rule
        * strikethrough
        * stroke_cap_style
        * stroke_join_style
        * stroke_miter_limit
        * stroke_opacity
        * sub_lift
        * sub_scale
        * sup_lift
        * sup_scale
        * text_color
        * text_mode
        * text_shaping
        * underline

        Font size can be specified in document units with `font_size` or in points with `font_size_pt`.

        Args:
            **kwargs: key-values settings to set at the beginning of this context.
        z@cannot create a local context inside an unbreakable() code blockN)r   rH   r  r  r  r  )r   r   r   r   r   r    s    5zFPDF.local_contextc	                 K   s  d|	kr,|dk	rt d|	d | j }|	d= d}
|	 D ]|\}}|dkrXt d| d|tjkr|
dkrpt }
t|
|| |dkr| d q8|d	krt| || q8t d| q8|
r| j|
}| j	
tj|| j | d
| d n
| d |dk	s|dk	s|dk	rD| |p$| j|dkr4| jn||p@| j |dk	rX| | |dk	rl| | |dk	r| | |dk	r| | |dk	r| jf | dS )z
        This method starts a "q/Q" context in the page content stream,
        and inserts operators in it to initialize all the PDF settings specified.
        rz  Nz0font_size & font_size_pt cannot be both provided)r  r  r  r  zUnsupported setting: zH - This can be controlled through dash_pattern / draw_color / line_widthZ
blend_moder-  )	char_vposr   r   Z
denom_liftZdenom_scaler   Znom_liftZ	nom_scaler   Zsub_liftZ	sub_scaleZsup_liftZ	sup_scaler   rV  r   r   zq /z gsr  )r/  r   r  r)   ZMERGE_PROPERTIESsetattrr  r   Zregister_styler  r  r>   r  r   r  r  r   r   r   r  r  r  r  r  )r   r   r   r   r   r   r   r   r   r   r  keyr.  Zgs_namer   r   r   r    s\    













zFPDF._start_local_contextc                 C   s   |  d dS )zN
        This method ends a "q/Q" context in the page content stream.
        r  N)r  r   r   r   r   r  %  s    zFPDF._end_local_contextc                 C   s   | j S )an  
        Whenever a page break condition is met, this method is called,
        and the break is issued or not depending on the returned value.

        The default implementation returns a value according to the mode selected by `FPDF.set_auto_page_break()`.
        This method is called automatically and should not be called directly by the application.
        )r9  r   r   r   r   accept_page_break+  s    	zFPDF.accept_page_breakc                 C   sp  | j stdt|ts"t|tr*tdt|trP|dkrPtjdt d d}t	
|}t
|}t
|}|tjkrtd|dkr|d	krt	j}tj}n<|dkrt	j}tj}n&|d
krt	j}tj}ntd| dtjd| d|j d|j dtt d | |}| jr$| ||
n
| ||
}| jt|d	d	|tjkrNtjn|||dd|||||||	|
d	S )a
  
        Prints a cell (rectangular area) with optional borders, background color and
        character string. The upper-left corner of the cell corresponds to the current
        position. The text can be aligned or centered. After the call, the current
        position moves to the selected `new_x`/`new_y` position. It is possible to put a link
        on the text. A cell has an horizontal padding, on the left & right sides, defined by
        the.c_margin property.

        If automatic page breaking is enabled and the cell goes beyond the limit, a
        page break is performed before outputting.

        Args:
            w (float): Cell width. Default value: None, meaning to fit text width.
                If 0, the cell extends up to the right margin.
            h (float): Cell height. Default value: None, meaning an height equal
                to the current font size.
            text (str): String to print. Default value: empty string.
            border: Indicates if borders must be drawn around the cell.
                The value can be either a number (`0`: no border ; `1`: frame)
                or a string containing some or all of the following characters
                (in any order):
                `L`: left ; `T`: top ; `R`: right ; `B`: bottom. Default value: 0.
            new_x (fpdf.enums.XPos, str): New current position in x after the call. Default: RIGHT
            new_y (fpdf.enums.YPos, str): New current position in y after the call. Default: TOP
            ln (int): **DEPRECATED since 2.5.1**: Use `new_x` and `new_y` instead.
            align (fpdf.enums.Align, str): Set text alignment inside the cell.
                Possible values are: `L` or empty string: left align (default value) ;
                `C`: center; `X`: center around current x position; `R`: right align
            fill (bool): Indicates if the cell background must be painted (`True`)
                or transparent (`False`). Default value: False.
            link (str): optional link to add on the cell, internal
                (identifier returned by `FPDF.add_link`) or external URL.
            center (bool): center the cell horizontally on the page.
            markdown (bool): enable minimal markdown-like markup to render part
                of text as bold / italics / strikethrough / underlined.
                Supports `\` as escape character. Default to False.
            txt (str): [**DEPRECATED since v2.7.6**] String to print. Default value: empty string.

        Returns: a boolean indicating if page break was triggered
        rw  jParameter 'w' and 'h' must be numbers, not strings. You can omit them by passing string content with text=r   r   HInteger values for "border" parameter other than 1 are currently ignoredr   r   zGcell() only produces one text line, justified alignment is not possibler   r   r   "Invalid value for parameter "ln" (z"), must be an int between 0 and 2.=The parameter "ln" is deprecated since v2.5.2. Instead of ln= use new_x=XPos., new_y=YPos.r4  F
text_widthnumber_of_spacesalignrY  	max_widthtrailing_nl)new_xnew_yr  rS  centerprevent_font_change)r   rH   r   r   r/  r   r   r   r$   rE   r  rF   r0   JRIGHTTOPLMARGINNEXTLEFTrg  r   r  rV  r  _preload_font_styles_render_styled_text_liner^   L)r   r1  r4  r  borderlnr  r  rS  r  r  r  r  styled_txt_fragsr   r   r   cell6  sz    9





	

	z	FPDF.cell)		text_liner4  r  r  r  r  rS  r  paddingc           0      C   s	  t |tr(|dkr(tjdt d d}nt |trDt|drDd}|	dkrZtdddd}	d }}|	j	dkrr| j
}|	jdkr| j
}|j}|st|jD ] \}}|j|dkd}||7 }q|j}|dkr|jstd	|| | }n|dkr| j| j | j }|r| j| j| d
  | _n |jtjkr:|  j|d
 8  _d}| }|D ]}|j|krJ|j}qJ|dkrr|}| |}g }| j}| j|	j	 | }| j| |	j | }| j| j |	j  | }| j| j|  |	j! | }|r*|dkrdnd}|"|dd|dd|| dd|| dd| 	 n<|dkrf|"|dd|dd|| dd|| dd t |trBd|kr|"|dd|dd|dd|dd d|kr|"|dd|dd|dd|dd d|kr|"|dd|dd|dd|dd d|krB|"|dd|dd|dd|dd | j#r^| $| j| j|| | j}d}d }}d} t%j&}!| j'}"| j(}#| j)}$| j*}%| j+}&| j,}'d}(| j-})|r|jtj.kr|| | }*n&|jtj/tjfkr|| d
 }*n|}*||*7 }d}+|jtj0kr(|j1r(|| | | |j1 }+|"d| j|* | dd| j| j d|  d|  | dd t|D ]R\}}t |t2r| j3| j4 5| |j6d |)kr|j6d })|"|)7 8  d}(|+r|j+dkr|+d |j+ }n|+}|&|j+kr|j+}&|"|j+dd |'|j,kr<|j,}'|"|j,dd  | j9s|
r|j:}"|j(}#|j)}$|"d!|"j; d|#dd" | j<=t>j?|"j;| j4 |j@}!n<|j: }"| _'|j( }#| _(|j) }$| _)| A| B|"|# |j@}!n^|"|j:ks|#|j(ks|$|j)ks|!|j@kr2|j:}"|j(}#|j)}$|"| jB|"|#dd# |j@}!|jC},|,| krX|"|,dd$ |,} |j*tDjEksr|j*|%kr|j*}%|"|j* d%|jFdd& |G|||+| j|* | | jd| d|   | j}-|-r|"|- |j|dkd|+|jHId  }.|jJr4|"| K| j|* | | jd|  d|j  |.|j: |jLrr|"| M| j|* | | jd|  d|j  |.|j: |jNr| jN| j|* | | jd|  d|j  |.|j|jNd' |jOs|}||.7 }qr|"d( |r| N| j|* | jd|  d|j  ||j| |r|dksz| dksz|!t%j&ksz|"| j'ksz|#| j(ksz|$| j)ksz|%| j*ksz|(sz|&| j+ksz|'| j,krd)dP| d*}/n
dP|}/| A|/ |p| j| _Q|tRjSkr|  j|7  _n|tRjTkr|| _n|tRjUkr|| | _nv|tRjVk	r"|	r|| | | _n|| _nL|tRjWk	r>||d+  | _n0|tRjXk	rT| j| _n|tRjYk	rn| j| j | _|tZj[k	r|  j|7  _|tZj\k	r| j]| _|tZj^k	r| j| j_ | _|S ),a  
        Prints a cell (rectangular area) with optional borders, background color and
        character string. The upper-left corner of the cell corresponds to the current
        position. The text can be aligned, centered or justified. After the call, the
        current position moves to the requested new position. It is possible to put a
        link on the text.

        If automatic page breaking is enabled and the cell goes beyond the limit, a
        page break is performed before outputting.

        Args:
            text_line (TextLine instance): Contains the (possibly empty) tuple of
                fragments to render.
            h (float): Cell height. Default value: None, meaning an height equal
                to the current font size.
            border: Indicates if borders must be drawn around the cell.
                The value can be either a number (`0`: no border ; `1`: frame)
                or a string containing some or all of the following characters
                (in any order):
                `L`: left ; `T`: top ; `R`: right ; `B`: bottom. Default value: 0.
            new_x (fpdf.enums.XPos): New current position in x after the call.
            new_y (fpdf.enums.YPos): New current position in y after the call.
            fill (bool): Indicates if the cell background must be painted (`True`)
                or transparent (`False`). Default value: False.
            link (str): optional link to add on the cell, internal
                (identifier returned by `FPDF.add_link`) or external URL.
            center (bool): center the cell horizontally on the page.
            padding (Padding or None): optional padding to apply to the cell content.
                If padding for left and right is non-zero then c_margin is ignored.
            prevent_font_change (bool): ensure no font settings (family / size / style)
                change during this call.

        Returns: a boolean indicating if page break was triggered
        r  r  r   r   ZLTRBNr   )Z
initial_cszA'text_line' must have fragments if 'text_line.text_width' is Noner   rM  fr  r  r  z re Sr  r  r  TRg        FrF  g      ?g333333?r  r   Tr   z Tzz TcrD  rE  )rI  z Tsr  r  )r   r   r1  r4  rS  ETr  z Qg       @)`r   r   r   r   r$   r   rk  
issupersetry   r>  r   r@  r  	enumerate	fragmentsr  r  r/  r1  r2  r   r   r3  r  r0   XZget_ordered_fragmentsrz  _perform_page_break_if_need_ber   r4  r   r?  bottomr  r  r  r4   ZLINEr   r   r   r   r   r   r   r  Cr  r  r_   r   r   Zadd_text_substitutiongraphics_stater  r   r   r   r  r  r  r>   rH  r  r  rK  liftrC   r   r   Zrender_pdf_text
characterscountr   r  r   r  rS  r!  rv  r   rE   r  STARTZENDWCONTZCENTERr  ZRMARGINrF   r  ZTMARGINr   ZBMARGINr5  )0r   r  r4  r  r  r  r  rS  r  r  r  Z
l_c_marginZ
r_c_marginZstyled_txt_widthr  r  Zunscaled_widthr1  Zmax_font_sizer  page_break_triggeredrJ  r   r>  r@  r?  r  opZs_startZs_widthZ
current_wsZfrag_wsZcurrent_liftZcurrent_char_vposr   Zcurrent_font_size_ptZcurrent_font_styleZcurrent_text_modeZcurrent_font_stretchingZcurrent_char_spacingZfill_color_changedZlast_used_colorZdxZword_spacingr  Zr_textZ
frag_widthr  r   r   r   r    s   /





8
2
*
*
*
*:
  



	



zFPDF._render_styled_text_linec                 C   s~   | j | j || j | j| | j || | j | j| | j || j | j| | | j || | j | j| | | j g d S r  )r  r   extendr   r4  r   r   r   r1  r4  r   r   r   r  
  s    zFPDF._add_quad_pointsc           	      C   s   | j s| ||S | j d r&| j d nt|}t||d}| }|j| j d< g }|D ]"\}}|| j d< || ||7 }qVt|S )zh "
        Break the text into bidirectional segments and preload font styles for each fragment
        rQ  )r  base_directionrU  rT  )rV  r  r"   r!   Zget_bidi_fragmentsr  r  )	r   r  r  rU  Z	paragraphZdirectional_segmentsr  Z	bidi_textZbidi_directionr   r   r   r    s    
z FPDF._preload_bidirectional_textc                 C   s   |s
t  S | j}| jr|d7 }| jr,|d7 }t | ||}|r| j}d| _tdd |D rj| jdd tdd |D r| jd	d td
d |D r| jdd tdd |D r| jdd |D ]}| j|j	|j  |_
q| j|d || _|S )aS  
        When Markdown styling is enabled, we require secondary fonts
        to ender text in bold & italics.
        This function ensure that those fonts are available.
        It needs to perform Markdown parsing,
        so we return the resulting `styled_txt_frags` tuple
        to avoid repeating this processing later on.
        r  r  r   c                 s   s   | ]}|j d kV  qdS )rM  Nr   r  r  r   r   r   r  D  s     z,FPDF._preload_font_styles.<locals>.<genexpr>rM  r  c                 s   s   | ]}|j d kV  qdS )rN  Nr  r  r   r   r   r  G  s     rN  c                 s   s   | ]}|j d kV  qdS r1  r  r  r   r   r   r  J  s     r2  c                 s   s   | ]}|j d kV  qdS )r   Nr  r  r   r   r   r  M  s     r   )r  r   r   r   _parse_charsr   r6  r  r   r   r   )r   r  r  prev_font_styler  r   r  r   r   r   r  .  s0    	zFPDF._preload_font_stylesc                    s\   t | fddjD }|s(dS tfdd|D d}|rJ|S jrTdS |d S )z
        Returns which fallback font has the requested glyph.
        This method can be overridden to provide more control than the `select_mode` parameter
        of `FPDF.set_fallback_fonts()` provides.
        c                    s$   g | ]}t  j| jkr|qS r   )ordr   cmap)r  Zfont_id)charr   r   r   
<listcomp>^  s   z*FPDF.get_fallback_font.<locals>.<listcomp>Nc                 3   s"   | ]}j | j kr|V  qd S r  )r   r  )r  r   )r  r   r   r   r  f  s      z)FPDF.get_fallback_font.<locals>.<genexpr>r   )rA   r  r   nextr   )r   r  r  Zfonts_with_charZfont_with_matching_emphasisr   )r  r  r   r   get_fallback_fontW  s    
zFPDF.get_fallback_font)r  r  r  c                 #   s~  |sj sjsjrjt|jD ]>\}}|dkrLtj jV  |r&t| jV  q&dS t| jV  dS g dj	kdj	kt
jt
jf\d d fdd}jrjj}ng }d}|rl|dd jjjjfk}|d }	t|d }
|
tjtjfkrRrNrN| V  |
jr|dtj jkrr| V   }rdndrdnd |d	< |d
< |d< tj|jV  |tjd }q|r|r҈r d |	krt|dk s|d |	kr|dkr<d|d d   n|d dkr҈r\| V  |dd jkrv |dd jkr |dd jkr |dd jkrĈ |dd }q|d jkr|d nd}j|}|r| \}}}r| V   }j|d< jr@j|d< zt|}j |d}W n t!k
rn   Y nX tt"||j|dV  qjr8|d dkr8t#|d |kr8rdndrdnd }$|d |}|r8| kr
%|d  |dd }qr| V  | %|d  |dd }q rPrL| V  d %|d  |dd }qrz| V  dS )zSplit text into fragmentsr   NrM  rN  c                     s     } rdndrdnd | d< | d< | d<  r~ddd  D | d	< dd
d  D | d< j  | d< d  d t| j}g |S )NrM  r   rN  r   r   r   c                 s   s   | ]}|  r|V  qd S r  )islowerr  r  r   r   r   r    s     z2FPDF._parse_chars.<locals>.frag.<locals>.<genexpr>r   c                 s   s   | ]}|  r|V  qd S r  )isupperr  r   r   r   r    s     r   )_get_current_graphics_staterv  r   r\   r   )gstatefragmentZcurrent_fallback_fontZcurrent_text_scriptZin_boldZ
in_italicsZin_strikethroughZin_underliner   Ztxt_fragr   r   r    s.    



zFPDF._parse_chars.<locals>.fragr   r   r   r   r   r<  r  r   r   r  )rS  
)&rV  r   rz  r  splitr_   r  r   r\   r   r   r   r   r!  r   r  MARKDOWN_BOLD_MARKERMARKDOWN_ITALICS_MARKERMARKDOWN_STRIKETHROUGH_MARKERMARKDOWN_UNDERLINE_MARKERrw   rv   ZCOMMONUNKNOWNr7  MARKDOWN_ESCAPE_CHARACTERMARKDOWN_LINK_REGEXr  groupsMARKDOWN_LINK_UNDERLINEMARKDOWN_LINK_COLORr   rT  r/  r  r  r  r  )r   r  r  seqZfragment_textr  Zfont_glyphsZnum_escape_charsZ	is_markerZhalf_markerZtext_scriptr  Zis_linkZ	link_text	link_destr   r  rO  r   r  r   r  o  s   
  






(
zFPDF._parse_charsc                 C   s   | j | | jko| j o| jS )a8  
        Let you know if adding an element will trigger a page break,
        based on its height and the current ordinate (`y` position).

        Args:
            height (float): height of the section that would be added, e.g. a cell

        Returns: a boolean indicating if a page break would occur
        )r   rC  r   r  )r   rY  r   r   r   will_page_break  s
    zFPDF.will_page_breakc                 C   s2   |  |r.td| j| j|| j |   dS dS )Nz;Page break on page %d at y=%d for element of height %d > %dTF)r   LOGGERdebugr   r   rC  _perform_page_breakr   r4  r   r   r   r  ,  s    
z#FPDF._perform_page_break_if_need_bec                 C   s   | j r| jrd S | j}g }|  rB||   |   |   qd| _| 	  | j
dd |   t|D ] }| 	  d|d< | jf | ql|| _d S )NFT)r  r   )r  r   r   Z!_is_current_graphics_state_nestedr  r  r  r  r   r  r  reversedr  )r   r   Zgs_stackZprev_gsr   r   r   r  9  s"    
zFPDF._perform_page_breakc                 C   s   | j | jkS r  )r8  r   r   r   r   r   r  S  s    zFPDF._has_next_pagec              
   c   s   t | jtjsd V  d S dd | _| j| j| j| jf\}}}}t| j	| j j
}|   z
d V  W 5 |   t|d | jd D ]}| j	|= q|| _|| j	| j _
| || | `X d S )Nc                  _   s   d S r  r   )r   r   r   r   r   <lambda>]      z'FPDF._disable_writing.<locals>.<lambda>r   )r   r  types
MethodTyper   r8  r   r   ro   r   r_  r  r  r	  set_xy)r   	prev_pageZprev_pages_countprev_xprev_yr_  pr   r   r   _disable_writingV  s(    


zFPDF._disable_writing)wrapmodec           1      C   sZ  t |}t|}|r*tjdtt d |s2|r|  H | j	||||||||	|
|||||dd|rjt
jn|||dW  5 Q R  S Q R X | jstdt|tst|trtdt|}t|}|	dkrh|	dkrtj}tj}nX|	d	k rtj}tj}n@|	d
krtj}tj}n(|	dkr.tj}tj}ntd|	 dtjd|	 d|j d|j dtt d t|}d}|dkr| j}|dkr| j| j | j }| j| j }}||j |j   }}g }|j s|!| j" |js|!| j" |tj#kr|  j|j 7  _|  j|j$7  _|rT|tj#kr8| jd
 n| j%| j&| d
  | _| j}| '|}|(dd}| j)r~| *||n
| +||}| j,}| j-}| j.}d}g }t/||||||d} | 0 }!|!dk	r|!|! | 0 }!q|st1ddd|||ddg}|
dkst2|d	kr|}"n
t3||
}"|p.|}#d}t4|D ]p\}$}!| 5||j6 rld}|  j|j$7  _|#r:|$dks|r:| j|j$ }%|j6| j7 }&t8| j9|% |& |" }'t3|'t2||$ }(t:||$|"  |(|" })| j|tj#kr|d
 nd }*t;| |*|j  | j|j$ |*| |j | j|) |j6 ||r4| j<nd |$t2|d	 k}+| j=|!|"|+r\|ntj|+rj|ntjdd|t d|jd|j |d	 ||"7 }|+s<|tj#kr<|| _q<||k r|tjkr|  j|| 7  _|}|r|tjkr| j}|d },|,r$|,j>r$|tj?tjfkr$| @  |tjkr8|| _n|tjkrT|  j|j67  _|rl|| _-|| _,|| _.|tjkr|  j|j7  _n|tjkr|  j|j 8  _t
|}d}-|t
jA@ r|-|f7 }-|t
j@ rg }.|D ]4}!g }/|!jBD ]}0|/C|0jD q|.!dE|/ q|-|.f7 }-|t
jF@ r@|-||j$ |j6 f7 }-t2|-d	krV|-d S |-S )ab  
        This method allows printing text with line breaks. They can be automatic
        (breaking at the most recent space or soft-hyphen character) as soon as the text
        reaches the right border of the cell, or explicit (via the `\n` character).
        As many cells as necessary are stacked, one below the other.
        Text can be aligned, centered or justified. The cell block can be framed and
        the background painted. A cell has an horizontal padding, on the left & right sides,
        defined by the.c_margin property.

        Args:
            w (float): cell width. If 0, they extend up to the right margin of the page.
            h (float): height of a single line of text.  Default value: None, meaning to use the current font size.
            text (str): string to print.
            border: Indicates if borders must be drawn around the cell.
                The value can be either a number (`0`: no border ; `1`: frame)
                or a string containing some or all of the following characters
                (in any order):
                `L`: left ; `T`: top ; `R`: right ; `B`: bottom. Default value: 0.
            align (fpdf.enums.Align, str): Set text alignment inside the cell.
                Possible values are:
                `J`: justify (default value); `L` or empty string: left align;
                `C`: center; `X`: center around current x position; `R`: right align
            fill (bool): Indicates if the cell background must be painted (`True`)
                or transparent (`False`). Default value: False.
            split_only (bool): **DEPRECATED since 2.7.4**:
                Use `dry_run=True` and `output=("LINES",)` instead.
            link (str): optional link to add on the cell, internal
                (identifier returned by `add_link`) or external URL.
            new_x (fpdf.enums.XPos, str): New current position in x after the call. Default: RIGHT
            new_y (fpdf.enums.YPos, str): New current position in y after the call. Default: NEXT
            ln (int): **DEPRECATED since 2.5.1**: Use `new_x` and `new_y` instead.
            max_line_height (float): optional maximum height of each sub-cell generated
            markdown (bool): enable minimal markdown-like markup to render part
                of text as bold / italics / strikethrough / underlined.
                Supports `\` as escape character. Default to False.
            print_sh (bool): Treat a soft-hyphen (\u00ad) as a normal printable
                character, instead of a line breaking opportunity. Default value: False
            wrapmode (fpdf.enums.WrapMode): "WORD" for word based line wrapping (default),
                "CHAR" for character based line wrapping.
            dry_run (bool): if `True`, does not output anything in the document.
                Can be useful when combined with `output`.
            output (fpdf.enums.MethodReturnValue): defines what this method returns.
                If several enum values are joined, the result will be a tuple.
            txt (str): [**DEPRECATED since v2.7.6**] string to print.
            center (bool): center the cell horizontally on the page.
            padding (float or Sequence): padding to apply around the text. Default value: 0.
                When one value is specified, it applies the same padding to all four sides.
                When two values are specified, the first padding applies to the top and bottom, the second to
                the left and right. When three values are specified, the first padding applies to the top,
                the second to the right and left, the third to the bottom. When four values are specified,
                the paddings apply to the top, right, bottom, and left in that order (clockwise)
                If padding for left or right ends up being non-zero then respective c_margin is ignored.

        Center overrides values for horizontal padding

        Using `new_x=XPos.RIGHT, new_y=XPos.TOP, maximum height=pdf.font_size` is
        useful to build tables with multiline text in cells.

        Returns: a single value or a tuple, depending on the `output` parameter value
        zcThe parameter "split_only" is deprecated since v2.7.4. Use instead dry_run=True and output="LINES".r   F)r1  r4  r  r  r  r  rS  r  max_line_heightr  print_shr  r  r  r   r   outputr  r  rw  r  r   r   r   r   r  r  z"), must be an int between 0 and 3.r  r  r  r4  Nr   )r  r  r  r  T)r4  r  r  r  r  rS  r  r  r<  r   )Gry   newrD   r  r   r   r   r$   r  
multi_cellr8   LINESr   rH   r   r   r/  rE   rF   r  r  r  r  r  rg  r0   rz  r1  r2  r   r   r@  r>  r  r   r  r?  r   r3  r  rB  rV  r  r  r   r   r   r]   get_liner^   r7  r  r  r  r  r5  r   r4  r  rr   r   r  r  ZLASTr  
PAGE_BREAKr  r  r  rv  ZHEIGHT)1r   r1  r4  r  r  r  r  r   rS  r  r  r  r  r  r  r  r   r  r  r  r  r  r  Zmaximum_allowed_widthZclearance_marginsnormalized_stringstyled_text_fragmentsZprev_current_fontr  Zprev_underlineZtotal_height
text_linesmulti_line_breakr  line_heightZbox_requiredtext_line_indexZtop_gapZ
bottom_gapZlines_before_breakZ	num_linesZ
box_heightr   Zis_last_line	last_lineZreturn_valueZoutput_linesr  r  r   r   r   r  s  s   U












(






 
	

 



zFPDF.multi_cell)r4  r  rS  r  r  c              
      sH  t |}| jstdt|tr*td|dkr8| j}d}| |	dd}| j
r`| |dn
| |d}g }	t| fdd| j| jf||d	}
| j| j | j }| |
 }| j| j | j }| |dk	r|	| |
 }q|	sdS t|	D ]@\}}|d
kr|   | j||d
tjtjd|d}|p0|}q|jrD|   |S )a  
        Prints text from the current position.
        When the right margin is reached, a line break occurs at the most recent
        space or soft-hyphen character, and text continues from the left margin.
        A manual break happens any time the \n character is met,
        Upon method exit, the current position is left just at the end of the text.

        Args:
            h (float): line height. Default value: None, meaning to use the current font size.
            text (str): text content
            link (str): optional link to add on the text, internal
                (identifier returned by `FPDF.add_link`) or external URL.
            print_sh (bool): Treat a soft-hyphen (\u00ad) as a normal printable
                character, instead of a line breaking opportunity. Default value: False
            wrapmode (fpdf.enums.WrapMode): "WORD" for word based line wrapping (default),
                "CHAR" for character based line wrapping.
            txt (str): [**DEPRECATED since v2.7.6**] text content
        rw  zbParameter 'h' must be a number, not a string. You can omit it by passing string content with text=NFr  r   c                    s    S r  r   )r4  r  r   r   r    r  zFPDF.write.<locals>.<lambda>)r  r  r   )r4  r  r  r  r  rS  )rD   r  r   rH   r   r   r/  rz  r  rB  rV  r  r  r]   r   r1  r   r2  r  r   r  r  r  r  rE   r  rF   r  r  )r   r4  r  rS  r  r  r  r  r  r  r  Zfirst_widthr  Z
full_widthr  r  r   r!  r   write  sb    







	z
FPDF.write
   r  r  imgimg_fill_widthncolsgutterbalance
text_alignr  r   r2  r  r  skip_leading_spacesc                 C   s$   t | |||||||||	|
|||dS )a  Establish a layout with multiple columns to fill with text.
        Args:
            text (str, optional): A first piece of text to insert.
            ncols (int, optional): the number of columns to create. (Default: 1).
            gutter (float, optional): The distance between the columns. (Default: 10).
            balance: (bool, optional): Specify whether multiple columns should end at approximately
                the same height, if they don't fill the page. (Default: False)
            text_align (Align or str, optional): The alignment of the text within the region.
                (Default: "LEFT")
            line_height (float, optional): A multiplier relative to the font size changing the
                vertical space occupied by a line of text. (Default: 1.0).
            l_margin (float, optional): Override the current left page margin.
            r_margin (float, optional): Override the current right page margin.
            print_sh (bool, optional): Treat a soft-hyphen (\u00ad) as a printable character,
                instead of a line breaking opportunity. (Default: False)
            wrapmode (fpdf.enums.WrapMode, optional): "WORD" for word based line wrapping,
                "CHAR" for character based line wrapping. (Default: "WORD")
            skip_leading_spaces (bool, optional): On each line, any space characters at the
                beginning will be skipped if True. (Default: False)
        r$  )rt   )r   r  r%  r&  r'  r(  r)  r*  r  r   r2  r  r  r+  r   r   r   text_columns  s     %zFPDF.text_columnsc                 C   sr   |rt jdtt d t| j||
\}}}t|trR| ||||||||||	|S | 	||||||||||	|
|S )a  
        Put an image on the page.

        The size of the image on the page can be specified in different ways:
        * explicit width and height (expressed in user units)
        * one explicit dimension, the other being calculated automatically
          in order to keep the original proportions
        * no explicit dimension, in which case the image is put at 72 dpi.
        * explicit width and height (expressed in user units) and `keep_aspect_ratio=True`

        **Remarks**:
        * if an image is used several times, only one copy is embedded in the file.
        * when using an animated GIF, only the first frame is used.

        Args:
            name: either a string representing a file path to an image, an URL to an image,
                bytes, an io.BytesIO, or a instance of `PIL.Image.Image`
            x (float, fpdf.enums.Align): optional horizontal position where to put the image on the page.
                If not specified or equal to None, the current abscissa is used.
                `fpdf.enums.Align.C` can also be passed to center the image horizontally;
                and `fpdf.enums.Align.R` to place it along the right page margin
            y (float): optional vertical position where to put the image on the page.
                If not specified or equal to None, the current ordinate is used.
                After the call, the current ordinate is moved to the bottom of the image
            w (float): optional width of the image. If not specified or equal to zero,
                it is automatically calculated from the image size.
                Pass `pdf.epw` to scale horizontally to the full page width.
            h (float): optional height of the image. If not specified or equal to zero,
                it is automatically calculated from the image size.
                Pass `pdf.eph` to scale horizontally to the full page height.
            type (str): [**DEPRECATED since 2.2.0**] unused, will be removed in a later version.
            link (str): optional link to add on the image, internal
                (identifier returned by `FPDF.add_link`) or external URL.
            title (str): optional. Currently, never seem rendered by PDF readers.
            alt_text (str): optional alternative text describing the image,
                for accessibility purposes. Displayed by some PDF readers on hover.
            dims (Tuple[float]): optional dimensions as a tuple (width, height) to resize the image
                before storing it in the PDF. Note that those are the **intrinsic** image dimensions,
                but the image will still be rendered on the page with the width (`w`) and height (`h`)
                provided as parameters. Note also that the `.oversized_images` attribute of FPDF
                provides an automated way to auto-adjust those intrinsic image dimensions.
            keep_aspect_ratio (bool): ensure the image fits in the rectangle defined by `x`, `y`, `w` & `h`
                while preserving its original aspect ratio. Defaults to False.
                Only meaningful if both `w` & `h` are provided.

        If `y` is provided, this method will not trigger any page break;
        otherwise, auto page break detection will be performed.

        Returns: an instance of a subclass of `ImageInfo`.
        zL"type" parameter is deprecated since v2.2.0, unused and will soon be removedr   )
r   r   r   r$   rZ   r   r   rV   _vector_image_raster_image)r   rg  r   r   r1  r4  r  rS  r   r]  dimskeep_aspect_ratior%  r,  r   r   r   r  L  sF    A	
          z
FPDF.image)r,  c              
   C   s\  d|kr|  d |j||| jd\}}|d krN| | | j}|  j|7  _|d kr\| j}t|tsx| |||||}|r|	||||\}}}}| j
r|d dkr|s| j|||||| jd}t||||||| j| jd}|	s|
r| j|	|
d | | W 5 Q R X n
| | |r0| ||||| | jtj|d | j tf |||d	S )
NZsmaskr-  )scaleusagesr   )r1  Zpdf_height_to_flipr   r]  r  Zrendered_widthZrendered_height)r  Zsize_in_document_unitsr   r  r   r   r   r	   
x_by_alignscale_inside_boxr   _downscale_imagerf   r4  _marked_sequencer  rS  r  r  r>   r  r   rU   )r   rg  r%  r,  r   r   r1  r4  rS  r   r]  r/  r0  Zstream_contentr   r   r   r.    sB    


       

zFPDF._raster_imagec                 C   sz   |r| dd||\}}}}t|}|tjkr>| j| d S |tjkrX| j| | j S |tjkrh| jS t	d| d S )Nr   r   z*Unsupported 'x' value passed to .image(): )
r6  r0   r  r  r1  r  r2  r  r   r/  )r   r   r1  r4  Zimg_infor0  _r   r   r   r5    s    



zFPDF.x_by_align)svgr,  c              
   C   sn  |j s4|jr4|jr4tjdt d dd|j|jf|_ |dkr|dkr|jr|jrt|jtrl|j| j d n|j}t|jtr|j| j	 d n|j}n6|j r|j \}}}}n t|t
rdn|}t| dnr|dks|dkr@|jr|jr|j|j }}n |j r|j \}}}}ntd|dkr4|| | }n|| | }|d krh| | | j}|  j|7  _|d krx| j}|r|||||\}}}}t|ts| |||||}|jd||d	d
\}}}|jt|| |_| j| j }}zL| dd |	s|
r.| j|	|
d | | W 5 Q R X n
| | W 5 | || X |rb| ||||| t||dS )NzI<svg> has no "viewBox", using its "width" & "height" as default "viewBox"r   r   r   z<svg>zT has no "viewBox" nor "height" / "width": w= and h= must be provided to FPDF.image()zY<svg> has no "viewBox" nor "height" / "width": w= and h= must be provided to FPDF.image()r   T)r1  r  rY  Zignore_svg_top_attrsr3  r4  )viewboxr  rY  r   r   r$   r   rl   r3  r6  rm  r/  r  r   r   r6  r	   r5  Ztransform_to_rect_viewportZ	transformr,   translationr
  r8  r  rS  rV   )r   rg  r:  r,  r   r   r1  r4  rS  r   r]  r0  r9  Zsvg_idZ	svg_widthZ
svg_heightr  Zold_xZold_yr   r   r   r-    sz    





   zFPDF._vector_imagec              	   C   s  | j j}|| ||  }}	d| }
|d || j kr|d |	| j krt|d | |d |	 | j }| j drtd||d |d ||	| np| j dkrt	|| j t	|	| j f}|d  d8  < |d d	kr*| j
j}| D ]0\\}}}|tjkr|d
 |kr||d
  q||
}|r|}|d |d  |d	 |d  k r|t||ptt|| j j| td|
|d
 | |d  d7  < nTtt||pt|| j j|}t|d |d
< d|d< |||
< td|
||d
  ntd| j |S )Nzlowres-r1  r4  r   zOVERSIZED: Image %s with size %.1fx%.1fpx is rendered at size %.1fx%.1fpt. Set pdf.oversized_images = 'DOWNSCALE' to reduce embedded image size by a factor %.1fZ	downscaler2  r   r   r  z>OVERSIZED: Updated low-res image with name=%s id=%d to dims=%szAOVERSIZED: Generated new low-res image with name=%s dims=%s id=%dz/Invalid value for attribute .oversized_images: )r   imagesr   r  r   r   
startswithr  warningroundr  resources_per_pager  r>   r  remover   updaterX   rY   rw  r  rU   r7  r/  )r   rg  r%  r,  r1  r4  r1  r=  Zwidth_in_ptZheight_in_ptZlowres_nameZfactorr/  rA  r9  ZrtyperesourceZlowres_infor   r   r   r7  B  s    

"
zFPDF._downscale_imagec                 C   s    t jdtt d t| j||S )z
        Read an image and load it into memory.

        .. deprecated:: 2.7.7
            Use `fpdf.image_parsing.preload_image` instead.
        zFPDF.preload_image() is deprecated since v2.7.7 and will be removed in a future release. Use `fpdf.image_parsing.preload_image` instead.r   )r   r   r   r$   rZ   r   )r   rg  r/  r   r   r   rZ     s    	zFPDF.preload_imagec                 k   sb   | j | j}| jf d|d|}| j}| d| d |V  | j|krTtd| d dS )
        Can receive as named arguments any of the entries described in section 14.7.2 'Structure Hierarchy'
        of the PDF spec: iD, a, c, r, lang, e, actualText
        z/Figure)r\  mcidz/P <</MCID z>> BDCz-A page jump occurred inside a marked sequenceZEMCN)r   Znext_mcid_for_pager   r`  r  rH   )r   r   rF  struct_elemr   r   r   r   r8    s     
zFPDF._marked_sequencec                 K   s8   | j jf d| ji|\}}|| j| j _| d |S )rE  rU  r-  )r   Zadd_marked_contentr   r   Zstruct_parentsr  )r   r   rG  Zspidr   r   r   r`    s    


zFPDF._add_marked_contentc                 C   sL   | j | _|dk	r |  j|7  _n(| jr8|  j| j7  _n|  j| j7  _dS )a  
        Line Feed.
        The current abscissa goes back to the left margin and the ordinate increases by
        the amount passed as parameter.

        Args:
            h (float): The height of the break.
                By default, the value equals the height of the last printed text line
                (except when written by `.text()`). If no text has been written yet to
                the document, then the current font height is used.
        N)r   r   r   r   rz  r  r   r   r   r    s    zFPDF.lnc                 C   s   | j S )z-Returns the abscissa of the current position.)r   r   r   r   r   get_x  s    z
FPDF.get_xc                 C   s   |dkr|n| j | | _dS )z
        Defines the abscissa of the current position.
        If the value provided is negative, it is relative to the right of the page.

        Args:
            x (float): the new current abscissa
        r   N)r1  r   )r   r   r   r   r   set_x  s    z
FPDF.set_xc                 C   s   | j rtd| jS )z-Returns the ordinate of the current position.z?Using get_y() inside an unbreakable() code block is error-prone)r   rH   r   r   r   r   r   get_y  s
    z
FPDF.get_yc                 C   s$   | j | _|dkr|n| j| | _dS )z
        Moves the current abscissa back to the left margin and sets the ordinate.
        If the value provided is negative, it is relative to the bottom of the page.

        Args:
            y (float): the new current ordinate
        r   N)r   r   r4  r   )r   r   r   r   r   set_y  s    z
FPDF.set_yc                 C   s   |  | | | dS )a,  
        Defines the abscissa and ordinate of the current position.
        If the values provided are negative, they are relative respectively to the right and bottom of the page.

        Args:
            x (float): the new current abscissa
            y (float): the new current ordinate
        N)rK  rI  )r   r   r   r   r   r   r
    s    	
zFPDF.set_xyc              
   C   sh   | j sd| jrdz|| jdW S  tk
rb } z$t|j||j | j| j d|W 5 d}~X Y nX |S )z7Check that text input is in the correct format/encodingr   )Z
text_index	characterZ	font_nameN)	r!  r   encodedecodeUnicodeEncodeErrorrJ   startr   r   )r   r  errorr   r   r   r    s    
zFPDF.normalize_textsha256c	                 C   sX   t stdt|d}	t|	 |\}
}}W 5 Q R X | j|
||||||||d	 dS )aE  
        Args:
            pkcs_filepath (str): file path to a .pfx or .p12 PKCS12,
                in the binary format described by RFC 7292
            password (bytes-like): the password to use to decrypt the data.
                `None` if the PKCS12 is not encrypted.
            hashalgo (str): hashing algorithm used, passed to `hashlib.new`
            contact_info (str): optional information provided by the signer to enable
                a recipient to contact the signer to verify the signature
            location (str): optional CPU host name or physical location of the signing
            signing_time (datetime): optional time of signing
            reason (str): optional signing reason
            flags (Tuple[fpdf.enums.AnnotationFlag], Tuple[str]): optional list of flags defining annotation properties
        Pendesive.signer not available - PDF cannot be signed - Try: pip install endesivera  )	r  certextra_certshashalgocontact_infolocationsigning_timereasonrr  N)r   EnvironmentErrorre  r   load_key_and_certificatesrf  sign)r   Zpkcs_filepathpasswordrV  rW  rX  rY  rZ  rr  Z	pkcs_filer  rT  rU  r   r   r   sign_pkcs12  s(     zFPDF.sign_pkcs12r   c
                 C   s   t std| jrtd|| _|| _|| _|| _|p:| j| _t	dddddd|	dt
||t| j|dd	}
| j| j j|
 d	S )
a  
        Args:
            key: certificate private key
            cert (cryptography.x509.Certificate): certificate
            extra_certs (list[cryptography.x509.Certificate]): list of additional PKCS12 certificates
            hashalgo (str): hashing algorithm used, passed to `hashlib.new`
            contact_info (str): optional information provided by the signer to enable
                a recipient to contact the signer to verify the signature
            location (str): optional CPU host name or physical location of the signing
            signing_time (datetime): optional time of signing
            reason (str): optional signing reason
            flags (Tuple[fpdf.enums.AnnotationFlag], Tuple[str]): optional list of flags defining annotation properties
        rS  z).sign* methods should be called only onceZWidgetZSigr   	signature)rW  rX  r  rZ  )Z
field_typer   r   r  rY  rr  r   r.  N)r   r[  r   rH   Z
_sign_certZ_sign_extra_certsZ_sign_hashalgor   Z
_sign_timer   rj   rp   r   r   r_  r  )r   r  rT  rU  rV  rW  rX  rY  rZ  rr  rs  r   r   r   r]  ?  s8    z	FPDF.signc                    s4   j } j j }}|j|j  _ _d _ |j j j |	  j
 d _|j|j d } j|kr js j|krdnd}d| d}|d j d	|j d
7 }t| jr"    fddt jD }tt|}i }t|jd  jt| d D ]d}	|	 jkr,| j|	 |d }
 j|	< |	||
 < |
|	 |jdkr
|	|
 _q
t|dkstdt|  j
D ]B}||j}|d k	r|jj |d|_||_|j!r||j!_"q j#j$}t%t&}|' D ]&\\}}}||||f}|||< q| j#_$||  _ _d S )NTFr   manyfewzKThe rendering function passed to FPDF.insert_toc_placeholder triggered too z page breaks: zToC ended on page z' while it was expected to span exactly z pagesc                    s   g | ]} j t j qS r   )r   popr7  )r  r9  r   r   r   r    s    z2FPDF._insert_table_of_contents.<locals>.<listcomp>r   z#new_pages: r  )(r   r   r   r   r   r   r   r   r   r   r   r   r   rH   r   r  r	  r  r  r8  r7  r  rc  r  Z	set_indexr   r  str^  r   rU  r[  rB  rG  Z_page_numberr  rA  r   rk  r  )r   Ztocpr  r  Zexpected_final_pageZtoo	error_msgZ	new_pagesZindices_remapZ
page_indexr   sectionZ	new_indexrA  Znew_resources_per_pagerU  Zresource_typerD  r  r   r   r   _insert_table_of_contentsx  s\    
 
 

zFPDF._insert_table_of_contentsc                 C   s   dS )aA  
        This method can be overridden in inherited classes
        in order to define a custom file identifier.
        Its output must have the format "<hex_string1><hex_string2>".
        If this method returns a falsy value (None, empty string),
        no /ID will be inserted in the generated PDF document.
        r<  r   r   r   r   r   file_id  s    zFPDF.file_idc                 C   sT   t jddd}|| | jr6|| jdd |  }d| d| dS )	Nmd5F)Zusedforsecurityz%Y%m%d%H%M%Sutf8<z><>)hashlibr  rC  r   strftimerM  	hexdigestr  )r   r  Zid_hashZhash_hexr   r   r   _default_file_id  s    	
zFPDF._default_file_idc                 C   sh   |dkr| j }|| j dd| j| |jd | j  | j dd|| j dd|j d | j ddS )zr
        Draw an horizontal line under some text,
        starting from (x, y) with a length equal to 'w'
        Nr  r     re f)r   r   r4  Zuprz  utr   r   r   r   r1  r   r   r   r   r    s    XzFPDF._do_underlinec                 C   sh   |dkr| j }|| j dd| j| |jd | j  | j dd|| j dd|j d | j ddS )zt
        Draw an horizontal line through some text,
        starting from (x, y) with a length equal to 'w'
        Nr  r  rq  rr  )r   r   r4  sprz  ssr   rt  r   r   r   r    s    XzFPDF._do_strikethroughc                 C   s`   | j rtdt|ts4t|ts*t|}|d}| jsBtd| j| j  j|d 7  _d S )NzGContent cannot be added on a finalized document, after calling output()latin1r      
)	r  rH   r   rm  r   rM  r   r   r  )r   r  r   r   r   r    s    


z	FPDF._outc                 C   s"  |d }|}dddddddd	d
dddd}|}	t |	d dkrHd|	 }	d|	  d}	tdt |	dD ]}
|	|
 }|	|
d  }||krtd| d||krtd| dddd t|| || D }t|D ]@\}}|dkr|n|}|d dkr| ||||d ||7 }qqhdS )z/Barcode I2of5 (numeric), adds a 0 if odd lengthr  ZnnwwnZwnnnwZnwnnwZwwnnnZnnwnwZwnwnnZnwwnnZnnnwwZwnnwnZnwnwnnnZwn)0123456789AZr   r   rz  ZAAZZAr   zChar "z" invalid for I25:z" invalid for I25: r   c                 s   s   | ]\}}| | V  qd S r  r   )r  cbcsr   r   r   r    s    z'FPDF.interleaved2of5.<locals>.<genexpr>r(  r  N)r7  r   r	  RuntimeErrorrv  zipr  r  )r   r  r   r   r1  r4  ZnarrowZwideZbar_charcoder  Zchar_barZ
char_spacer  Z	bar_indexr  r   r   r   r   interleaved2of5  sD    

zFPDF.interleaved2of5      ?r  c              -   C   s
  ||d d}| dr"|ds2tjdt 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,d-d.d/d0d1d2,}| D ]l}||krtd3| d4t|| D ]6\}	}
|	d5 d6kr| ||||
 |d7 |||
 7 }q||d8 7 }qd9S ):zBarcode 3of9r  )r1  r(  *zpCode 39 input must start and end with a '*' character to be valid. This method does not insert it automatically.r   Z	nnnwwnwnnZ	wnnwnnnnwZ	nnwwnnnnwZ	wnwwnnnnnZ	nnnwwnnnwZ	wnnwwnnnnZ	nnwwwnnnnZ	nnnwnnwnwZ	wnnwnnwnnZ	nnwwnnwnnZ	wnnnnwnnwZ	nnwnnwnnwZ	wnwnnwnnnZ	nnnnwwnnwZ	wnnnwwnnnZ	nnwnwwnnnZ	nnnnnwwnwZ	wnnnnwwnnZ	nnwnnwwnnZ	nnnnwwwnnZ	wnnnnnnwwZ	nnwnnnnwwZ	wnwnnnnwnZ	nnnnwnnwwZ	wnnnwnnwnZ	nnwnwnnwnZ	nnnnnnwwwZ	wnnnnnwwnZ	nnwnnnwwnZ	nnnnwnwwnZ	wwnnnnnnwZ	nwwnnnnnwZ	wwwnnnnnnZ	nwnnwnnnwZ	wwnnwnnnnZ	nwwnwnnnnZ	nwnnnnwnwZ	wwnnnnwnnZ	nwwnnnwnnZ	nwnnwnwnnZ	nwnwnwnnnZ	nwnwnnnwnZ	nwnnnwnwnZ	nnnwnwnwn),rz  r{  r|  r}  r~  r  r  r  r  r  r  rM  r  r  Er  GHrN  r  Kr  MNOPr  r  r  r  r  VWr  Yr  -r4  r  r  $/+%zInvalid char "z" for Code39r   r   r  r(  N)	r>  endswithr   r   r$   r  r  r  r  )r   r  r   r   r1  r4  Zdimcharsr  r  dr   r   r   code39-  sv    0zFPDF.code39c                 c   sb   |  d|| j dd| j| | | j dd|| j dd|| j dd	 dV  |  d dS )a}  
        Context manager that defines a rectangular crop zone,
        useful to render only part of an image.

        Args:
            x (float): abscissa of the clipping region top left corner
            y (float): ordinate of the clipping region top left corner
            w (float): width of the clipping region
            h (float): height of the clipping region
        r  r  r  z re W nNr  r  r  r   r   r   	rect_clips  s
    FzFPDF.rect_clipc                 c   s0   |  d | ||||d dV  |  d dS )a]  
        Context manager that defines an elliptic crop zone,
        useful to render only part of an image.

        Args:
            x (float): abscissa of the clipping region top left corner
            y (float): ordinate of the clipping region top left corner
            w (float): ellipse width
            h (float): ellipse height
        r  zW nNr  )r  r  r  r   r   r   elliptic_clip  s    
zFPDF.elliptic_clipc              	   c   s&   |  |||| dV  W 5 Q R X dS )aF  
        Context manager that defines a circular crop zone,
        useful to render only part of an image.

        Args:
            x (float): abscissa of the clipping region top left corner
            y (float): ordinate of the clipping region top left corner
            r (float): radius of the clipping region
        N)r  )r   r   r   r  r   r   r   
round_clip  s    zFPDF.round_clipc                 c   s   | j | j }}t| dd}d|_d| _td |V  |j| |j | | j  }|| | jksh|j |krtd |	  |j
  |  d|_d| _td dS )aL  
        Ensures that all rendering performed in this context appear on a single page
        by performing page break beforehand if need be.

        Notes
        -----

        Using this method means to duplicate the FPDF `bytearray` buffer:
        when generating large PDFs, doubling memory usage may be troublesome.
        Fr  TzStarting unbreakable blockz.Performing page jump due to unbreakable heightzEnding unbreakable blockN)r   r   ri   r  r   r  r  r6  rC  rewindZpdfr  Zreplayr   r  r  recorderZy_scrollr   r   r   unbreakable  s    


zFPDF.unbreakablec                 c   sj   | j | j }}t| dd}d|_|V  |j| |j | | j  }|| | jksX|j |kr^d|_|  dS )z
        All rendering performed in this context is made on a dummy FPDF object.
        This allows to test the results of some operations on the global layout
        before performing them "for real".
        Fr  TN)r   r   ri   r  r6  rC  r  r  r   r   r   offset_rendering  s    zFPDF.offset_rendering)render_toc_functionr   allow_extra_pagesr   c                 C   s   |dk rt d| t|s0tdt| | jrHtd| jj t|| j| j	| j
||| _|| _t|D ]}|   qpdS )a  
        Configure Table Of Contents rendering at the end of the document generation,
        and reserve some vertical space right now in order to insert it.
        At least one page break is triggered by this method.

        Args:
            render_toc_function (function): a function that will be invoked to render the ToC.
                This function will receive 2 parameters: `pdf`, an instance of FPDF, and `outline`,
                a list of `fpdf.outline.OutlineSection`.
            pages (int): the number of pages that the Table of Contents will span,
                including the current one that will. As many page breaks as the value of this argument
                will occur immediately after calling this method.
            allow_extra_pages (bool): If set to `True`, allows for an unlimited number of
                extra pages in the ToC, which may cause discrepancies with pre-rendered
                page numbers. For consistent numbering, using page labels to create a
                separate numbering style for the ToC is recommended.
            reset_page_indices (bool): Whether to reset the pages indices after the ToC. Default to True.
        r   z3'pages' parameter must be equal or greater than 1: z,The first argument must be a callable, got: zIA placeholder for the table of contents has already been defined on page N)r/  callablerk  r  r   rH   r   r   r   r   r   r   r	  r  )r   r  r   r  r   r9  r   r   r   insert_toc_placeholder  s.    zFPDF.insert_toc_placeholderc           	      C   sR   |||||||fD ]$}|rt |tstdt| q|||||||d| _dS )a  
        Defines a style for section titles.
        After calling this method, calls to `FPDF.start_section` will render section names visually.

        Args:
            level0 (TextStyle): style for the top level section titles
            level1 (TextStyle): optional style for the level 1 section titles
            level2 (TextStyle): optional style for the level 2 section titles
            level3 (TextStyle): optional style for the level 3 section titles
            level4 (TextStyle): optional style for the level 4 section titles
            level5 (TextStyle): optional style for the level 5 section titles
            level6 (TextStyle): optional style for the level 6 section titles
        z0Arguments must all be TextStyle instances, got: )r   r   r   r  r  r     N)r   rN   rk  r  r   )	r   Zlevel0Zlevel1Zlevel2Zlevel3Zlevel4Zlevel5Zlevel6levelr   r   r   set_section_title_styles  s    zFPDF.set_section_title_stylesc                 C   s  |dk rt d|rL| jrL|| jd jd krLt d| d| jd j dt| j| j| j| j  d}d	}| jr| j| }|j	d	k	r| j
}|j	| _
tj}t|jttfrt|j}| j| j| j|tjtjd
tj|t|jpdt|jttfr|jnd|jpddd	}	|j	d	k	r|| _
|	r,|   | j |dH}
|
}| !|. | j| j| j||tjtj|jtj"kd W 5 Q R X W 5 Q R X | j#t$||| j|| d	S )a  
        Start a section in the document outline.
        If section_title_styles have been configured,
        render the section name visually as a title.

        Args:
            name (str): section name
            level (int): section level in the document outline. 0 means top-level.
            strict (bool): whether to raise an exception if levels increase incorrectly,
                for example with a level-3 section following a level-1 section.
        r   z)"level" mut be equal or greater than zeror<  r   z+Incoherent hierarchy: cannot start a level z section after a level z one)r?  NT)r?  r>  r  )	r1  r4  r  r  r  r   r  r  r  r]  )r1  r4  r  r  r  r  r  )%r/  r   r  rn   r   rH  r   r   r   size_ptr   r0   r  r   r   r   r  r  r3  rz  rE   r  rF   r  r8   r  ry   r   r   r  r5  r  r8  use_text_styler  r  r`   )r   rg  r  strictr[  Zoutline_struct_elem
text_styleZprev_font_size_ptr  r  rG  r   r   r   start_section1  sh    



	zFPDF.start_section)r  c              	   c   s   d }|rV|j r| |j  |jrVt|jttfrH| j}|j| _| j| _ntd|j | 	| d V  W 5 Q R X |r|j
r| |j
 |d k	r|| _| j| _d S )Nz@Unsupported '%s' value provided as l_margin to .use_text_style())r   r  r   r   r  r   r   r  r  use_font_facer5  )r   r  Zprev_l_marginr   r   r   r  x  s(    

zFPDF.use_text_style)	font_facec                 c   s   |sdV  dS | j | j| jf}| |jp,| j |jdk	r>|jjn| j|jpL| j d| _| j	}|j
dk	r~|j
| j	kr~| |j
 | j}|jdk	r| |j dV  |jdk	r| | || _	| j|  dS )a  
        Sets the provided `fpdf.fonts.FontFace` in a local context,
        then restore font settings back to they were initially.
        This method must be used as a context manager using `with`:

            with pdf.use_font_face(FontFace(emphasis="BOLD", color=255, size_pt=42)):
                put_some_text()

        Known limitation: in case of a page jump in this local context,
        the temporary style may "leak" in the header() & footer().
        NF)r   r   r   r  r  r  r  r  r   r   r  r  r   r  )r   r  Z	prev_fontZprev_text_colorZprev_fill_colorr   r   r   r    s.    


	


zFPDF.use_font_facec                 o   s"   t | f||}|V  |  dS )ao  
        Inserts a table, that can be built using the `fpdf.table.Table` object yield.
        Detailed usage documentation: https://py-pdf.github.io/fpdf2/Tables.html

        Args:
            rows: optional. Sequence of rows (iterable) of str to initiate the table cells with text content.
            align (str, fpdf.enums.Align): optional, default to CENTER. Sets the table horizontal position
                relative to the page, when it's not using the full page width.
            borders_layout (str, fpdf.enums.TableBordersLayout): optional, default to ALL. Control what cell
                borders are drawn.
            cell_fill_color (int, tuple, fpdf.drawing.DeviceCMYK, fpdf.drawing.DeviceGray, fpdf.drawing.DeviceRGB): optional.
                Defines the cells background color.
            cell_fill_mode (str, fpdf.enums.TableCellFillMode): optional. Defines which cells are filled
                with color in the background.
            col_widths (int, tuple): optional. Sets column width. Can be a single number or a sequence of numbers.
            first_row_as_headings (bool): optional, default to True. If False, the first row of the table
                is not styled differently from the others.
            gutter_height (float): optional vertical space between rows.
            gutter_width (float): optional horizontal space between columns.
            headings_style (fpdf.fonts.FontFace): optional, default to bold.
                Defines the visual style of the top headings row: size, color, emphasis...
            line_height (number): optional. Defines how much vertical space a line of text will occupy.
            markdown (bool): optional, default to False. Enable markdown interpretation of cells textual content.
            text_align (str, fpdf.enums.Align): optional, default to JUSTIFY. Control text alignment inside cells.
            v_align (str, fpdf.enums.VAlign): optional, default to CENTER. Control vertical alignment of cells content.
            width (number): optional. Sets the table width.
            wrapmode (fpdf.enums.WrapMode): "WORD" for word based line wrapping (default),
                "CHAR" for character based line wrapping.
            padding (number, tuple, Padding): optional. Sets the cell padding. Can be a single number or a sequence
                of numbers, default:0
                If padding for left or right ends up being non-zero then the respective c_margin is ignored.
            outer_border_width (number): optional. The outer_border_width will trigger rendering of the outer
                border of the table with the given width regardless of any other defined border styles.
            num_heading_rows (number): optional. Sets the number of heading rows, default value is 1. If this value is not 1,
                first_row_as_headings needs to be True if num_heading_rows>1 and False if num_heading_rows=0. For backwards compatibility,
                first_row_as_headings is used in case num_heading_rows is 1.
            repeat_headings (fpdf.enums.TableHeadingsDisplay): optional, indicates whether to print table headings on every page, default to 1.
        N)rq   r  )r   r   r   tabler   r   r   r    s    )z
FPDF.tablec              	   C   s  |rt jdtt d t  | js| jdkr6|   | 	  | j
rL|   | jr| j D ]>}| D ]0}|j| d|t| jd|_qhq\|rt}|| }| | _|rt|tjr|| j n(t|trt|| j n|| j dS | jS )ao  
        Output PDF to some destination.
        The method first calls [close](close.md) if necessary to terminate the document.
        After calling this method, content cannot be added to the document anymore.

        By default the bytearray buffer is returned.
        If a `name` is given, the PDF is written to a new file.

        Args:
            name (str): optional File object or file path where to save the PDF under
            dest (str): [**DEPRECATED since 2.3.0**] unused, will be removed in a later version
            output_producer_class (class): use a custom class for PDF file generation
        zL"dest" parameter is deprecated since v2.2.0, unused and will soon be removedr   r   r   N)r   r   r   r$   rw   cache_clearr  r   r  r  r   rg  rz  r   r%  Zget_text_substitutionsr  rB  Zget_placeholder_stringrM  Zrender_text_substitutionr   r8  r[   Z	bufferizer   osPathLikewrite_bytesr   r"  )r   rg  r[  Z	linearizeZoutput_producer_classr   Zsubstitution_itemZoutput_producerr   r   r   r    sL    	



zFPDF.output)r   r   r   r   )NNNNN)r<  )r   )r   )TNNNN)N)ry  )NNN)r   r   Fr   NNNN)T)r<  r<  )r<  r<  )r<  r<  )FF)N)N)r   r   r   )FFN)FN)r   r   )NFr   )N)N)r   N)r   N)Nr   FFFN)Nr   FN)FN)Nr   Nr   )Nr   r   )T)T)r   r   r<  rR  )r   r   r<  rR  )N)NNNN)r   r   N)NNNN)r~  r  N)r  NN)r   r  r   )r   )NN)NN)r   r   NN)NNNNNNNN)r   )
NNr   r   r   r   NNNF)	NNr   r   r   NNNF)NNr   r   r   NNF)N)N)N)N)r   r#  )r  r  )r   FT)NNNNNN)r   T)r   r   r   __doc__r  r  r  r  r  recompileDOTALLr  r  r  r  r  rR   r  r   r6   RC4r/   allr  r  r  propertyrA   r  r   r!  r;   r"  setterr&  rG   r   rg   r0  r3  r6  r8  r;  r   r=  rA  rB  r   rF  r   r   r   r   r@   rZ  rM  r\  r^  r`  rb  rd  rf  rh  rj  ro  rq  rt  rx  r   r   r9   r   r  r  ru   r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r=   AUTOr  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r-  r0  r@  r  rC  rK  r  r  rQ  rT  rV  rS  rp  r   rt  rv  r{  r}  r  r  r  r  r%   r  r  r  r  r  r  r  r  r  r0   r  rE   r  rF   r  r  r^   ry   r  r  r  r  r  r   r\   r  r   r  r  r  r  r  r  rD   ZWORDr8   r  r  r"  r   r,  r  rU   r.  r5  rm   rV   r-  r7  rZ   r8  r`  r  rH  rI  rJ  rK  r
  r  r2   ZPRINTLOCKEDr_  r]  rg  rh  rp  r  r  r  r  r  r  r  r  r  r  r   r  r  r  rN   r  rM   r  r  rb   r  __classcell__r   r   r	  r   r      s  

    
!	

    (



		
    
O

			
	  
        
 
(
7

*&E'#         
-@B]2   
9   %   3
    !
	  4    #/"'  ?       
^

 
  V) .  MT
5         c        3       XP

-
89
7D  5     &F&,   r   r  FrE   rF   rT   rU   rV   rC   rO   r   )N)rm  r  loggingr  r  r  sysr  r   collectionsr   
contextlibr   r   r   	functoolsr   r   Znumbersr	   os.pathr
   pathlibr   typingr   r   r   r   r   r   ,cryptography.hazmat.primitives.serializationr   Zendesiver   rX  Z	PIL.Imager   r   actionsr   annotationsr   r   r   r    Zbidir!   r"   deprecationr#   r$   r%   Zdrawingr&   r'   r(   r)   r*   r+   r,   r-   Z
encryptionr.   enumsr/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   errorsrH   rI   rJ   r   rK   rL   rM   rN   rO   rP   r  rQ   htmlrR   Zimage_datastructuresrS   rT   rU   rV   Zimage_parsingrW   rX   rY   rZ   Zlinearizationr[   Z
line_breakr\   r]   r^   r_   outliner`   r  ra   rb   rc   rd   re   rf   rg   rh   r  ri   r]  rj   Zstructure_treerk   r:  rl   rm   Zsyntaxrn   ro   rp   r  rq   rr   Ztext_regionrs   rt   Ztransitionsru   Zunicode_scriptrv   rw   utilrx   ry   ZFPDF_VERSIONr   	getLoggerr   r  __file__resolver>  ZHEREr7  ZSINGLE_PAGEZ
ONE_COLUMNZTWO_COLUMN_LEFTrL  r   r   r   r   modulesr
  Z__pdoc____all__r   r   r   r   <module>   s   (
l (



$                                          m