
    mjv                    T   d dl mZ d dlZd dlmZ d dlmZ d dlmZ d dl	m
Z
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mZmZmZ ddlmZ ddlmZmZmZm Z m!Z!m"Z" ddl#m$Z$m%Z% e
rd dl&m'Z' ddl(m)Z) dZ*e G d d             Z+ G d de      Z, G d de      Z- G d de,      Z.y)    )annotationsN)	dataclass)IntEnum)BytesIO)TYPE_CHECKINGAnycast   )fill_from_encoding)CORE_FONT_METRICS)Font)logger_warning)AnnotationDictionaryAttributesBorderStylesFieldDictionaryAttributesPageAttributes)PdfReadError)DecodedStreamObjectDictionaryObjectIndirectObject
NameObjectNumberObjectRectangleObject)ByteStringObjectTextStringObject)	PdfWriter)
PageObject   c                  P    e Zd ZU dZdZded<   dZded<   ej                  Z	ded	<   y
)BaseStreamConfigzBA container representing the basic layout of an appearance stream.)        r!   r!   r!   z3RectangleObject | tuple[float, float, float, float]	rectangle   intborder_widthstrborder_styleN)
__name__
__module____qualname____doc__r"   __annotations__r%   r   SOLIDr'        S/root/.hermes/venv/lib/python3.12/site-packages/pypdf/generic/_appearance_stream.pyr    r    !   s*    LEYIBYL#$**L#*r/   r    c                  $     e Zd ZdZd fdZ xZS )BaseStreamAppearancez^A class representing the very base of an appearance stream, that is, a rectangle and a border.c                    t         |           |xs
 t               | _        t	        d      | t	        d      <   t	        d      | t	        d      <   t        | j                  j                        | t	        d      <   y)z
        Takes the appearance stream layout as an argument.

        Args:
            layout: The basic layout parameters.
        z/XObject/Typez/Form/Subtype/BBoxN)super__init__r    _layoutr   r   r"   )selflayout	__class__s     r0   r8   zBaseStreamAppearance.__init__,   sf     	3!1!3$.z$:Z !'1'':Z
#$$3DLL4J4J$KZ !r/   )r;   BaseStreamConfig | NonereturnNone)r(   r)   r*   r+   r8   __classcell__r<   s   @r0   r2   r2   )   s    hL Lr/   r2   c                      e Zd ZdZdZdZdZy)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/   r0   rC   rC   :   s    YDFEr/   rC   c                      e Zd ZdZ	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddddej                  ddf	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZdd	dddddddej                  ddf	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fd
Ze		 	 	 	 	 	 	 	 	 	 dd       Z
e		 d	 	 	 	 	 	 	 	 	 	 	 dd       Ze	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Z xZS )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.
    c	           
        g }	g }
d}|j                   |z  dz  }|D ]  }|j                         s|	j                  d       &|j                  |j                        }t        |      D ]  \  }}|j                  |      |z  dz  }||z   |r|ndz   }||kD  r4|
r2|	j                  ||j                  j                  |
      f       |g}
|}b|
s||kD  r|	j                  ||f       g }
d}|
r||z  }|
j                  |       ||z  } |
s|	j                  ||j                  j                  |
      f       g }
d}! |t        |	      dz
  |z  |z  z   }||kD  r"||z
  }||k\  r| j                  ||||||||      S |	t        |d      fS )ap  
        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 text paragraphs to fit with the field.
            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     )r!    r#   )space_widthstripappendsplit
