a
    ˜ëj«  ã                   @  sØ  d dl mZ d dl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mZmZmZ dd	lmZ dd
lmZ ddlmZ ddlmZmZ ddlmZmZmZmZ ddlm Z  ddl!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0m1Z1 ddl2m3Z3 e�r2d dl4m5Z5 ddlm6Z6 zd dl7Z7d dl8m9Z9 dZ:W n e;�yf   dZ:Y n0 dZ<dZ=eG dd„ dƒƒZ>G dd„ de$ƒZ?G dd „ d eƒZ@G d!d"„ d"eƒZAG d#d$„ d$e?ƒZBd%d&d'd(œd)d*„ZCdS )+é    )ÚannotationsN)Ú	dataclassÚfield)ÚIntEnum)ÚBytesIO)Ú
attrgetter)ÚTYPE_CHECKINGÚAnyÚ
NamedTupleÚcasté   )Ú!encoding_dict_from_named_encoding)ÚCORE_FONT_METRICS)ÚTransformation)Úis_char_rtlÚlogger_warning)ÚAnnotationDictionaryAttributesÚBorderStylesÚFieldDictionaryAttributesÚPageAttributes)ÚPdfReadError)
ÚArrayObjectÚContentStreamÚDecodedStreamObjectÚDictionaryObjectÚFloatObjectÚIndirectObjectÚ
NameObjectÚNumberObjectÚRectangleObjectÚStreamObject)ÚByteStringObjectÚTextStringObjecté   )ÚColorÚ
DeviceGray)ÚFont)Ú	PdfWriter)Ú
PageObject)Úget_displayTFé   iè  c                   @  sf   e Zd ZU dZedd„ d�Zded< dZded	< ej	Z
d
ed< dZded< dZded< dZded< dS )ÚBaseStreamConfigzBA container representing the basic layout of an appearance stream.c                   C  s   t dƒS )N)ç        r,   r,   r,   )r   © r-   r-   ú_/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/pypdf/generic/_appearance_stream.pyÚ<lambda>6   ó    zBaseStreamConfig.<lambda>)Údefault_factoryr   Ú	rectangler#   ÚintÚborder_widthÚstrÚborder_styleNúColor | NoneÚborder_colorÚbackground_colorr   Úrotation)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r2   Ú__annotations__r4   r   ÚSOLIDr6   r8   r9   r:   r-   r-   r-   r.   r+   3   s   
r+   c                      s8   e Zd ZdZdddœdd„Zdddœ‡ fd	d
„Z‡  ZS )ÚBaseStreamAppearancez^A class representing the very base of an appearance stream, that is, a rectangle and a border.r3   ÚNone)r:   Úreturnc                 C  s¾   t ƒ  |¡}| jjjdf}d| jjjf}| jjj| jjjf}| |¡}| |¡}| |¡}td|d |d |d ƒ }	td|d |d |d ƒ }
| |	|
¡}t	dd„ |j
D ƒƒ| tdƒ< d S )Nr,   r   r#   c                 S  s   g | ]}t t|d ƒƒ‘qS )é   )r   Úround)Ú.0Úir-   r-   r.   Ú
<listcomp>T   r0   z4BaseStreamAppearance._add_matrix.<locals>.<listcomp>ú/Matrix)r   ÚrotateÚ_layoutr2   ÚwidthÚheightZapply_onÚminÚ	translater   Úctmr   )Úselfr:   ZmatrixZbottom_right_cornerZtop_left_cornerZtop_right_cornerZrotated_bottom_right_cornerZrotated_top_left_cornerZrotated_top_right_cornerZtranslation_x_offsetZtranslation_y_offsetr-   r-   r.   Ú_add_matrixA   s    