space_char	enumerateget_text_widthjoinlen_scale_textround)r:   font	font_sizeleading_factorfield_widthfield_height
paragraphsmin_font_sizefont_size_stepwrapped_linescurrent_line_wordscurrent_line_widthrL   	paragraphwordsiword
word_width
test_widthestimated_total_heightnew_font_sizes                        r0   rU   z TextStreamAppearance._scale_textK   s   : (*$%&&2T9# 	'I??$$$Y/OODOO4E$U+ 54!006BTI
/*<qVWX
+0B!((*<doo>R>RSe>f)gh*.&)3&+
[0H!((*d);<)+&)*&)*k9*&--d3&*4&5  "$$&8$//:N:NOa:b%cd%'"%&"1	'4 "+c-.@1.D-VYb-b!b!L0%6M-''!" !"	 	 eIq111r/   /Helvr!   z0 gFNc                   | j                   j                  }t        |t              rt	        |      }|j
                  j                  d   |j
                  j                  d   z
  dz  }| j                   j                  dv rdnd}t        | j                   j                  |z  d      }|j                  d|z  z
  }|j                  d|z  z
  }|j                         \  }}d d}d!d}|d	k(  rd
}|rd}|rFt        }|j                         D cg c]  } |||       }}| j                  |||||||      \  }}n||z  } |||      }|j!                  |      dz  }||xs dz  }t#        t        t%        ||      |      d      }||z  |fg}n|	r}|
r!t'        |      |
kD  rt)        dt*        ||
       g }t-        |      D ]I  \  }}||
xs t'        |      k  s |||      }|j/                  |j!                  |      |z  dz  |f       K nHg }|j                         D ]3  } |||      }|j/                  |j!                  |      |z  dz  |f       5 |r0|j                  |z   |j
                  j                  d   |z  dz  z
  } n%|||j
                  j0                  |z  dz  z
  dz  z   } | d| d| }!dd|z   d| d| d| d|! dj3                         }"d	}#t-        |      D ]}  \  }$\  }%}|rV| |dj5                  |      |      v r<|"d| |$|z  |z  z
  dz
   d|j                  dz
   d|dz    d|! d	j3                         z  }"d	}&|	r"|
r |j                  |
z  }'|'|%z
  dz  }(|$|'z  |(z   }&nT|t6        j8                  k(  r|j                  |dz  z
  |%z
  }&n+|t6        j:                  k(  r|j                  |%z
  dz  }&n|dz  }&|&|#z
  })d	}*|$d	k(  r| }*n|	rd}*n| |z  }*|"|) d|* dj3                         z  }"|&}# |||      }+t=        d |+D              r8|"ddj5                  |+      j?                         j3                         z   dz   z  }"d|"ddj5                  |+      z   dz   z  }" |"dz  }"|"S c c}w )"a  
        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 PDF
                graphics state string (e.g., "0 g" for black).
            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.

           r#   g     @@>   /B/Ir
      c                8    dj                  fd| D              S )NrK   c              3  B   K   | ]  }j                  ||        y wN)get).0	characterreverse_cmaps     r0   	<genexpr>zfTextStreamAppearance._generate_appearance_stream_data.<locals>._unicode_to_glyph_id.<locals>.<genexpr>   s     Xi<++IyAXs   )rS   )textrv   s    `r0   _unicode_to_glyph_idzSTextStreamAppearance._generate_appearance_stream_data.<locals>._unicode_to_glyph_id   s    77XSWXXXr/   c                    | D cg c]7  }|j                  |t        |      dk  rt        t        |      f      nd      9 c}S c c}w )N      ?)rs   ordbytes)glyphsencoding_cmapglyph_ids      r0   _glyph_id_to_byteszQTextStreamAppearance._generate_appearance_stream_data.<locals>._glyph_id_to_bytes   sM     %& "%%S]S5H%X 01d & & &s   <Ar   g      @FrJ   zZLength of text %(text)s exceeds maximum length (%(max_length)d) of field, input truncated.)sourcerx   
max_length z Tf zq
/Tx BMC 
q
z	 re
W
BT

rK   z1 z re
0.5 0.5 0.5 rg s
r!   z Td
c              3  8   K   | ]  }t        |      d k\    yw)r
   N)rT   )rt   cs     r0   rw   zHTextStreamAppearance._generate_appearance_stream_data.<locals>.<genexpr>@  s     513q6Q;5s      <r/   s   > Tj
   (s   ) Tj
s   ET
Q
EMC
Q
)rx   r&   rv   zdict[str, str]r>   r&   )r   r&   r   zdict[str, bytes]r>   zlist[bytes]) r9   r"   
isinstancetupler   font_descriptorbboxr'   maxr%   heightwidth_get_typographic_mapsDEFAULT_FONT_SIZE_IN_MULTILINE
splitlinesrU   rR   rV   minrT   r   r(   rQ   rN   ascentencoderS   rC   rF   rE   anyhex),r:   rx   	selectionrW   	font_namerX   
font_coloris_multiline	alignmentis_combr   r"   rY   factormarginr[   rZ   rv   r   ry   r   r]   rb   glyph_paragraphslinesmax_vertical_sizer   text_width_unscaledmax_horizontal_sizeindexcharliney_offsetdefault_appearance	ap_streamcurrent_x_posline_number
line_widthdesired_abs_x_start
cell_widthcentering_offset_in_cellx_rel_offsety_rel_offsetencoded_lines,                                               r0    _generate_appearance_stream_dataz5TextStreamAppearance._generate_appearance_stream_data   s_   P LL**	i''	2I..33A69M9M9R9RST9UUY__ ll//<?QT\\..7; ''!f*4ooF
2&*&@&@&B#m	Y	& >M$:	SWSbSbSd$FO(LA$  $ $(#3#3" $!$ y %1>$A!-dLA&*&9&9&&AD&H#&15H5MA&N#!#c*;=P&QS`"acde	-	96BCc$i*45 $) E( [tJ3#d)41$EFLL$"5"5f"=	"ID"PRX!YZ[
 E) W-dLAd11&9IELfUVW
  ''&043G3G3L3LQ3OR[3[^d3ddH,1E1E1L1Ly1X[_1_"_cd!deH ){!I;d:,G q6zl!F81[M<. Q,-R1
&( 	  !/8/? 1	G+K+*dT%9"''):Ll%[[[9%<~%MNQRRSST *+1Y]O <));(<B@ &(		 *+:&__z9
 -7,Cq+H('2Z'?C[&[#m111&/oo
&BZ&O#m222'0'Cq&H#&,qj# />L #$La'"!*{^; L><.>EEGGI 0M-dMBL555TSXXl%;$@$@$B$I$I$KKiWW	TCHH\$::YFF	c1	Gd 	''	W$s   Q-rK   c                   t         |   |       |r|sd}t        d   }t        d      }t	        di t        t        t        d      |            d|j                  t        |      D ci c],  \  }}||j                  v rt        |      |j                  |   . c}}      }|j                  d   |j                  d<   |j                         }| j                  |||||||	|
||
      }| j                  t        |             t!        t#        |            | t%        d	      <   t'        t%        d
      t'        t%        |      t)        |d|      i      i      | t%        d      <   yc c}}w )a(  
        Initializes a TextStreamAppearance object.

        This constructor creates a new PDF stream object configured as an XObject
        of subtype Form. It uses the `_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.

        rj   	Helveticacp1252r{   Type1namecharacter_mapencodingsub_typer   character_widthsdefaultr   rX   r   r   r   r   r   /Length/Fontindirect_reference
/ResourcesN)r7   r8   r   r   r   dictzipranger   rQ   r   chras_font_resourcer   set_datar   r   rT   r   r   getattr)r:   r;   rx   r   rW   font_resourcer   rX   r   r   r   r   r   core_font_metricswin_ansi_encoding_listcodevalueap_stream_datar<   s                     r0   r8   zTextStreamAppearance.__init__H  s   P 	 =I 1+ >%7%A"  c%*.DEF  1 A A\e.]"MXTSX"3"D"DD I0AA%HH"D 0A/Q/QR[/\D!!), 113M>>!%! ? 
 	&~67&23~3F&GZ	"#)9w!19%w}>RTa'b3 ";
 *Z%&3"s   )1E&c                   t        t        |j                  d|j                  dt                                 }|j                  dt                     }|j                  | d       }|rt	        j
                  |      }n| j                  d      t        vrt        dt        |        d} t        | j                  d         }t	        | j                  d      i t        t        t        d      t        d                  d	|j                  |j                  
      }|j!                  |      }	|	s|j                  j"                  r_|j$                  dk(  rP	 |j'                  t)        |j                  j"                  j+                                     }d} |j!                  |      }	|	st        dt        |       | |fS # t,        t.        f$ r}
t        dt        |
       Y d }
~
>d }
~
ww xY w)N/DRr   /zEFont dictionary for %(font_name)s not found; defaulting to Helvetica.)r   r   z
/Helveticar{   r   r   r   TrueTypez/PYPDF1z/Unable to use embedded font for encoding: %(e)s)r   ezText 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   rx   )r	   r   get_inheritedrs   r   from_font_resourceremoveprefixr   r   r(   r   r   r   r   r   r   
can_encode	font_filer   from_truetype_font_filer   get_dataImportErrorr   )r   
annotation	acro_formrx   acro_form_resourcesacro_form_font_resourcesr   rW   r   	encodabler   s              r0   _find_annotation_font_resourcez3TextStreamAppearance._find_annotation_font_resource  s    $($$e%5%78$
 $7#:#:7DTDV#W 044YE**=9D
 %%c*2CC[#'
 )	 1)2H2H2M N++C0 c%*.@.JKL  1 A A!2!C!CD OOD)	 ##--$--:2Ml77@T@T@^@^@g@g@i8jkD )I $ 5I k $ $ $\2 l"#T]eijkkls   AF9 9G$GG$c                   |j                  t        d      t                     j                         }||vr|j	                  | |t        |            }n||   }|rmt        t        |t        j                           j                  t        d      t                     j                         }||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   
get_object_add_to_writerr	   r   	RESOURCESr   )writerr   rW   target_resource_dictpagetarget_fontsfont_resource_referencepage_fonts_resources           r0   &_sync_appearance_stream_font_resourcesz;TextStreamAppearance._sync_appearance_stream_font_resources  s     ,66z'7JL\L^_jjlL(&*&9&99%'# '39&=#"&'7n>V>V9W"X"c"c7#%5%7#jl    33=D+-ACZ>#Jy$9: '&r/   c	                	   t        t        |t        j                           }	t        ddt	        |	d   |	d   z
        t	        |	d   |	d   z
        f      }
|j                  t        j                  |j                  t        j                  d            }|st        d      }n|j                         }|j                  t        j                  d      }|j                  t        j                  d      dk(  ru|t        j                  j                  z  dk(  rUd	j                  |j                  t        j                   g             }|j                  d
g       }t#        |t$              s|g}n|j                  d
d      }g }|j'                  dd      j'                  dd      j'                  dd      }t)        j*                  d|      D cg c]  }|s|	 }}|j-                  |j/                  d      dz
        }t1        |j-                  |j/                  d      dz
              }|j3                  d       dj                  |      }|r|}n|}|dkD  r|}| j5                  ||||      \  }}||k7  r't        |j'                  ||            |t7        d      <   | j9                  ||||j;                  t7        d      t=                     |r|nd      }d}d}|t        j                  j>                  z  rd}|j                  d      }d}|t        j                  j@                  z  rd}|j                  dtB        jD                        }d}tF        jH                  }d|v rFt        t<        |d         j                  d|      }t        t<        |d         j                  d|      }tK        |
||      } | ||||||||||||      }t        jL                  |v rt        t<        |t        jL                           j                  d i       jO                         D ]g  \  }} |d!v r|d"k(  rSd#| vr$t=               | j                         t7        d#      <   tQ        |d$|      | d#   j                         t7        |      <   c| ||<   i |S c c}w )%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.

        r   r
   rl   r#   Nz/Helv 0 Tf 0 gz/Txz/Chr   z/VrK   \z\\(z\()z\)z\sTfr   z/DAr   FTz/MaxLenz/Qz/BSz/Wz/S)r"   r%   r'   r   z/N>   /Filterr6   r4   r   r5   r   r   r   ))r	   r   r   Rectabsr   DArs   r   r   r   FfFTFfBitsComborS   Optr   listreplacererO   popr   floatremover   r   r   r   r   Comb	MultilinerC   rD   r   r-   r    APitemsr   )!clsr   r   flattenr   fieldr   user_font_nameuser_font_size
_rectangler"   r   field_flagsrx   r   propfont_propertiesda_font_namerX   r   r   rW   r   r   r   r   r   r%   r'   r;   new_appearance_streamkeyr   s!                                    r0   from_text_annotationz)TextStreamAppearance.from_text_annotation  sm   L /:6T6Y6Y+Z[
#Q3z!}z!}/L+MsS]^_S`cmnocpSpOq$rs	 (55*--MM8;;TB
 "!12B!C!3!>!>!@ ii 9 < <a@		366>%G7>>DDDI99Z556O6S6SUWXYD		$+Ii.&K	99T2&DI ||D&)11#u=EEc5Q -/HHU<N,OXDSW4XX&**?+@+@+F+JK/--o.C.CD.IA.MNO	t$XXo.
&I$IA&I<<Y
T]_cd	4 $,<=O=W=WXdfo=p,qJz%() #&"L"L  E!24D4FGD#
 
299>>>G#	2J299CCCLIIdM$6$67	#))E> 0%,?CCD,WL 0%,?CCD,WL "IL_kl ##!%!!
 *,,
:%z2P2S2S'TUYYZ^`bciik7
U NN,&e+BRBT((*:g+>?IP/1EG^JE'N--/
90EF 27)#.7 %$] Ys   RR)g?)rW   r   rX   r  rY   r  rZ   r  r[   r  r\   z	list[str]r]   r  r^   r  r>   z%tuple[list[tuple[float, str]], float])rx   r&   r   list[str] | NonerW   r   r   r&   rX   r  r   r&   r   boolr   rC   r   r  r   
int | Noner>   r~   )r;   r=   rx   r&   r   r  rW   zFont | Noner   z(DictionaryObject | IndirectObject | Noner   r&   rX   r  r   r&   r   r  r   rC   r   r  r   r  r>   r?   )
r   r&   r   r   r   r   rx   r&   r>   ztuple[str, Font]rr   )r   r   r   r&   rW   r   r   r   r   zPageObject | Noner>   r   )rK   )r   r   r   r   r  r  r   r   r  r   r   r   r  r&   r  r  r>   rH   )r(   r)   r*   r+   rU   rC   rD   r   r8   staticmethodr   r   classmethodr  r@   rA   s   @r0   rH   rH   B   s   " !$J2J2 J2 	J2
 J2 J2 J2 J2 J2 
/J2b !"#0#5#5!%oo $o 	o
 o o o o !o o o 
of +/&* BF "#0#5#5!%Q'Q Q $	Q
 Q @Q Q Q Q Q !Q Q Q 
Qf BB(B (B 	B
 B BH  #'''' ' /	'
  ' 
' '@  ! "Z%Z% Z% 	Z%
 $Z%  Z% %Z% Z% Z% 
Z% Z%r/   rH   )/
__future__r   r  dataclassesr   enumr   ior   typingr   r   r	   _codecsr   _codecs.core_font_metricsr   _fontr   _utilsr   	constantsr   r   r   r   errorsr   genericr   r   r   r   r   r   generic._baser   r   pypdf._writerr   _pager   r   r    r2   rC   rH   r.   r/   r0   <module>r-     s    " 	 !   + + ( 9  # o o !  ?'"!#  + + +L. L"G Z	%/ Z	%r/   