ÿÿz BaseStreamAppearance._add_matrixúBaseStreamConfig | None)ÚlayoutrC   c                   s~  t ƒ  ¡  |ptƒ | _tdƒ| tdƒ< tdƒ| tdƒ< | jj| tdƒ< | jjd }|r`|  |¡ g }t| jj	t
ƒr¤| d| jjj› d| jjj› d	| jj	 ¡ › d
�¡ | jjdk�rNt| jjt
ƒ�rF| jjdkrÜ| jj› d�nd}| | jj› d| jj› d| jjjd| jj  › d| jjjd| jj  › d	|› | jjjdd�› d�¡ nd| j_|�rj| dd¡ | d¡ d |¡ ¡ | _dS )z„
        Takes the appearance stream layout as an argument.

        Args:
            layout: The basic layout parameters.
        z/XObjectú/Typez/Formú/Subtypeú/BBoxih  z0 0 ú z re
z
f
r   r#   z w
Ú r   T)Zstrokez
s
zq
zQ
N)ÚsuperÚ__init__r+   rK   r   r2   r:   rR   Ú
isinstancer9   r$   ÚappendrL   rM   Úas_operatorr4   r8   ÚinsertÚjoinÚencodeÚ_ap_stream_data)rQ   rT   r:   Zap_stream_partsZborder_width_string©Ú	__class__r-   r.   r[   V   sH    


ÿÿ
ÿþýüûÿ
zBaseStreamAppearance.__init__)r;   r<   r=   r>   rR   r[   Ú__classcell__r-   r-   rc   r.   rA   >   s   rA   c                   @  s   e Zd ZdZdZdZdZdS )ÚTextAlignmentzODefines the alignment options for text within a form field's appearance stream.r   r#   r   N)r;   r<   r=   r>   ÚLEFTÚCENTERÚRIGHTr-   r-   r-   r.   rf   ˆ   s   rf   c                   @  s*   e Zd ZU dZded< ded< ded< dS )ÚWidthWordGlyphszgA tuple of the unscaled width of a word (unencoded text) and the font-encoded glyphs that represent it.ÚfloatrL   r5   ÚwordÚglyphsN)r;   r<   r=   r>   r?   r-   r-   r-   r.   rj   �   s   
rj   c                      s  e Zd ZdZd5ddddddddddœ	dd	„Zd
dddejddfddddddddddddœdd„Zdddddd
dddejddfddddddddddddddœ‡ fdd„Ze	dd d dd!d"œd#d$„ƒZ
e	d6d%ddd d&d'd(œd)d*„ƒZe	d+d,d-œd.d/„ƒZed7d%d1dd d d ddd d2œ	d3d4„ƒZ‡  ZS )8ÚTextStreamAppearanceaH  
    A class representing the appearance stream for a text-based form field.

    This class generates the content stream (the `ap_stream_data`) that dictates
    how text is rendered within a form field's bounding box. It handles properties
    like font, font size, color, multiline text, and text selection highlighting.
    çš™™™™™É?r&   rk   zlist[list[WidthWordGlyphs]]z#tuple[list[WidthWordGlyphs], float])	ÚfontÚ	font_sizeÚleading_factorÚfield_widthÚfield_heightÚ
paragraphsÚmin_font_sizeÚfont_size_steprC   c	                 C  sŒ  g }	g }
d}|j | t }|D �]}t|ƒD ]À\}}|j| }|| |rL|nd }||kr |
r |	 t|d ttdƒ|
ƒ¡|j	 ttdƒ|
ƒ¡d�¡ |g}
|}q,|
sÎ||krÎ|	 t||j
|jd�¡ g }
d}q,|
rÚ||7 }|
 |¡ ||7 }q,|
r|	 t|d ttdƒ|
ƒ¡|j	 ttdƒ|
ƒ¡d�¡ g }
d}q|t|	ƒd | |  }||k�r~|| }||k�r~|  ||||||||¡S |	t|dƒfS )aô  
        Takes a piece of text and scales it to field_width or field_height, given font_name
        and font_size. Wraps text where necessary.

        Args:
            font: The font to be used.
            font_size: The font size in points.
            leading_factor: The line distance.
            field_width: The width of the field in which to fit the text.
            field_height: The height of the field in which to fit the text.
            paragraphs: The list of text paragraphs to fit with the field, where each paragraph is a list
                of tuples of unscaled width, unencoded text, and glyphs (font-encoded text).
            min_font_size: The minimum font size at which to scale the text.
            font_size_step: The amount by which to decrement font size per step while scaling.

        Returns:
            The text in the form of list of tuples, each tuple containing the length of a line
            and its contents, and the font_size for these lines and lengths.
        r   rX   rl   rm   ©rL   rl   rm   r#   )Úspace_widthÚ TEXT_SPACE_TO_GLYPH_SPACE_FACTORÚ	enumeraterL   r]   rj   r`   Úmapr   Z
space_charrl   rm   ÚlenÚ_scale_textrE   )rQ   rp   rq   rr   rs   rt   ru   rv   rw   Zwrapped_linesZcurrent_line_wordsZcurrent_line_widthry   Z	paragraphrG   Zwidth_word_glyphsZ
word_widthZ
test_widthZestimated_total_heightZnew_font_sizer-   r-   r.   r~   ¡   sn    

ýÿýÿ

ý

ø
z TextStreamAppearance._scale_textú/Helvr,   NFr5   zlist[str] | Noner7   Úboolrf   z
int | NoneÚbytes)ÚtextÚ	selectionrp   Ú	font_namerq   Ú
font_colorÚis_multilineÚ	alignmentÚis_combÚ
max_lengthrC   c           5      C  sd  |pt ƒ }| jj}|jjd |jjd  t }| jjdv r>dnd}| jj| }|jd|  }|j	dt
|dƒ  }| ¡ \}}ddddœd	d
„}ddddœdd„}|dk�r´d}|r¶d}|�rZt}g }| ¡ D ]p}| ¡ sð| tdddd�g¡ qÌg }| d¡}|D ].}|||ƒ}| t| |¡t ||d�¡ �q| |¡ qÌ|  |||||||¡\}}nX|| }|||ƒ}| |¡t }||�p„d } tt
t|| ƒ|ƒdƒ}t|| ||d�g}nÄ|	�r8|
�rÞt|ƒ|
k�rÞtdt||
d� g }t|ƒD ]J\}!}"|!|
�p t|ƒk �rê||"|ƒ}| t| |¡| t |"|d�¡ �qên@g }| ¡ D ]2}|||ƒ}| t| |¡| t ||d�¡ �qD|�rœ|| |jjd | t  }#n|||jj| t  d  }#|› d|› d| ¡ › �}$tƒ }%|%ddt
|dƒ › d|› dt|dt
|dƒ  dƒ› dt|| dƒ› d|$› d� ¡ 7 }%d}&|�rD|d |¡|ƒnd}'t|ƒD �] \}(\})}*}|'�r¶||'v �r¶|%dt|#|(| |  d dƒ› d|j	d › d|d › d|$› d�	 ¡ 7 }%d}+|	�rê|
�rê|j	|
 },|,|) d }-|(|, |- }+nP|tj k�r|j	t
|dƒd  |) }+n*|tj!k�r,|j	|) d }+nt
|dƒd }+|+|& }.d}/|(dk�rV|#}/n|	�rbd}/n
| | }/|%t|.dƒ› dt|/dƒ› d� ¡ 7 }%|+}&t"d d!„ |D ƒƒ}0|||ƒ}1|0�räd"|* d#¡ }2|2 #¡  $¡ }3|%d$|3› d%� ¡ 7 }%|j%d&k�r|%d'd( |1¡ #¡  ¡  d) 7 }%n2d( |1¡ &d*d+¡ &d,d-¡ &d.d/¡}4|%d,|4 d0 7 }%|0�rP|%d17 }%�qP|%d27 }%t'|%ƒS )3aI  
        Generates the raw bytes of the PDF appearance stream for a text field.

        This private method assembles the PDF content stream operators to draw
        the provided text within the specified rectangle. It handles text positioning,
        font application, color, and special formatting like selected text.

        Args:
            text: The text to be rendered in the form field.
            selection: An optional list of strings that should be highlighted as selected.
            font: The font to use.
            font_name: The name of the font resource to use (e.g., "/Helv").
            font_size: The font size. If 0, it is automatically calculated
                based on whether the field is multiline or not.
            font_color: The color to apply to the font, represented as a class Color
            is_multiline: A boolean indicating if the text field is multiline.
            alignment: Text alignment, can be TextAlignment.LEFT, .RIGHT, or .CENTER.
            is_comb: Boolean that designates fixed-length fields, where every character
                fills one "cell", such as in a postcode.
            max_length: Used if is_comb is set. The maximum number of characters for a fixed-
                length field.

        Returns:
            A byte string containing the PDF content stream data.

        rD   r#   >   z/Iz/Br   é   r5   zdict[str, str])r‚   Úreverse_cmaprC   c                   sJ   t r2t | ¡}t|dd�}d ‡ fdd„|D ƒ¡S d ‡ fdd„| D ƒ¡S )NÚL)Úbase_dirrY   c                 3  s   | ]}ˆ   ||¡V  qd S ©N©Úget©rF   Úchar©r‹   r-   r.   Ú	<genexpr>4  r0   zfTextStreamAppearance._generate_appearance_stream_data.<locals>._unicode_to_glyph_id.<locals>.<genexpr>c                 3  s   | ]}ˆ   ||¡V  qd S rŽ   r�   r‘   r“   r-   r.   r”   6  r0   )ÚHAS_RTL_SUPPORTÚarabic_reshaperZreshaper)   r`   )r‚   r‹   Zreshaped_textZvisual_textr-   r“   r.   Ú_unicode_to_glyph_id/  s
    
zSTextStreamAppearance._generate_appearance_stream_data.<locals>._unicode_to_glyph_idzdict[str, bytes]zlist[bytes])rm   Úencoding_cmaprC   c                   s   ‡ fdd„| D ƒS )Nc                   s2   g | ]*}ˆ   |t|ƒd k r(tt|ƒfƒnd¡‘qS )é   ó   ?)r�   Úordr�   )rF   Zglyph_id©r˜   r-   r.   rH   :  s   þÿzeTextStreamAppearance._generate_appearance_stream_data.<locals>._glyph_id_to_bytes.<locals>.<listcomp>r-   )rm   r˜   r-   rœ   r.   Ú_glyph_id_to_bytes9  s    
þzQTextStreamAppearance._generate_appearance_stream_data.<locals>._glyph_id_to_bytesr   g      @Fr,   rY   rx   rX   zZLength of text %(text)s exceeds maximum length (%(max_length)d) of field, input truncated.)Úsourcer‚   r‰   z Tf zq
/Tx BMC 
q
z	 re
W
BT
Ú
z1 z re
0.5 0.5 0.5 rg s
z Td
c                 s  s   | ]}t |ƒV  qd S rŽ   )r   r‘   r-   r-   r.   r”   Í  r0   zHTextStreamAppearance._generate_appearance_stream_data.<locals>.<genexpr>s   þÿz	utf-16-bez/Span << /ActualText <z	> >> BDC
ZType0ó   <r0   s   > Tj
ó   \s   \\ó   (s   \(ó   )s   \)s   ) Tj
s   EMC
s   ET
Q
EMC
Q
)(r%   rK   r2   Úfont_descriptorZbboxrz   r6   r4   rM   rL   ÚmaxZ_get_typographic_mapsÚDEFAULT_FONT_SIZE_IN_MULTILINEÚ
splitlinesÚstripr]   rj   ÚsplitZget_text_widthr~   rE   rN   r}   r   r;   r{   Zascentr^   Ú	bytearrayra   r`   rf   ri   rh   ÚanyÚhexÚupperÚsub_typeÚreplacer�   )5rQ   r‚   rƒ   rp   r„   rq   r…   r†   r‡   rˆ   r‰   r2   rr   ZfactorÚmarginrt   rs   r‹   r˜   r—   r�   rv   ru   ÚlineZline_by_widths_words_glyphsÚwordsrl   Z
glyph_wordÚlinesZmax_vertical_sizerm   Ztext_width_unscaledZmax_horizontal_sizeÚindexr’   Zy_offsetÚdefault_appearanceZ	ap_streamZcurrent_x_posZselection_glyphsÚline_numberÚ
line_widthZoriginal_textZdesired_abs_x_startZ
cell_widthZcentering_offset_in_cellZx_rel_offsetZy_rel_offsetZis_rtlZencoded_lineZbom_textZhex_original_textZline_as_bytesr-   r-   r.   Ú _generate_appearance_stream_dataú   s0   '
ÿ



ýÿù


ù

ýÿ

ýÿ	ÿÿÿÿþþýÿÿÿþÿ


$
 
ÿþýÿz5TextStreamAppearance._generate_appearance_stream_datarY   rS   zFont | Nonez(DictionaryObject | IndirectObject | NonerB   )rT   r‚   rƒ   rp   Úfont_resourcer„   rq   r…   r†   r‡   rˆ   r‰   rC   c                   s¬   t ƒ  |¡ |r|s(d}t ¡ }| ¡ }|  j| j||||||pDtƒ |	|
||d�
7  _|  t	| jƒ¡ t
t| jƒƒ| tdƒ< ttdƒtt|ƒt|d|ƒiƒiƒ| tdƒ< dS )a1  
        Initializes a TextStreamAppearance object.

        This constructor creates a new PDF stream object configured as an XObject
        of subtype Form. It uses the `_generate_appearance_stream_data` method to
        generate the content for the stream.

        Args:
            layout: The basic layout parameters.
            text: The text to be rendered in the form field.
            selection: An optional list of strings that should be highlighted as selected.
            font: A Font object. Falls back to Type 1 Helvetica if not given.
            font_resource: An optional variable that represents a PDF font dictionary. Falls back
                to Type 1 Helvetica if not given.
            font_name: The name of the font resource, e.g., "/Helv".
            font_size: The font size. If 0, it's auto-calculated.
            font_color: The font color string.
            is_multiline: A boolean indicating if the text field is multiline.
            alignment: Text alignment, can be TextAlignment.LEFT, .RIGHT, or .CENTER.
            is_comb: Boolean that designates fixed-length fields, where every character
                fills one "cell", such as in a postcode.
            max_length: Used if is_comb is set. The maximum number of characters for a fixed-
                length field.

        r   ©r„   rq   r…   r†   r‡   rˆ   r‰   ú/Lengthú/FontÚindirect_referenceú
/ResourcesN)rZ   r[   r&   Úfrom_core_font_nameZas_font_resourcerb   r¸   r%   Úset_datar!   r   r}   r   r   Úgetattr)rQ   rT   r‚   rƒ   rp   r¹   r„   rq   r…   r†   r‡   rˆ   r‰   rc   r-   r.   r[   ç  s0    (
ö
ÿÿzTextStreamAppearance.__init__r   ztuple[str, Font])r„   Ú
annotationÚ	acro_formr‚   rC   c              
   C  sÐ  t t| d| dtƒ ¡¡ƒ}| dtƒ ¡}| | d ¡}|rJt | ¡ ¡}n*|  d¡tvrjt	dt
| d� d} t | ¡}| |¡}|�sÈ|jjrø|jdkrøz(| t|jj ¡ ƒ¡}d} | |¡}W n6 ttfyô }	 zt	d	t
|	d
� W Y d }	~	n
d }	~	0 0 n¼|jdk�r´|jtv �r´t|j }
h d£}|D ]Œ}t |¡}t|ƒ|_| |¡}|�r&|}|j ¡  |j ¡ D ]*\}}||
jv �rf|
j| |jt|ƒ< �qf|
jd |jd< d| }  �q´�q&|�sÈt	dt
|d� | |fS )Nú/DRr¼   ú/zEFont dictionary for %(font_name)s not found; defaulting to Helvetica.)rž   r„   z
/HelveticaZTrueTypez/PYPDF1z7Unable to use embedded font for encoding: %(exception)s)rž   Ú	exceptionZType1>   Úcp1257Ú
iso8859_15Úcp1254Úcp1252Úcp1250Údefaultz¿Text string '%(text)s' contains characters not supported by font encoding. This may result in text corruption. Consider calling writer.update_page_form_field_values with auto_regenerate=True.)rž   r‚   )r   r   Úget_inheritedr�   r&   Zfrom_font_resourceÚ
get_objectÚremoveprefixr   r   r;   r¿   Z
can_encoder¤   Z	font_filer®   Zfrom_truetype_font_filer   Úget_dataÚImportErrorr   ÚnameÚcopyr   ÚencodingZcharacter_widthsÚclearÚitemsÚchr)r„   rÂ   rÃ   r‚   Zacro_form_resourcesZacro_form_font_resourcesr¹   rp   Z	encodablerÆ   Zcore_font_metricsZtest_encodingsrÔ   Z	test_fontÚcodeÚ	characterr-   r-   r.   Ú_find_annotation_font_resource,  sn    	þþý

ý





ù
z3TextStreamAppearance._find_annotation_font_resourcer'   zPageObject | Noner   )Úwriterr„   rp   Útarget_resource_dictÚpagerC   c                 C  s€   |  tdƒtƒ ¡ ¡ }||vr2| | |t|ƒ¡}n|| }|r|tt|tj ƒ  tdƒtƒ ¡ ¡ }||vr|t|d|ƒ|t|ƒ< |S )zÇ
        Unified helper to sync fonts from an AP stream to a target resource dictionary (e.g., AcroForm /DR).
        Will sync to page resources as well when page is added to the arguments.
        r¼   r½   )	Ú
setdefaultr   r   rÎ   Z_add_to_writerr   r   Z	RESOURCESrÁ   )rÛ   r„   rp   rÜ   rÝ   Ztarget_fontsÚfont_resource_referenceZpage_fonts_resourcer-   r-   r.   Ú&_sync_appearance_stream_font_resources‡  s"    ý
ÿÿz;TextStreamAppearance._sync_appearance_stream_font_resourcesz#TextStringObject | ByteStringObjectz&tuple[str | None, float, Color | None])rµ   rC   c           	      C  sÈ   t ddƒ}| | j¡ z
|j}W n ty4   Y dS 0 d}d}d}|D ]v\}}|dkržt|ƒdkr¼t|d tƒr¼t|d tt	fƒr¼t
|d ƒt	|d ƒ }}qFt || d¡¡ }durF|}qF|||fS )	aÿ  
        Read the font name, font size and font color from a default appearance string.

        A default appearance is a content stream fragment of graphics and text state operators, such as
        `/a1.0 gs 0 0 0 rg /Helv 10 Tf` (Section 12.7.4.3 "Variable text" of the PDF 2.0 specification).
        Where an operator occurs more than once, the last one is in effect. Operators other than `Tf` and
        the non-stroking color operators are ignored.

        Args:
            default_appearance: The /DA string of a variable text field.

        Returns:
            The font name and font size of the last complete Tf operator, or None and 0 if there is none,
            and the color of the last complete color operator, or None if there is none.
        N)Nr,   Nr,   s   Tfr   r   r#   zlatin-1)r   rÀ   Úoriginal_bytesÚ
operationsr   r}   r\   r   r3   rk   r5   r$   Úfrom_normalized_valuesÚdecode)	rµ   Ústreamrâ   r„   rq   r…   ZoperandsÚoperatorÚcolorr-   r-   r.   Ú_parse_default_appearance¨  s     

,z.TextStreamAppearance._parse_default_appearanceéÿÿÿÿr(   )	rÛ   rÝ   ÚflattenrÃ   r   rÂ   Úuser_font_nameÚuser_font_sizerC   c	           #      C  sz  t t|tj ƒ}	| d¡dv rPtddt|	d |	d  ƒt|	d |	d  ƒfƒ}
n0tddt|	d |	d  ƒt|	d |	d  ƒfƒ}
| tj| tjd¡¡}|s¦tdƒ}n| 	¡ }| t
jd¡}| t
jd	¡d
k�r|t
jj@ dk�rd | t
jg ¡¡}| dg ¡}t|tƒ�s&|g}n| dd¡}g }|  |¡\}}}|du �rZtdtt|ƒd� d\}}|�rf|}n|}|dk�rx|}|  ||||¡\}}||k�r®t| ||¡ƒ|tdƒ< |  |||| tdƒtƒ ¡|�rÒ|nd¡}d}d}|t
jj@ �rüd}| d¡}d}|t
jj@ �rd}| dtj ¡}d}t!j"}d|v �r`t t|d ƒ d|¡}t t|d ƒ d|¡}d}d}d}| dd¡}t|tƒ�r´t#| dd¡ƒ}t$ %| d¡¡}t$ %| d¡¡}t&|
|||||d�}| ||||||||||||d�} tj'|v �rvt t|tj' ƒ d i ¡ (¡ D ]d\}!}"|!d!v �r&�q|!d"k�rjd#|"v�rLtƒ |" 	¡ td#ƒ< t)|d$|ƒ|"d#  	¡ t|ƒ< n|"| |!< �q| S )%aE  
        Creates a TextStreamAppearance object from a text field annotation.

        This class method is a factory for creating a `TextStreamAppearance`
        instance by extracting all necessary information (bounding box, font,
        text content, etc.) from the PDF field and annotation dictionaries.
        It respects inheritance for properties like default appearance (`/DA`).

        Args:
            writer: The PdfWriter instance that we are creating text stream appearances for.
            page: The page that we are processing annotations for.
            flatten: Whether we flatten text annotations or not. If true, add new font resource
                to the page font resources. Otherwise, add them to the AcroForm resources.
            acro_form: The root AcroForm dictionary from the PDF catalog.
            field: The field dictionary object.
            annotation: The widget annotation dictionary object associated with the field.
            user_font_name: An optional user-provided font name to override the
                default. Defaults to an empty string.
            user_font_size: An optional user-provided font size to override the
                default. A value of -1 indicates no override.

        Returns:
            A new `TextStreamAppearance` instance configured for the given field.

        z/Rotate>   éZ   i  r   rD   r#   r   Nz/Helv 0 Tf 0 gz/Txz/ChrŸ   z/VrY   zsCould not read a complete Tf operator from the default appearance %(default_appearance)r; defaulting to /Helv 0 Tf.)rž   rµ   )r   r,   z/DArÄ   FTz/MaxLenz/Qz/BSz/Wz/Sz/MKz/Rz/BCz/BG)r2   r4   r6   r8   r9   r:   rº   ú/N>   z/FilterrU   rV   r»   rW   r¾   r¼   r½   )*r   r   r   ZRectrÍ   ÚabsZDAr�   r"   rÎ   r   ZFfZFTZFfBitsZCombor`   ZOptr\   Úlistrè   r   r;   r5   rÚ   r¯   r   rà   rÞ   r   ZCombZ	Multilinerf   rg   r   r@   r3   r$   rã   r+   ZAPrÖ   rÁ   )#ÚclsrÛ   rÝ   rê   rÃ   r   rÂ   rë   rì   Z
_rectangler2   rµ   Zfield_flagsr‚   rƒ   Zda_font_namerq   r…   r„   rp   rß   rˆ   r‰   r†   r‡   r4   r6   r:   r8   r9   Zappearance_characteristicsrT   Znew_appearance_streamÚkeyÚvaluer-   r-   r.   Úfrom_text_annotationÎ  sÌ    &20þ
ÿþ

ú

û	

ú	ôÿ



ÿz)TextStreamAppearance.from_text_annotation)ro   )N)rY   ré   )r;   r<   r=   r>   r~   rf   rg   r¸   r[   ÚstaticmethodrÚ   rà   rè   Úclassmethodrô   re   r-   r-   rc   r.   rn   ˜   sH    ÷ ^õ$ pó,EZ û %	  ÷rn   r   r   rB   )Úannotation_objÚtransformationrC   c                 C  s¨   d| vrdS t t| d ƒ}d|vr&dS |d }t|tƒrJt|tƒsJ| ¡ n|g}|D ]N}| ¡ }t|tƒslqTt| dd¡ƒ}tdd„ t	|ƒ 
|¡jD ƒƒ|tdƒ< qTdS )aW  
    Compose `transformation` into an annotation's /AP /N appearance stream(s), in place.

    Repositioning/resizing an annotation's /Rect alone is not enough: per
    the appearance-stream algorithm (PDF 2.0, 12.5.5), a viewer fits the
    appearance's /BBox (as mapped by its own /Matrix) into /Rect using an
    axis-aligned scale, never a rotation. Left alone, rotating or shearing
    a page therefore stretches/skews the untouched appearance content into
    the new, differently-shaped /Rect instead of rotating it. Composing the
    transform into /Matrix (rather than overwriting it) keeps the rendered
    content consistent with the rest of the transformed page while
    preserving whatever the annotation already had. Handles both a single
    appearance stream and the multi-state /AP /N dict used by
    checkbox/radio-button widgets.
    z/APNrî   rI   )r#   r   r   r#   r   r   c                 s  s   | ]}t |ƒV  qd S rŽ   )r   )rF   Úxr-   r-   r.   r”   ¬  s   z2transform_annotation_appearance.<locals>.<genexpr>)r   r   r\   r    ÚvaluesrÎ   Útupler�   r   r   Z	transformrP   r   )r÷   rø   ZapZ	normal_apZ	state_apsZstate_apZ	state_objZ
old_matrixr-   r-   r.   Útransform_annotation_appearance…  s(    ÿÿ
ý
ÿrü   )DÚ
__future__r   rÓ   Zdataclassesr   r   Úenumr   Úior   ræ   r   Útypingr   r	   r
   r   Ú_codecsr   Z_codecs.core_font_metricsr   Z_pager   Ú_utilsr   r   Ú	constantsr   r   r   r   Úerrorsr   Zgenericr   r   r   r   r   r   r   r   r   r    Zgeneric._baser!   r"   Z_colorr$   r%   Z_fontr&   Zpypdf._writerr'   r(   r–   Zbidi.algorithmr)   r•   rÑ   r¦   rz   r+   rA   rf   rj   rn   rü   r-   r-   r-   r.   Ú<module>   sN   0

J     r