o
     Zh                    @   s4  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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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 m!Z!m"Z" dd
l#m$Z$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/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5 ddl6m7Z8 ddl6m9Z: ddl6m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZC ddl6mDZE ddl6mFZG ddl6mHZI ddl6mJZK ddl6mLZM ddlNmOZO ddlPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZambZbmcZcmdZdmeZemfZfmgZg ddlhmiZimjZj ddlmkZkmlZlmmZmmnZnmoZompZp ddlqmrZr eCs ZtdZuG dd dejvZwd:d ed!exd"eyfd#d$ZzG d%d& d&e"Z{d'eeeyef eye|ee f d"e_fd(d)Z}d*ede[f d+eyd,eee|e|e|f eydf d-e~d.e~d"ecfd/d0Zd1eyd2eey d3eyd4eeyef d5e`d6e|d7e|d"efd8d9ZdS );    N)BytesIOFileIOIOBase)compress)Path)TracebackType)IOAnyCallableDictIterableListOptionalPatternTupleTypeUnioncast   )_default_fonts_space_widthbuild_char_map_from_dict)DocumentInformationPdfDocCommon)EncryptAlgorithm
Encryption)
PageObject)nums_clear_rangenums_insert	nums_next)	PdfReader)StrByteType
StreamType_get_max_pdf_version_header	deprecatedeprecate_no_replacementdeprecation_with_replacementlogger_warning)AnnotationDictionaryAttributes)CatalogAttributes)	CatalogDictionary"FileSpecificationDictionaryEntriesGoToActionArguments	ImageTypeInteractiveFormDictEntriesOutlineFontFlagPageLabelStyleTypFitArgumentsUserAccessPermissions)Core)FieldDictionaryAttributes)PageAttributes)PagesAttributes)TrailerKeys)
PyPdfError)PAGE_FITArrayObjectBooleanObjectByteStringObjectContentStreamDecodedStreamObjectDestinationDictionaryObjectFitFloatObjectIndirectObject
NameObject
NullObjectNumberObject	PdfObjectRectangleObjectStreamObjectTextStringObject
TreeObjectViewerPreferencescreate_string_object
hex_to_rgbis_null_or_none)	PageRangePageRangeSpec)AnnotationSubtypeBorderArrayType
LayoutTypeOutlineItemTypeOutlineTypePagemodeType)XmpInformation   c                   @   s\   e Zd ZdZe Ze Ze Ze Z	e Z
e Ze Ze ZeeB eB ZdS )ObjectDeletionFlagr   N)__name__
__module____qualname__NONEenumautoTEXTLINKSATTACHMENTS
OBJECTS_3DALL_ANNOTATIONSXOBJECT_IMAGESINLINE_IMAGESDRAWING_IMAGESZIMAGES rh   rh   D/var/www/html/lang_env/lib/python3.10/site-packages/pypdf/_writer.pyrY      s    rY      stream	blocksizereturnc                    s4   t  }t fdddD ]}|| q| S )Nc                      s
     S N)readrh   rl   rk   rh   ri   <lambda>   s   
 z#_rolling_checksum.<locals>.<lambda>    )hashlibmd5iterupdate	hexdigest)rk   rl   hashblockrh   rp   ri   _rolling_checksum   s   rz   c                       sT  e Zd ZdZ				ddedeeef dedeeef deded	df
d
dZ	e
d	efddZe
d	efddZe
d	ee fddZejdeeeef  d	dfddZe
d	ee fddZejdee d	dfddZe
d	efddZejded	dfddZdddZdeee  dee dee d	dfdd Ze
d	efd!d"Zejd#eeef d	dfd$d"Zd%ed	efd&d'Zd(eeef d	efd)d*Z d(eeef d%ed	efd+d,Z!	-dd.e"d/ed0e#e d	e"fd1d2Z$dd4ed	dfd5d6Z%d	e&fd7d8Z'	-dd.e"d0e#e d	e"fd9d:Z(	;	-dd.e"d/ed0e#e d	e"fd<d=Z)d(edee*ef d	ee fd>d?Z+	dd@ee, dAee, d	e"fdBdCZ-			;dd@eee,e.j/f  dAeee,e.j/f  d/ed	e"fdDdEZ0e
d	ede1e2e3f f fdFdGZ4e4jdHedee1e"f d	dfdIdGZ4dJed	dfdKdLZ5dMedNeeef d	dfdOdPZ6	ddQedRee7e"gdf  d	dfdSdTZ8		UddVedWedXedYe,d	df
dZd[Z9e:;d;Z<e<d3fd.ee"e=e" df d\e>eeee=e e?eee,f f f d]e:j;d^ee d	df
d_d`Z@	dd.ee" d	e=e fdadbZAdQed	dfdcddZB	ddQedRee7e"gdf  d	dfdedfZCd	e3fdgdhZDddidjZEdd3eFfddkdledmee dnedoeGdpee d	dfdqdrZHdseId	dfdtduZJdseeef d	e?eeKeL f fdvdwZMd	e=e fdxdyZNdseId	dfdzd{ZOdseId	e?e=e e=e f fd|d}ZPdseId~e=e de=e d	efddZQdseIded	dfddZRe
d	eeS f fddZTeTjdeeeSee>eLeLf f  d	dfddZTde>eeLf d	dfddZU	3	3ddeded	dfddZVdeeWeXeeYeeZee[e2e*f
 d	dfddZ\dNed	efddZ]d%ed	efddZ^d	e_fddZ`d	eWfddZae
d	eWfddZb			3ddeee"e_f dede_ef dede_ef ded	ef
ddZc			3ddeddede_ef dede_ef ded	ef
ddZedddddefd3fdedede"eef dede_ef dede_ef deee?e,e,e,f ef  dededegded	efddZhdddZide2deeeWf d	dfddZjded	efddZkdeded	efddZldddZmdeeene#en f  d	dfddZod.eee"ef dee#e  d	dfddZp	dd.ee"ef deeqe#eq f dee>eeLf  d	dfddZresjtfdesd	dfddZuddee=e  d	dfddńZv	ddededewdeeW d	df
ddʄZxdZyd	eez fdd̈́Z{deeZezf d	dfddЄZ|dezd	dfdd҄Z}e
d	eez fddԄZ~e~jdezd	dfddԄZ~dZd	ee fdd؄Ze
d	ee fddڄZejded	dfddڄZdeee"f dWe>eeLf d	efddބZd.ee"ef d	e"fddZdeeeef d	e?eee f fddZ			3	d deeeef deedee?eef e?eeef e=e f dedee?eef e?eeef e=e e=e" f dedeee=e e?edf f  d	dfddZ			3	-d!dee deeeef dee deeee=e" f  dedeee=e e?edf f  d	dfddZdede>ee"f dQed	efddZdeeeL ef de>ee"f dQed	dfddZd.edee"e*f de>ee"f dQed	ee fddZdeee=e df d.e"de>ee"f dQed	e=e1 f
ddZdeLde>ee"f dQed	e=e1 fddZdHe1d	e_fddZ	dde=e1 dee_ef dede_ef d	dfddZddd Z	dde>eeLf dee d	ee=e  fddZ	dde>eeLf dee d	dfddZ	ddQedeef d	dfddZ			;ddeded	ee d
ee dee d	dfddZ			;ddeded	ee d
ee dee d	dfddZ		ddede#e f dede#e f d	e>eeLf fddZ  ZS ("  	PdfWritera  
    Write a PDF file out, given pages produced by another class or through
    cloning a PDF file during initialization.

    Typically data is added from a :class:`PdfReader<pypdf.PdfReader>`.

    Args:
        clone_from: identical to fileobj (for compatibility)

        incremental: If true, loads the document and set the PdfWriter in incremental mode.

            When writing incrementally, the original document is written first and new/modified
            content is appended. To be used for signed document/forms to keep signature valid.

        full: If true, loads all the objects (always full if incremental = True).
            This parameter may allow loading large PDFs.

     NFfileobj
clone_fromincrementalfullrm   c                 C   s  |p|| _ 	 g | _	 g | _	 i | _	 i | _	 |  	 d | _	 | j rbt|ttfrCt	|d}t
|d}W d    n1 s>w   Y  t|t
rLt|}t|tsUtd|| _|j | _d| _nd| _| ttdtdi| _dtd ttttt t
f d	td ttttt t
f d
td ttttt t
f fdd}|||}|| _d| _d| _d| _t }|tt j!tdtt j"t#dtt j$t% i g | _&d | _'d | _(|d urt|tst|}| )| d| _n$| || _*t | _+| j+tt j!tt,j-tt,j.| j*i | | j+ |r|sd| _ t| jt/rHt| jd t0r1t1| jd 2 | jd< t| jd t0rJt1| jd 2 | jd< d S d S d S )Nrbz!Invalid type for incremental modeTs   %PDF-1.3z	/ProducerZpypdfr}   r~   rm   c                 S   s   t | ttttfr| dks|d ur|S d}t | ttfr1tt|  r/tt|  jdkr1d}t | ttfrL| 	 }| 
dddkrFd}| 
|d |rP| }|S )Nr|   Tr   F   )
isinstancestrr   r   r   existsstatst_sizer   tellseek)r}   r~   Zcloningtrh   rh   ri   _get_clone_from   s"   z+PdfWriter.__init__.<locals>._get_clone_fromr|   F/Pagesr   r   )3r   _objects_original_hash_idnum_hash_id_translated_IDr   r   r   openr   ro   r   r7   _reader
pdf_headerencode_headerZ	_readonly_add_objectr?   rC   rL   	_info_objr   r   r	   temp_fileobjr}   _with_as_usage_clonedrv   PATYPECOUNTrE   KIDSr9   flattened_pages_encryption_encrypt_entryclone_document_from_reader_pages_root_objectCOZCATALOGZPAGESlistrI   r;   Zget_original_bytes)selfr}   r~   r   r   fr   pagesrh   rh   ri   __init__   s   






zPdfWriter.__init__c                 C      dS )z
        Read-only boolean property showing whether this PDF file is encrypted.

        Note that this property, if true, will remain true even after the
        :meth:`decrypt()<pypdf.PdfReader.decrypt>` method is called.
        Frh   r   rh   rh   ri   is_encrypted*  s   zPdfWriter.is_encryptedc                 C   s   | j S )zw
        Provide direct access to PDF Structure.

        Note:
            Recommended only for read access.

        )r   r   rh   rh   ri   root_object4  s   	zPdfWriter.root_objectc                 C   s   | j du rdS tt| j  S )z
        Provide access to "/Info". Standardized with PdfReader.

        Returns:
            /Info Dictionary; None if the entry does not exist

        N)r   r   r?   
get_objectr   rh   rh   ri   _info?  s
   
zPdfWriter._infovaluec              	   C   s   |d u r!zd | j | jjjd < W n ttfy   Y nw d | _d S | jd u r-| t | _tt| j	 }|
  |tt|	  d S )Nr   )r   r   indirect_referenceidnumKeyErrorAttributeErrorr   r?   r   r   clearrv   )r   r   objrh   rh   ri   r   N  s   

c                 C   s   t t| jjS )(XMP (Extensible Metadata Platform) data.)r   rW   r   xmp_metadatar   rh   rh   ri   r   ]  s   zPdfWriter.xmp_metadatac                 C   s8   |du rd| j v r| j d= | j jS || j td< | j jS )r   Nz	/Metadata)r   rC   r   r   r   rh   rh   ri   r   b  s   
c                 C   s   t dd | jS Nwith_as_usagez6.0r$   r   r   rh   rh   ri   r   m  s   
zPdfWriter.with_as_usagec                 C   s   t dd || _d S r   r   r   rh   rh   ri   r   r  s   

c                 C   s*   | j }| j}|   || _ d| _|| _| S )z*Store how writer is initialized by 'with'.T)r   r   r   r   r}   )r   cr   rh   rh   ri   	__enter__w  s   zPdfWriter.__enter__exc_typeexc	tracebackc                 C   s$   | j r| js| | j  dS dS dS )zWrite data to the fileobj.N)r}   r   write)r   r   r   r   rh   rh   ri   __exit__  s   zPdfWriter.__exit__c                 C   s
   | j  S )aL  
        Read/Write property of the PDF header that is written.

        This should be something like ``'%PDF-1.5'``. It is recommended to set
        the lowest version that supports all features which are used within the
        PDF file.

        Note: `pdf_header` returns a string but accepts bytes or str for writing
        )r   decoder   rh   rh   ri   r     s   
zPdfWriter.pdf_header
new_headerc                 C   s   t |tr	| }|| _d S rn   )r   r   r   r   )r   r   rh   rh   ri   r     s   

r   c                 C   s   t |dd d ur|jj| kr|jS t|tr/t|tjd ttfr/| 	|tj |t
tj< | j| tt| jd| |_|jS )Nr   r   )getattrr   pdfr   r?   getPGZCONTENTSr9   r   rC   r   appendrB   len)r   r   rh   rh   ri   r     s   zPdfWriter._add_objectr   c                 C   sP   t |tr| j|d  }n|j| krtd| j|jd  }|d us&J d|S )Nr   PDF must be selfmypy)r   intr   r   
ValueErrorr   r   r   r   rh   rh   ri   r     s   

zPdfWriter.get_objectc                 C   s   t |tr|j| krtd|j}| j|d  jj}t|dd d ur-|jj| kr-|	| }|| j|d < t||| |_t |t
sDJ d|S )Nr   r   r   r   )r   rB   r   r   r   r   r   Z
generationr   clonerF   )r   r   r   genrh   rh   ri   _replace_object  s   


zPdfWriter._replace_objectrh   pageindexexcluded_keysc           	      C   s  t |tr|tjd tjkrtd| jd usJ d|}t	|}|tj
dg7 }z| jt|jj |jj= W n	 ty@   Y nw td|| d| }|jd ur]|jj}t| j|| _| |\}}|j|ttj
< |dkrtt|tj ||j | j|| ntt|tj |j | j| d}t|stt| }ttt|tj  d |ttj < |tj
d }|d7 }|dkrt!d	t|r|S )
NzInvalid page objectfor mypyz/StructParentsr   Fr   r   i  zToo many recursive calls!)"r   r   r   r   r   r   ZPAGEr   r   r   PARENTr   idr   r   r   	Exceptionr   r   r   r   r"   Z_get_page_in_noderC   r9   r   insertr   rN   r?   rE   r   r   r7   )	r   r   r   r   Zpage_orgothernodeidxrecurserh   rh   ri   	_add_page  sH   
"zPdfWriter._add_pageTstatec              
   C   s   z't j| jvr| t | jtt j< ttj}t|t	t| jt j |< W dS  t
yE } ztd| d| t W Y d}~dS d}~ww )a  
        Sets the "NeedAppearances" flag in the PDF writer.

        The "NeedAppearances" flag indicates whether the appearance dictionary
        for form fields should be automatically generated by the PDF viewer or
        if the embedded appearance should be used.

        Args:
            state: The actual value of the NeedAppearances flag.

        Returns:
            None

        zset_need_appearances_writer(z
) catch : N)r)   	ACRO_FORMr   r   r?   rC   r-   ZNeedAppearancesr:   r   r   r&   rZ   )r   r   Zneed_appearancesr   rh   rh   ri   set_need_appearances_writer  s"   

z%PdfWriter.set_need_appearances_writerc                 C   s    t  }| || jttj< |S rn   )rK   r   r   rC   r)   ZVIEWER_PREFERENCES)r   orh   rh   ri   create_viewer_preferences  s   z#PdfWriter.create_viewer_preferencesc                 C   s&   | j dus	J d| |t| j |S )a  
        Add a page to this PDF file.

        Recommended for advanced usage including the adequate excluded_keys.

        The page is usually acquired from a :class:`PdfReader<pypdf.PdfReader>`
        instance.

        Args:
            page: The page to add to the document. Should be
                an instance of :class:`PageObject<pypdf._page.PageObject>`
            excluded_keys:

        Returns:
            The added PageObject.

        Nr   )r   r   r   )r   r   r   rh   rh   ri   add_page&  s   zPdfWriter.add_pager   c                 C   s`   | j dus	J d|dk rt| j | }|dk rtd|t| j kr)| ||S | |||S )a]  
        Insert a page in this PDF file. The page is usually acquired from a
        :class:`PdfReader<pypdf.PdfReader>` instance.

        Args:
            page: The page to add to the document.
            index: Position at which the page will be inserted.
            excluded_keys:

        Returns:
            The added PageObject.

        Nr   r   zInvalid index value)r   r   r   r   r   )r   r   r   r   rh   rh   ri   insert_page?  s   zPdfWriter.insert_pagec                 C   sN   t |rdS |dusJ dt|trt|d| }| }t|tr%|jS dS )z
        Generate _page_id2num.

        Args:
            indirect_reference:

        Returns:
            The page number or None

        Nr   r   )rN   r   r   rB   r   r   page_numberr   rh   rh   ri   _get_page_number_by_indirect[  s   

z&PdfWriter._get_page_number_by_indirectwidthheightc                 C   s   t | ||}| |S )a(  
        Append a blank page to this PDF file and return it.

        If no page size is specified, use the size of the last page.

        Args:
            width: The width of the new page expressed in default user
                space units.
            height: The height of the new page expressed in default
                user space units.

        Returns:
            The newly appended page.

        Raises:
            PageSizeNotDefinedError: if width and height are not defined
                and previous page does not exist.

        )r   create_blank_pager   )r   r   r   r   rh   rh   ri   add_blank_pages  s   
zPdfWriter.add_blank_pagec                 C   sT   |du s|du r||   k r| j| }|jj}|jj}t| ||}| || |S )aU  
        Insert a blank page to this PDF file and return it.

        If no page size is specified, use the size of the last page.

        Args:
            width: The width of the new page expressed in default user
                space units.
            height: The height of the new page expressed in default
                user space units.
            index: Position to add the page.

        Returns:
            The newly inserted page.

        Raises:
            PageSizeNotDefinedError: if width and height are not defined
                and previous page does not exist.

        N)Zget_num_pagesr   Zmediaboxr   r   r   r   r   )r   r   r   r   Zoldpager   rh   rh   ri   insert_blank_page  s   
zPdfWriter.insert_blank_pagec                       t  jS rn   )superopen_destinationr   	__class__rh   ri   r     s   zPdfWriter.open_destinationdestc                 C   s   |d u rz| j d= W d S  ty   Y d S w t|tr&t|| j td< d S t|tr5|j| j td< d S t|trQtd|j	d urD|j	nt
 tj| j td< d S d S )Nz/OpenActionZOpening)r   r   r   r   rI   rC   r>   
dest_arrayr   r   rD   r8   )r   r   rh   rh   ri   r     s*   




javascriptc              	   C   s   d| j vrt | j ttj< tt| j tj }d|vr(ttdt i|td< tttt|d d }t }|ttj	tdtdtdtdt
| i |ttt  || | dS )a%  
        Add JavaScript which will launch upon opening this PDF.

        Args:
            javascript: Your JavaScript.

        >>> output.add_js("this.print({bUI:true,bSilent:false,bShrinkToFit:true});")
        # Example: This will launch the print window when the PDF is opened.

        /Namesz/JavaScriptz/Action/Sz/JSN)r   r?   rC   CANAMESr   r9   rv   r   r   rI   r   rL   r   uuiduuid4r   )r   r   namesZjs_listjsrh   rh   ri   add_js  s&   
	zPdfWriter.add_jsfilenamedatac                 C   s>  t |tr
|d}t }|| |ttjtdi t	 }|td| 
|i t	 }|ttjtdttjt|ttj|i tj| jvrZ| 
t	 | jttj< dtt	| jtj vrt	ttjt i}| 
|tt	| jtj td< ntt	tt	| jtj d }tt|tj t||g dS )a  
        Embed a file inside the PDF.

        Reference:
        https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf
        Section 7.11.3

        Args:
            filename: The filename to display.
            data: The data in the file.

        zlatin-1z/EmbeddedFile/Fz	/Filespecz/EmbeddedFilesN)r   r   r   r=   set_datarv   rC   r   r   r?   r   r*   FrL   ZEFr   r   r   r   r9   extend)r   r  r  Z
file_entryZef_entryZfilespecZembedded_files_names_dictionaryrh   rh   ri   add_attachment  sF   





zPdfWriter.add_attachmentreaderafter_page_appendc                 C   s@   t |j}t|D ]}|j| }| |}t|r|| q	dS )a  
        Copy pages from reader to writer. Includes an optional callback
        parameter which is invoked after pages are appended to the writer.

        ``append`` should be preferred.

        Args:
            reader: a PdfReader object from which to copy page
                annotations to this writer object. The writer's annots
                will then be updated.
            after_page_append:
                Callback function that is invoked after each page is appended to
                the writer. Signature includes a reference to the appended page
                (delegates to append_pages_from_reader). The single parameter of
                the callback is a reference to the page just appended to the
                document.

        N)r   r   ranger   callable)r   r
  r  Zreader_num_pagesZreader_page_numberZreader_pageZwriter_pagerh   rh   ri   append_pages_from_readerH  s   


z"PdfWriter.append_pages_from_readerr   field
annotation	font_name	font_sizec                    s  t t|tj }tddt|d |d  t|d |d  f}|tjt t| jt	j
 tjd }|d u r<td}n| }|ddddd}d	d
 |D }|r`|||dd < n	||dd  }|dkro|n
t||dd  }	|	dkr|tjdtjj@ rt}	n|jd }	t|	||dd < d|}|jd |	 }
t tt t|dt t| jt	j
 dt  }|dt  }||vr|tvrt tttf t t| jt	j
 di }| dt  }||d }t|sTt t| }td|\}} }z|d= W n
 ty   Y nw t  tr/ fdd|! D }n0dd  ! D }dd  ! D }|! D ]\}}|||||< qEnt"d| dt# i }|tjd}|tj$ddkr|tjj%@ dkrd|tj&g }|dg }t |t's|g}n|dd}g }|dddddd}t(||||||	|
}t)*t+d t+d!t+d"t+d#t+d$|d%t,|d&di}tj-|v rt t|tj- d'i ! D ]\}}|d(vr|||< q|d urtt+dtt+|t.|d)|ii|t+d*< tj-|vr$tt+d'| /|i|t+tj-< d S d't t|tj- vrB| /|t t|t+tj- t+d'< d S |tj- d' j0j1}|| j2|d < t3|d| |_0d S )+Nr   r      r   z/Helv 0 Tf 0 g
 c                 S   s   g | ]}|d kr|qS )r|   rh   .0xrh   rh   ri   
<listcomp>  s    z6PdfWriter._update_field_annotation.<locals>.<listcomp>ZTfz/DR/Font   r   c                    s   i | ]
\}}||  qS rh   )r   r  kvZfont_encodingrh   ri   
<dictcomp>  s    z6PdfWriter._update_field_annotation.<locals>.<dictcomp>c                 S      i | ]
\}}|t |fqS rh   bytesr  rh   rh   ri   r!        c                 S   r"  rh   r#  r  rh   rh   ri   r!    r%  zFont dictionary for z not found./Tx/Ch/Vr|   \z\\(z\()z\)/Type/XObject/Subtype/Form/BBox__streamdata__/Length/N>   r.  r,  r0  r2  /Filterr   
/Resources)4r   rG   AARectabsZget_inheritedZDAr?   r   r)   r   r   rI   r   replacesplitr   floatFAFfFfBits	Multiline DEFAULT_FONT_HEIGHT_IN_MULTILINEr   r   joinr   r   r	   rN   r   r   r   itemsr&   rZ   FTZComboZOptr   generate_appearance_streamr=   initialize_from_dictionaryrC   r;   APr   r   r   r   r   rB   )r   r  r  r  r  Z_rctrctdaZfont_propertiesfont_heighty_offsetZdrZfont_resZfont_subtype_Zfont_mapfont_full_revZfont_encoding_revkeyr   Zfield_flagstxtsel	ap_streamdctr  r  nrh   r   ri   _update_field_annotationh  s   0







&	$

z"PdfWriter._update_field_annotationfieldsflagsauto_regeneratec              	   C   s  t j| jvr
tdtt| jt j }tj|vrtdt|t	r&| 
| |du r/t| j}t|trH|D ]}tj|v rE| |||d q6dS tj|vrTtdt dS |tj D ]}tt| }|dddkrkqYd|v rvd	|v rv|}n
|tjt  }| D ]\}	}
| ||	ks|d	d|	ksq|ddd
krd|v r|d= |rt||ttj< t|
trtdd |
D }||ttj< nt|
trt|
d |ttj< n	t|
|ttj< |tjdv rt|
}||tt j! td vrtd}||tt j"< ||ttj< q|tjdks"|tjd
kr<t|
tr5| #|||
d |
d  q| #|| q|tjdkrJtdt qqYdS )a  
        Update the form field values for a given page from a fields dictionary.

        Copy field texts and values from fields to page.
        If the field links to a parent object, add the information to the parent.

        Args:
            page: `PageObject` - references **PDF writer's page** where the
                annotations and field data will be updated.
                `List[Pageobject]` - provides list of pages to be processed.
                `None` - all pages.
            fields: a Python dictionary of:

                * field names (/T) as keys and text values (/V) as value
                * field names (/T) as keys and list of text values (/V) for multiple choice list
                * field names (/T) as keys and tuple of:
                    * text values (/V)
                    * font id (e.g. /F1, the font id must exist)
                    * font size (0 for autosize)

            flags: A set of flags from :class:`~pypdf.constants.FieldDictionaryAttributes.FfBits`.

            auto_regenerate: Set/unset the need_appearances flag;
                the flag is unchanged if auto_regenerate is None.

        z2No /AcroForm dictionary in PDF of PdfWriter Objectz0No /Fields dictionary in PDF of PdfWriter ObjectNz No fields to update on this pager.  r|   /Widget/FT/Tr'  /Ic                 s       | ]}t |V  qd S rn   )rI   r  r  rh   rh   ri   	<genexpr>J      z:PdfWriter.update_page_form_field_values.<locals>.<genexpr>r   z/Btnr3  z/Offr&  r   r   z/Sigz#Signature forms not implemented yet)$r)   r   r   r7   r   r?   r-   Fieldsr   boolr   r   r   r   ANNOTSupdate_page_form_field_valuesr&   rZ   r   r   r   rB  Z_get_qualified_field_namerE   rC   r<  r=  r9   VtuplerI   rC  r6  rF  ZASrS  )r   r   rT  rU  rV  afpr  Zparent_annotationr  r   lstr  rh   rh   ri   rb    s   !










z'PdfWriter.update_page_form_field_valuesc           
      C   sD  g }|du r| j D ]	}|| |7 }q	|S ztt| jtj }W n ty4   t }|| jttj< Y nw z
tt	|t
j }W n tyR   t	 }||tt
j< Y nw d|vrY|S tt	|d }t|D ];\}}t|t}	tt| }|dddkrd|v rd|jv r|j|v rqd|	s| |||< ||j || qd|S )a1  
        Parse annotations within the page looking for orphan fields and
        reattach then into the Fields Structure.

        Args:
            page: page to analyze.
                  If none is provided, all pages will be analyzed.

        Returns:
            list of reattached fields.

        N/Annotsr.  r|   rW  rX  r   )r   reattach_fieldsr   r?   r   r)   r   r   rC   r9   r-   r_  	enumerater   rB   r   r   __dict__r   r   r   )
r   r   rg  rf  re  rT  annotationsr   r  Zis_indirectrh   rh   ri   ri  j  sB   




zPdfWriter.reattach_fieldsc                 C   sB  d| _ | jr2dgtt|jd d  | _tt| jD ]}||d }|dur0|	| | j|< qn| j
  |j| | _| jd| _t| jtt|jd ksTJ | jr`dd | jD | _|   | jduskJ | jD ]}| tt|jj| | js| j|td< qn| jstdd | jD tt| j td	< dS dS )
a  
        Copy the reader document root to the writer and all sub-elements,
        including pages, threads, outlines,... For partial insertion, ``append``
        should be considered.

        Args:
            reader: PdfReader from which the document root should be copied.

        N/Sizer   r   c                 S   s    g | ]}|d ur|  ndqS Nr   )hash_bin)r  r   rh   rh   ri   r    s    z8PdfWriter.clone_reader_document_root.<locals>.<listcomp>/Parentc                 S   s   g | ]}|j qS rh   )r   )r  rf  rh   rh   ri   r    s    /Kids)r   r   r   r   trailerr   r  r   r   Z	replicater   r   r   r   Zraw_getr   r   _flattenr   r   rB   r   r   rC   r9   r?   )r   r
  ir   rf  rh   rh   ri   clone_reader_document_root  s<   


z$PdfWriter.clone_reader_document_rootc                 C   s   |  | |j}| jr1|dur0tt|| j| _t| jt	s#J d| j
 | j| jjjd < n|durB| t	tt	| | _ztt|j| | _W n	 tyW   Y nw t|rrtttt	| j d D ]
}||  qidS dS )a{  
        Create a copy (clone) of a document from a PDF file reader cloning
        section '/Root' and '/Info' and '/ID' of the pdf.

        Args:
            reader: PDF file reader instance from which the clone
                should be created.
            after_page_append:
                Callback function that is invoked after each page is appended to
                the writer. Signature includes a reference to the appended page
                (delegates to append_pages_from_reader). The single parameter of
                the callback is a reference to the page just appended to the
                document.

        Nr   r   rq  )ru  r   r   r   rB   r   r   r   r   r?   ro  r   r   r   r   r9   r   r   r  r   )r   r
  r  infr   rh   rh   ri   r     s:   
z$PdfWriter.clone_document_from_readerc                 C   s,   t  }| | |d tt|dS )Nr   utf8)r   _write_pdf_structurer   r;   rz   r   )r   rk   rh   rh   ri   _compute_document_identifier  s   

z&PdfWriter._compute_document_identifierc                 C   s8   | j r| j d }|  }n|  }|}t||f| _ dS )u"  
        Generate an identifier for the PDF that will be written.

        The only point of this is ensuring uniqueness. Reproducibility is not
        required.
        When a file is first written, both identifiers shall be set to the same value.
        If both identifiers match when a file reference is resolved, it is very
        likely that the correct and unchanged file has been found. If only the first
        identifier matches, a different version of the correct file has been found.
        see §14.4 "File Identifiers".
        r   N)r   ry  r9   )r   Zid1Zid2rh   rh   ri   generate_file_identifiers  s   

z#PdfWriter.generate_file_identifiers)	algorithmuser_passwordowner_password
use_128bitpermissions_flagr{  c                C   s   |du r|}|dur%zt t|dd}W n ty$   td| dw tj}|s-tj}|   | js6J t	
||| jd | _| j||}| jrb| jjdusSJ | jj|_|| j|jjd < n| | || _dS )a  
        Encrypt this PDF file with the PDF Standard encryption handler.

        Args:
            user_password: The password which allows for opening
                and reading the PDF file with the restrictions provided.
            owner_password: The password which allows for
                opening the PDF files without any restrictions. By default,
                the owner password is the same as the user password.
            use_128bit: flag as to whether to use 128bit
                encryption. When false, 40bit encryption will be used.
                By default, this flag is on.
            permissions_flag: permissions as described in
                Table 3.20 of the PDF 1.7 specification. A bit value of 1 means
                the permission is granted.
                Hence an integer value of -1 will set all flags.
                Bit position 3 is for printing, 4 is for modifying content,
                5 and 6 control annotations, 9 for form fields,
                10 for extraction of text and graphics.
            algorithm: encrypt algorithm. Values may be one of "RC4-40", "RC4-128",
                "AES-128", "AES-256-R5", "AES-256". If it is valid,
                `use_128bit` will be ignored.

        N-rK  zAlgorithm 'z' NOT supportedr   r   )r   r   r9  r   r   ZRC4_128ZRC4_40rz  r   r   maker   Zwrite_entryr   r   r   r   r   )r   r|  r}  r~  r  r{  algentryrh   rh   ri   encrypt  s*   !



zPdfWriter.encryptrk   c                 C   s   t |drd|jvrtd|j dt | jr9| jjd |	| jj
d t|  dkr7| | d S d S | |\}}| |||}| || d S )NmodebzFile <zH> to write to is not in binary mode. It may not be written to correctly.r   r   )hasattrr  r&   namerZ   r   r   rk   r   r   ro   r   list_objects_in_increment_write_incrementrx  _write_xref_table_write_trailer)r   rk   object_positionsfree_objectsxref_locationrh   rh   ri   write_streamH  s    
zPdfWriter.write_streamc                 C   sf   d}|dkrt d|dt|ttfrt|d}d}| | |r+|  ||fS |  ||fS )a  
        Write the collection of pages added to this object out as a PDF file.

        Args:
            stream: An object to write the file to. The object can support
                the write method and the tell method, similar to a file object, or
                be a file path, just like the fileobj, just named it stream to keep
                existing workflow.

        Returns:
            A tuple (bool, IO).

        Fr|   zOutput(stream=z) is empty.wbT)r   r   r   r   r   r  closeflush)r   rk   Zmy_filerh   rh   ri   r   `  s   

zPdfWriter.writec                    s$   t j  fddtjD S )a  
        For analysis or debugging.
        Provides the list of new or modified objects that will be written
        in the increment.
        Deleted objects will not be freed but will become orphans.

        Returns:
            List of new or modified IndirectObjects

        c                    s>   g | ]\}}|d ur| ks|  j| krtt|jqS rn   )ro  r   r   rB   r   )r  rt  r   original_hash_countr   rh   ri   r    s    
z7PdfWriter.list_objects_in_increment.<locals>.<listcomp>)r   r   rj  r   r   rh   r  ri   r    s   
z#PdfWriter.list_objects_in_incrementc                 C   s\  i }g }d}d}t | j}t| jD ]T\}}|d urf||ks'| | j| krf|d }	t|ts4J d| ||	< ||	 d	  	 |
| |d |	|krb|dkr`|||| g |	}|	d }q|dksoJ d|||| g | }
t | jd }|| d		  td
tdtdt|d td| jjtdtdtdtdd |D tdttdtdtdgddi}| jd ur| jjjd t | jkstt| j | j| jjjd  kr| jj|ttj< t| jj|ttj< | jr| j|ttj< t|}|ddd |  D  |
| |d|
 d	  d S )Nr   r   r    0 obj
   
endobj
r   zfor pytest onlyz 0 objr,  z/XRefrm  z/Rootr4  z/FlateDecodez/Indexc                 S   s   g | ]}|D ]}t |qqS rh   rE   )r  Z_suZ_itrh   rh   ri   r        z.PdfWriter._write_increment.<locals>.<listcomp>z/W   r1  rr   c                 S   s   g | ]
}t d d|dqS )s   >BIBr   r   )structpack)r  _posrh   rh   ri   r    r%  
startxref

%%EOF
)!r   r   rj  r   ro  r   rF   r   r   r   write_to_streamr   rC   rE   r   r   r9   r   r   r   rB   TKINFOr   Z
_startxrefZPREVr   IDrH   rE  r  rA  values)r   rk   r  Zobject_blocksZcurrent_startZcurrent_stopr  rt  r   r   r  Zxr_idZ	init_dataZxrrh   rh   ri   r    s|   






zPdfWriter._write_incrementc                 C   s   g }g }| | j d  | d t| jddD ]>\}}|d urN||  | | d  | jrC|| jkrC| j	||d}|
| | d q|d || q|d ||fS )	N   
s   %
r   )startr  r   r  r   )r   r   r   rj  r   r   r   r   r   Zencrypt_objectr  )r   rk   r  r  r   r   rh   rh   ri   rx    s    



zPdfWriter._write_pdf_structurer  r  c                 C   s   |  }|d |dt| jd  d  ||d dddd	d
  d}|D ]+}|dkrD||dddd	d  q.||| dddd	d
  |d7 }q.|S )Ns   xref
0 r   r  r   z0>10r  i  z0>5z f 
z n 
)r   r   r   r   r   )r   rk   r  r  r  Zfree_idxoffsetrh   rh   ri   r    s   
 " "
zPdfWriter._write_xref_tabler  c                 C   s   | d tttjtt| jd ttj| j	j
i}| jdur*| jj
|ttj< | jdur7| j|ttj< | jrC| jj
|ttj< || | d| d  dS )z
        Write the PDF trailer to the stream.

        To quote the PDF specification:
            [The] trailer [gives] the location of the cross-reference table and
            of certain special objects within the body of the file.
        s   trailer
r   Nr  r  )r   r?   rC   r  ZSIZErE   r   r   ROOTr   r   r   r  r   r  r   ZENCRYPTr  r   )r   rk   r  rr  rh   rh   ri   r    s   



zPdfWriter._write_trailerc                    r   )a  
        Retrieve/set the PDF file's document information dictionary, if it exists.

        Args:
            value: dict with the entries to be set. if None : remove the /Info entry from the pdf.

        Note that some PDF files use (XMP) metadata streams instead of document
        information dictionaries, and these metadata streams will not be
        accessed by this function, but by :meth:`~xmp_metadata`.

        )r   metadatar   r   rh   ri   r    s   zPdfWriter.metadatac                 C   s4   |d u r	d | _ d S | j d ur| j   | | d S rn   )r   r   add_metadatar   rh   rh   ri   r  *  s
   


infosc                 C   sz   i }t |trtt| }t| D ]\}}t |tr!| }tt||t	|< q| j
du r5t | _
| j
| dS )z
        Add custom metadata to the output.

        Args:
            infos: a Python dictionary where each key is a field
                and each value is your new metadata.

        N)r   rF   r   r?   r   r   rB  rL   r   rC   r   rv   )r   r  argsrM  r   rh   rh   ri   r  7  s   	


zPdfWriter.add_metadataremove_identicalsremove_orphansc                    s  dt dtttf ddf fddi | _dgt| j  t| jD ]=\}}t|r+q"|dus3J dt|j	ts;J |
 }|rW|| jv rW| j| d	 |j	 d| j|< q"|j	g f| j|< q"d
d | j D }i }| D ]\}}	|t|	|ft|	  qp| jD ]}t|ttfr|| qd | jj	jd	 < d | jj	jd	 < zd | jj	jd	 < W n	 ty   Y nw ttt| j D ]}
d| j|
< qdS )aE  
        Parse the PDF file and merge objects that have the same hash.
        This will make objects common to multiple pages.
        Recommended to be used just before writing output.

        Args:
            remove_identicals: Remove identical objects.
            remove_orphans: Remove unreferenced objects.

        r   crossrefrm   Nc                    s   t | tr
|  }nt | trt| }nd S t | ttfsJ |D ]!\}}t |tr<d |jd < ||v r;|| | |< q!	 || q!d S )NFr   )r   r?   rB  r9   rj  rB   r   )r   r  Zkey_valr  r  Zorphansreplace_in_objrh   ri   r  [  s   




z<PdfWriter.compress_identical_objects.<locals>.replace_in_objTr   r   c                 S   s*   i | ]}t |d  dkr|d |d  qS )r   r   r   r\  rh   rh   ri   r!    s   * z8PdfWriter.compress_identical_objects.<locals>.<dictcomp>F)rF   r   rB   r   r   r   rj  rN   r   r   
hash_valuer   r  rB  rv   zipr?   r9   r   r   r   r   r   r   r  )r   r  r  r   r   hZcnvZcnv_revr  r  rt  rh   r  ri   compress_identical_objectsK  sJ   


z$PdfWriter.compress_identical_objectsrootc                 C   s   t d dS )a  
        Resolving any circular references to Page objects.

        Circular references to Page objects can arise when objects such as
        annotations refer to their associated page. If these references are not
        properly handled, the PDF file will contain multiple copies of the same
        Page object. To address this problem, Page objects store their original
        object reference number. This method adds the reference number of any
        circularly referenced Page objects to an external reference map. This
        ensures that self-referencing trees reference the correct new object
        location, rather than copying in a new copy of the Page object.

        Args:
            root: The root of the PDF object tree to sweep.

        zb_sweep_indirect_references has been removed, please report to dev team if this warning is observedN)r#   )r   r  rh   rh   ri   _sweep_indirect_references  s   z$PdfWriter._sweep_indirect_referencesc                 C   s   t d tdd| S )a  
        Resolves an indirect object to an indirect object in this PDF file.

        If the input indirect object already belongs to this PDF file, it is
        returned directly. Otherwise, the object is retrieved from the input
        object's PDF file using the object's ID number and generation number. If
        the object cannot be found, a warning is logged and a `NullObject` is
        returned.

        If the object is not already in this PDF file, it is added to the file's
        list of objects and assigned a new ID number and generation number of 0.
        The hash value of the object is then added to the `_idnum_hash`
        dictionary, with the corresponding `IndirectObject` reference as the
        value.

        Args:
            data: The `IndirectObject` to resolve.

        Returns:
            The resolved `IndirectObject` in this PDF file.

        Raises:
            ValueError: If the input stream is closed.

        z`_resolve_indirect_object has been removed, please report to dev team if this warning is observedr   )r#   rB   )r   r  rh   rh   ri   _resolve_indirect_object  s   z"PdfWriter._resolve_indirect_objectc                 C   s0   | j |d }t|d| }| |ksJ |S Nr   r   )r   r   rB   r   )r   r   r   refrh   rh   ri   get_reference  s   zPdfWriter.get_referencec                 C   s   t j| jv r:tt| jt j }t|ts"t|}| |jj| |}| j	
|d }t|d| }| |ks8J |S t }|i  | |}|| jtt j< |S r  )r   OUTLINESr   r   rJ   r   r   r   r   r   r   rB   r   rv   r   rC   )r   outliner   r   Zoutline_refrh   rh   ri   get_outline_root  s   


zPdfWriter.get_outline_rootc                 C   s<   t j| jv rtt| jt j }|S t }|| jtt j< |S )u  
        The list of threads.

        See §12.4.3 of the PDF 1.7 or PDF 2.0 specification.

        Returns:
            An array (possibly empty) of Dictionaries with an ``/F`` key,
            and optionally information about the thread in ``/I`` or ``/Metadata`` keys.

        )r   ZTHREADSr   r   r9   rC   )r   threadsrh   rh   ri   get_threads_root  s   zPdfWriter.get_threads_rootc                 C      |   S )u  
        Read-only property for the list of threads.

        See §12.4.3 of the PDF 1.7 or PDF 2.0 specification.

        Each element is a dictionary with an ``/F`` key, and optionally
        information about the thread in ``/I`` or ``/Metadata`` keys.
        )r  r   rh   rh   ri   r    s   
zPdfWriter.threadspage_destinationparentbeforeis_openc                 C   s   t t| }t|tr| td|j t t|jt	
 S |d u r'|  }t||td< t t| }| |}|d urB|j}|||| |rL|jndd  d|vr]td|td< |S )Nzpage #z
/%is_open%c                 S   r   rn  rh   )r  yrh   rh   ri   rq   1  s    z8PdfWriter.add_outline_item_destination.<locals>.<lambda>z/Countr   )r   r   r   r   add_outline_item_destinationr>   r   rB   r   r@   fitr  r:   rC   rJ   r   insert_childZinc_parent_counter_outlinerE   )r   r  r  r  r  page_destination_refrh   rh   ri   r    s6   



z&PdfWriter.add_outline_item_destinationoutline_itemc                 C   s"   t  }|| 	 | ||||S rn   )rJ   rv   r  )r   r  r  r  r  Zoutline_item_objectrh   rh   ri   add_outline_item_dict8  s   
	zPdfWriter.add_outline_item_dicttitler   colorbolditalicr  c
                 C   s4  t |tr|dur|du r|}| j|||d|||||	d	S |du r$d}
n[t |tr,|}n$t |tr5|j}nt |trPz| j| j}W n tyO   t	|}Y nw |du r_t
d| t t }ttd| d ||}| tttj|jttjtdi}
| t|
||||}|du r|  }| ||||	S )a  
        Add an outline item (commonly referred to as a "Bookmark") to the PDF file.

        Args:
            title: Title to use for this outline item.
            page_number: Page number this outline item will point to.
            parent: A reference to a parent outline item to create nested
                outline items.
            before:
            color: Color of the outline item's font as a red, green, blue tuple
                from 0.0 to 1.0 or as a Hex String (#RRGGBB)
            bold: Outline item font is bold
            italic: Outline item font is italic
            fit: The fit of the destination page.

        Returns:
            The added outline item as an indirect object.

        N)r  zcan not find reference of page /z outline item/GoTo)r   r@   add_outline_itemrB   r   r   r   r   
IndexErrorrE   r&   rZ   rD   r>   rC   r   r?   r+   Dr   S_create_outline_itemr  r  )r   r  r   r  r  r  r  r  r  r  
action_refpage_refr   r  rh   rh   ri   r  O  sT   
 


zPdfWriter.add_outline_itemc                 C   s   t d)NzIThis method is not yet implemented. Use :meth:`add_outline_item` instead.)NotImplementedErrorr   rh   rh   ri   add_outline  s   zPdfWriter.add_outlinedestinationc                 C   sn   |   }d}|t|k r,||| k r"||| ||t| d S |d7 }|t|k s|t||g d S )Nr   r   )get_named_dest_rootr   r   rI   r  )r   r  r  Z
named_destrt  rh   rh   ri   add_named_destination_array  s   z%PdfWriter.add_named_destination_arrayc                 C   s&   |  |j}| td|d | |S )NrI   /Title)r   r   r  r   )r   r  r  rh   rh   ri   add_named_destination_object  s
   z&PdfWriter.add_named_destination_objectc                 C   s   |  | jtj | }t }|ttjt	|tt
jtdgttjtdi | |}t|ts9tt|}| || |S )Ni:  r  )r   r   r   r   r?   rv   rC   r+   r  r9   r0   ZFIT_HrE   r  r   r   rI   r   r  )r   r  r   r  r   Zdest_refrh   rh   ri   add_named_destination  s   

	
zPdfWriter.add_named_destinationc                 C   s   | j D ]	}| |tj qdS )z.Remove links and annotations from this output.N)r   remove_objects_from_pagerY   rd   )r   r   rh   rh   ri   remove_links  s   
zPdfWriter.remove_linkssubtypesc                 C   s   | j D ]}| || qdS )aC  
        Remove annotations by annotation subtype.

        Args:
            subtypes: subtype or list of subtypes to be removed.
                Examples are: "/Link", "/FileAttachment", "/Sound",
                "/Movie", "/Screen", ...
                If you want to remove all annotations, use subtypes=None.

        N)r   _remove_annots_from_page)r   r  r   rh   rh   ri   remove_annotations  s   
zPdfWriter.remove_annotationsc                 C   s   t t| }tj|v r_d}|tt t|tj k rat t|tj | }t t| }|d u s8t t|d |v rMt|t	rFt
 | j|jd < |tj |= n|d7 }|tt t|tj k sd S d S d S )Nr   r.  r   )r   r?   r   r   ra  r   r9   r   r   rB   rD   r   r   )r   r   r  rt  anr   rh   rh   ri   r    s   

z"PdfWriter._remove_annots_from_page	to_deletetext_filtersc                    s  t ttfrD ]}|| q	dS t tsJ tj@ r&|dS tj@ r1|dS tj@ r<|dS tj	@ rG|dS g tj
@ rRg dtj@ r[g d	ddtdtt d	tt d
ttttf  ddf
fdd dtdtt dttt tt f f fddt |tst|j}d|v rtt| }|g \}} ||| || dS dS )a  
        Remove objects specified by ``to_delete`` from the given page.

        Args:
            page: Page object to clean up.
            to_delete: Objects to be deleted; can be a ``ObjectDeletionFlag``
                or a list of ObjectDeletionFlag
            text_filters: Properties of text to be deleted, if applicable. Optional.
                This is a Python dictionary with the following properties:

                * font_ids: List of font resource IDs (such as /F1 or /T1_0) to be deleted.

        N)/Link)z/FileAttachmentz/Soundz/Moviez/Screen)z/3D)   w   J   j   M   d   i   Ws   W*   bs   b*   Bs   B*   S   s   fs   f*   F   n   m   l   c   v   y   hs   res   sh)s   Tjs   TJ   '   "contentimagesformsr  rm   c           	         s   d }g }|rt j@ r|dg }d}|t| jk ro| j| \}}|dkr)|d }|dkr2t j@ sE| v sE|dkrdt j@ rd|d |v rdt j@ rZt j@ rQ|rZt j@ r_||v r_| j|= n	|d7 }n|d7 }|t| jk s|   d S )Nfont_idsr   s   Tfs   INLINE IMAGEs   Dor   )rY   r`   r   r   
operationsrf   re   get_data)	r  r  r  r  Zfont_idZfont_ids_to_deletert  Zoperandsoperator)jump_operatorsr  rh   ri   clean+  s>   

z1PdfWriter.remove_objects_from_page.<locals>.cleaneltstackc              
      s   |v st  drt fdd|D rg g fS zttttf tt d d }W n ty5   i }Y nw g }g }| D ]\}}| }znd }t	j
@ r\|d dkr\t }|| |d dkr|| t|tro|}n!t|}|d	d
 | D  z|j|_W n	 ty   Y nw |  || |d urt|tr|j|jd < n|||< W q> ttfy   Y q>w |D ]}	||	= qt trt tst }
|
   |
  || ||fS )Nr   c                 3   s"    | ]} j t|d dkV  qdS )r   r   N)r   r   r  r  rh   ri   r]  \  s
    
zJPdfWriter.remove_objects_from_page.<locals>.clean_forms.<locals>.<genexpr>r5  r-  r.  z/Imager/  c                 S   s   i | ]\}}|d vr||qS ))r2  r4  z/DecodeParmsrh   )r  Zk1Zv1rh   rh   ri   r!  }  s
    zKPdfWriter.remove_objects_from_page.<locals>.clean_forms.<locals>.<dictcomp>r   )r  anyr   r   r	   r?   r   rB  r   rY   re   rD   r   r   r<   rv   r   r   rB   r   r   r   	TypeErrorrH   )r  r  dr  r  r  r  r   r  Zime)r  clean_formsr   r  r  r  ri   r  U  sz   










z7PdfWriter.remove_objects_from_page.<locals>.clean_formsz	/Contentsrn   )r   r   rd  r  rY   ra   r  rb   rc   rd   rg   r`   r<   r   r   r   r   r	   r?   r   r   r   r   Zget_contentsZreplace_contents)r   r   r  r  Zto_dr  r  r  rh   )r  r  r  r   r  r  ri   r    s`   





	*
Gz"PdfWriter.remove_objects_from_pagec                 C   sT   t |trtj}tj}dD ]}|t| @ r|t| O }q| jD ]}| || qdS )z
        Remove images from this output.

        Args:
            to_delete: The type of images to be deleted
                (default = all images types)

        )re   rf   rg   N)r   r`  r,   ALLrY   r]   r   r  )r   r  rt  imager   rh   rh   ri   remove_images  s   

zPdfWriter.remove_images
font_namesc                    s   |sg }| j D ]N}g }|rD		ddtdttttf  dtt dtttf f fdd  |d}|D ]}||v rC||| d	  q4i }|rL||d
< | j|tj	|d qdS )z
        Remove text from the PDF.

        Args:
            font_names: List of font names to remove, such as "Helvetica-Bold".
                Optional. If not specified, all text will be removed.
        Nr   	font_inforM  rm   c                    s   |d u ri }t | tr|  } t | trV| ddkrG| dd}|ddd }||vr6|g d||< ||| d	 vrG|| d	 | | D ]
} | | ||}qI|S t | tt	frg| D ]} ||}q_|S )
Nr,  r  z	/BaseFontr|   r  +r   )normalized_font_nameresource_idsr  )
r   rB   r   dictr   lstripr:  r   r   r9   )r   r  rM  r  r  r  Z	child_objget_font_inforh   ri   r     s*   


z,PdfWriter.remove_text.<locals>.get_font_infor5  r  r  )r  NN)
r   r	   r   r   r   r   r  r  rY   r`   )r   r  r   Zresource_ids_to_remover  r  r  rh   r  ri   remove_text  s4   

zPdfWriter.remove_texturirectborderc                 C   s  |  | jtj | }ttttf |  |}|dur=dd |dd D }t|dkr<t	dd |d D }|
| ntdtdtdg}t|trRt|}n
t|trXnt|}t }	|	tdtd	td	t|i t }
|
ttjtd
ttjtdttj|ttj|tdtdttjt	|td|	i | |
}tj|v r|tj 
| dS t	|g|ttj< dS )a  
        Add an URI from a rectangular area to the specified page.

        Args:
            page_number: index of the page on which to place the URI action.
            uri: URI of resource to link to.
            rect: :class:`RectangleObject<pypdf.generic.RectangleObject>` or
                array of four integers specifying the clickable rectangular area
                ``[xLL, yLL, xUR, yUR]``, or string in the form
                ``"[ xLL yLL xUR yUR ]"``.
            border: if provided, an array describing border-drawing
                properties. See the PDF spec for details. No border will be
                drawn if this argument is omitted.

        Nc                 S      g | ]}t |qS rh   r  r  rR  rh   rh   ri   r  	      z%PdfWriter.add_uri.<locals>.<listcomp>r  r  c                 S   r&  rh   r  r'  rh   rh   ri   r  	  r(  r   r   z/URIz/Annotr  z/HrZ  /A)r   r   r   r   r   r   r   r	   r   r9   r   rE   r   rG   r?   rv   rC   rI   r6  r   ZSubtypePr7  ZBorderr   r   ra  )r   r   r#  r$  r%  Z	page_linkr  Z
border_arrZdash_patternZlnk2ZlnkZlnk_refrh   rh   ri   add_uri  sF   







zPdfWriter.add_uri)z	/NoLayoutz/SinglePagez
/OneColumnz/TwoColumnLeftz/TwoColumnRightz/TwoPageLeftz/TwoPageRightc                 C   (   z	t t| jd W S  ty   Y d S w )N/PageLayout)r   rS   r   r   r   rh   rh   ri   _get_page_layoutD	  
   zPdfWriter._get_page_layoutlayoutc                 C   sP   t |ts|| jvrtddd| jf t t|}| jtd|i dS )a  
        Set the page layout.

        Args:
            layout: The page layout to be used.

        .. list-table:: Valid ``layout`` arguments
           :widths: 50 200

           * - /NoLayout
             - Layout explicitly not specified
           * - /SinglePage
             - Show one page at a time
           * - /OneColumn
             - Show one column at a time
           * - /TwoColumnLeft
             - Show pages in two columns, odd-numbered pages on the left
           * - /TwoColumnRight
             - Show pages in two columns, odd-numbered pages on the right
           * - /TwoPageLeft
             - Show two pages at a time, odd-numbered pages on the left
           * - /TwoPageRight
             - Show two pages at a time, odd-numbered pages on the right

        zLayout should be one of: r|   r-  N)r   rC   _valid_layoutsr&   rA  rZ   r   rv   r   r0  rh   rh   ri   _set_page_layoutJ	  s   

zPdfWriter._set_page_layoutc                 C   s   |  | dS )a  
        Set the page layout.

        Args:
            layout: The page layout to be used

        .. list-table:: Valid ``layout`` arguments
           :widths: 50 200

           * - /NoLayout
             - Layout explicitly not specified
           * - /SinglePage
             - Show one page at a time
           * - /OneColumn
             - Show one column at a time
           * - /TwoColumnLeft
             - Show pages in two columns, odd-numbered pages on the left
           * - /TwoColumnRight
             - Show pages in two columns, odd-numbered pages on the right
           * - /TwoPageLeft
             - Show two pages at a time, odd-numbered pages on the left
           * - /TwoPageRight
             - Show two pages at a time, odd-numbered pages on the right

        Nr3  r2  rh   rh   ri   set_page_layoutm	  s   zPdfWriter.set_page_layoutc                 C   r  )a  
        Page layout property.

        .. list-table:: Valid ``layout`` values
           :widths: 50 200

           * - /NoLayout
             - Layout explicitly not specified
           * - /SinglePage
             - Show one page at a time
           * - /OneColumn
             - Show one column at a time
           * - /TwoColumnLeft
             - Show pages in two columns, odd-numbered pages on the left
           * - /TwoColumnRight
             - Show pages in two columns, odd-numbered pages on the right
           * - /TwoPageLeft
             - Show two pages at a time, odd-numbered pages on the left
           * - /TwoPageRight
             - Show two pages at a time, odd-numbered pages on the right
        )r.  r   rh   rh   ri   page_layout	  s   zPdfWriter.page_layoutc                 C   s   |  | d S rn   r4  r2  rh   rh   ri   r6  	  s   )z/UseNonez/UseOutlinesz
/UseThumbsz/FullScreenz/UseOCz/UseAttachmentsc                 C   r,  )N	/PageMode)r   rV   r   r   r   rh   rh   ri   _get_page_mode	  r/  zPdfWriter._get_page_modec                 C   r  )a  
        Page mode property.

        .. list-table:: Valid ``mode`` values
           :widths: 50 200

           * - /UseNone
             - Do not show outline or thumbnails panels
           * - /UseOutlines
             - Show outline (aka bookmarks) panel
           * - /UseThumbs
             - Show page thumbnails panel
           * - /FullScreen
             - Fullscreen view
           * - /UseOC
             - Show Optional Content Group (OCG) panel
           * - /UseAttachments
             - Show attachments panel
        )r8  r   rh   rh   ri   	page_mode	  s   zPdfWriter.page_moder  c                 C   sR   t |tr|}n|| jvrtdd| j t t|}| jtd|i d S )NzMode should be one of: z, r7  )r   rC   _valid_modesr&   rA  rZ   r   rv   )r   r  Z	mode_namerh   rh   ri   r9  	  s   

c                 C   s   |}t |tr| j| }n	t |tstdttt|}|j|t	d< |j
du r0t |t	d< |j
dus7J |ddkrjd|v rjttttf |t	d }tt	d|d	 t|d
 t|d d}|j|t	d< |j
| | |ddkrt	d|v r|jtt|d  t	d< |S )a  
        Add a single annotation to the page.
        The added annotation must be a new annotation.
        It cannot be recycled.

        Args:
            page_number: PageObject or page index.
            annotation: Annotation to be added (created with annotation).

        Returns:
            The inserted object.
            This can be used for popup creation, for example.

        zpage: invalid type/PNrh  r.  r  /Destz	/LinkNameZtarget_page_indexr  fit_args)Zfit_typer=  z/Popuprp  )r   r   r   r   r  r   r?   _pdf_objectifyr   rC   rl  r9   r   r   r	   r>   r@   r  r   r   r   r   )r   r   r  r   to_addtmpr   rh   rh   ri   add_annotation	  s6   


zPdfWriter.add_annotationc                 C   s   t d| }|dg D ];}| }|dd}|dd}t|tr-t||td< q|durH| }|dd}t|trHt||td< q|S )z
        Perform some clean up in the page.
        Currently: convert NameObject named destination to TextStringObject
        (required for names/dests list)

        Args:
            page:

        Returns:
            The cleaned PageObject

        r   rh  r<  Nr)  /D)r   r   r   r   rC   rI   )r   r   aZa_objr  Zactrh   rh   ri   
clean_page
  s   

zPdfWriter.clean_pagec                 C   s   d }t |ttfr+t|d}t| }W d    ||fS 1 s"w   Y  ||fS t |trR|jr6|j}|j	 }|j
d t|j }|j
| ||fS t|drmt|drm|
d | }t|}||fS td)Nr   r   r   ro   zMerging requires an object that PdfReader can parse. Typically, that is a Path or a string representing a Path, a file object, or an object implementing .seek and .read. Passing a PdfReader directly works as well.)r   r   r   r   r   ro   r   r   rk   r   r   r  r  )r   r}   encryption_objr   rk   Z	orig_tellZfilecontentrh   rh   ri   _create_stream)
  s0   	



zPdfWriter._create_streamr   import_outlineexcluded_fields.c                 C   sl   |du rd}t |tttfr*t |trt |ts|}|}|}| d|d||| dS | d||||| dS )aQ  
        Identical to the :meth:`merge()<merge>` method, but assumes you want to
        concatenate all pages onto the end of the file instead of specifying a
        position.

        Args:
            fileobj: A File Object or an object that supports the standard
                read and seek methods similar to a File Object. Could also be a
                string representing a path to a PDF file.
            outline_item: Optionally, you may specify a string to build an
                outline (aka 'bookmark') to identify the beginning of the
                included file.
            pages: Can be a :class:`PageRange<pypdf.pagerange.PageRange>`
                or a ``(start, stop[, step])`` tuple
                or a list of pages to be processed
                to merge only the specified range of pages from the source
                document into the output document.
            import_outline: You may prevent the source document's
                outline (collection of outline items, previously referred to as
                'bookmarks') from being imported by specifying this as ``False``.
            excluded_fields: Provide the list of fields/keys to be ignored
                if ``/Annots`` is part of the list, the annotation will be ignored
                if ``/B`` is part of the list, the articles will be ignored

        Nrh   )r   rd  r   rO   r`  merge)r   r}   r  r   rG  rH  rh   rh   ri   r   M
  s0   *

	zPdfWriter.appendpositionc              	      s  t |tr| n|\}}t|dd |du rd}|du r)ttt j}n3t |tr;tt|	t j }n!t |trAnt |t
rSt|dkrStt| }n	t |t
s\tdi |D ]S}	t |	trj|	}
n j|	 }
|
jdusvJ |du r|
g t|dddd	|
jj< n|
|g t|dddd	|
jj< |d7 }|
|
jj _q` j _d
tddf fdd} j D ]}|| q|durtdjt|tt jtd }n } j}|rtj |v r!|"tj d }#||d d	|vr; D ]"}$|j"d	d| }t|dkr4||t%d	< &| qd|v r|d durdj'vrf(tt) jd *ddj't%d< t+ }ntt+tt)j'd d }j,t-  }z- jd d D ]#}zt.||j d}||vr|/| W q t0y   Y qw W n t0y   (t+ }Y nw |tt)j'd t%d< d|vr҈1d  dS dS )a  
        Merge the pages from the given file into the output file at the
        specified page number.

        Args:
            position: The *page number* to insert this file. File will
                be inserted after the given number.
            fileobj: A File Object or an object that supports the standard
                read and seek methods similar to a File Object. Could also be a
                string representing a path to a PDF file.
            outline_item: Optionally, you may specify a string to build an outline
                (aka 'bookmark') to identify the
                beginning of the included file.
            pages: can be a :class:`PageRange<pypdf.pagerange.PageRange>`
                or a ``(start, stop[, step])`` tuple
                or a list of pages to be processed
                to merge only the specified range of pages from the source
                document into the output document.
            import_outline: You may prevent the source document's
                outline (collection of outline items, previously referred to as
                'bookmarks') from being imported by specifying this as ``False``.
            excluded_fields: provide the list of fields/keys to be ignored
                if ``/Annots`` is part of the list, the annotation will be ignored
                if ``/B`` is part of the list, the articles will be ignored

        Raises:
            TypeError: The pages attribute is not configured properly

        F)strictNrh   r  z:"pages" must be a tuple of (start, stop[, step]) or a listr   /Brh  r   rm   c              	      s:  | j }djv r(| d ttt ttttjd dt dt v r(d S | d d u s5t| d tr7d S t| d t	r|z	 j
| d  }W n
 tyQ   Y d S w |jd usYJ zt|jj j|td< | d | W d S  ty{   Y d S w | d jjv r| d jj j|td< | d | d S d S )Nr   r  z/Dests/Pager   )r   r   r   r   r	   r?   r   r   rD   r   r   r  r   rE   r   r   r  r   )r   arrrf  r
  r   Zsrcpagesrh   ri   _process_named_dests
  sF   


z-PdfWriter.merge.<locals>._process_named_destsrJ   )r  r   z	/AcroForm)/FieldsrQ  r|   )2r   r   rF  r   r   r  r   r   rO   indicesrd  r  r   r   r   r   r   original_pageZnamed_destinationsZ_named_destinationsr	   r  r   r  rI   nextru   r8   r   r  r   r   r  _get_filtered_outliner   _insert_filtered_outline_insert_filtered_annotationsrC   rD  r   r   r?   r   r9   r   r   rB   r   r   add_filtered_articles)r   rJ  r}   r  r   rG  rH  rk   rE  r   ZpgrP  r   Zoutline_item_typZ_ror  pagrg  rN  Ztrslatr   indrh   rO  ri   rI  
  s   
&




"
	



	
zPdfWriter.mergethreadc                 C   sx  |j | ddd}| j|j td|d }|}d}|dur| td|d ||}|dur|du rGtd| t  }|}	|j|t	d< ntd| tt	d	|ji }
|
j|t	d
< |
}||t	d< |j|t	d< |d |t	d< td| }d|vrt
 |t	d< td|d |j td|d
 }||kr|	j|t	d
< |j|	t	d	< d}|dus|jdusJ |jS )z
        Clone the thread with only the applicable articles.

        Args:
            thread:
            pages:
            reader:

        Returns:
            The added thread as an indirect reference

        T)r  )Zforce_duplicateignore_fieldsr?   r  Nr   r;  r(  r3  rY  z/RrL  r9   )r   r  r   r   r   _get_cloned_pager   r?   r   rC   r9   )r   r[  r   r
  ZnthreadZfirst_articleZcurrent_articleZnew_articlerY  Z	new_firstZnew_article2Zpag_objrh   rh   ri   _add_articles_threadO  s^   %zPdfWriter._add_articles_threadfltrc                 C   s   t |trt|}n
t |tstd}| D ]=}|j}|ddD ]1}| d}|du r2q$| }|j	j
| jt| vrU||di ddrU| ||| q$qdS )z
        Add articles matching the defined criteria.

        Args:
            fltr:
            pages:
            reader:

        r|   rL  rh   rY  NrZ  r  )r   r   recompiler   r  rS  r   r   r   r   r   r   searchr^  )r   r_  r   r
  rf  pprC  Zthrrh   rh   ri   rX    s(   



zPdfWriter.add_filtered_articlesc                 C   sb   t |trd S t |tr|dddkr|j}nt |tr|}z||j jW S  ty0   Y d S w )Nr,  r|   rM  )r   rD   r?   r   r   rB   r   r   )r   r   r   r
  Z_irh   rh   ri   r]    s   

zPdfWriter._get_cloned_pageannotsc                 C   s  t  }t|trtd| }|d u r|S |D ]}td| }|d dks9d|vs9td|d d dks9d|v rd|vrI|| ||  q|d }t|trdt|| 	 v rc||| j
 qtd	|}| |d
 ||}	|	d ur|j| dd}
t |	g|dd   |
td< || |
 qtd|d dt }|d u st|trqt|trt|| 	 v r||| j
 qtd	|}| |d
 ||}	|	d ur|j| dd}
t |	g|dd   td|
d td< || |
 q|S )Nz	List[Any]r?   r.  r  r)  r   r  r<  r9   r   )r<  )r\  r   rB  )rB  )r9   r   rB   r   r   r   r   r   r   r  r   r]  rC   r   rD   )r   rd  r   r   r
  Zoutlistr  Zanor  rf  Zancrh   rh   ri   rW    sV   




z&PdfWriter._insert_filtered_annotationsr   c                 C   s&  g }|du r	t  }| }t|rt }|dddks d|vr9|dd}|dur7| }|| |||7 }|S |dur| }td||}| td|d	 ||}|du r\t  }||t	d	< d|v rq| |d |||_
ng |_
t|d	 t rt|j
d
kr|| |dd}|dus=|S )z
        Extract outline item entries that are part of the specified page set.

        Args:
            node:
            pages:
            reader:

        Returns:
            A list of destination objects.

        Nr,  r|   	/Outlinesr  /Firstr>   r   rM  r   /Next)rD   r   rN   r?   r   rU  r   Z_build_outline_itemr]  rC   _filtered_childrenr   r   r   )r   r   r   r
  Znew_outliner   r  rh   rh   ri   rU    s>   

zPdfWriter._get_filtered_outlinec                 C   s   t  }| | t|d |td< t|d ts7|jd ur0d|jv r0|jd | |td< n|j|td< |jd ur_t	|j
dd|td< t|j
dtdtdtdg|td< |S )	Nr  rM  r)  r<  r  r   /Cg        )rJ   r   rI   rC   r   rD   r   r   r   rE   r   r9   rA   )r   r   Zn_olrh   rh   ri   _clone_outline,  s   

zPdfWriter._clone_outlineoutlinesc                 C   s^   |D ]*}| dddksd|vr|}n| |}tt| |||  | |j|d  qd S )Nr,  r|   re  r  )r   rj  r   rJ   r   r  rV  rh  )r   rk  r  r  r   nprh   rh   ri   rV  ?  s   
z"PdfWriter._insert_filtered_outlinec                 C   r   )z"Implemented for API harmonization.Nrh   r   rh   rh   ri   r  O  s   zPdfWriter.closec                 C   s   |d u r	|   }ntd|}d}|d urZ|j|ks!|dd |kr$|gS d|v rB| |tt|d }|rBd|v r>|g| S g | S d|v rR|d7 }tt|d }nd S |d usd S d S )NrJ   r   r  rf  rg  r   )r  r   r   r   find_outline_itemrU   rJ   )r   r  r  r   rt  resrh   rh   ri   rm  S  s&   


zPdfWriter.find_outline_itemc                 C   s   t ddd dS )zZ
        .. deprecated:: 2.9.0
            Use :meth:`find_outline_item` instead.
        find_bookmarkrm  z5.0.0N)r%   )r   r  r  rh   rh   ri   ro  p  s   	zPdfWriter.find_bookmarkc                 C   s   |du r	i | _ dS t|tr"z	| j t|= W dS  ty!   Y dS w t|tr<z
| j t|j= W dS  ty;   Y dS w td)a3  
        Reset the translation table between reader and the writer object.

        Late cloning will create new independent objects.

        Args:
            reader: PdfReader or IndirectObject referencing a PdfReader object.
                if set to None or omitted, all tables will be reset.

        Nzinvalid parameter {reader})r   r   r   r   r   rB   r   )r   r
  rh   rh   ri   reset_translation{  s   


zPdfWriter.reset_translationpage_index_frompage_index_tostyleprefixr  c                 C   s   |du r|du rt d|dk rt d||k rt d|t| jkr't d|dur7|dkr7|dk r7t d| ||||| dS )	aK  
        Set a page label to a range of pages.

        Page indexes must be given starting from 0.
        Labels must have a style, a prefix or both.
        If a range is not assigned any page label, a decimal label starting from 1 is applied.

        Args:
            page_index_from: page index of the beginning of the range starting from 0
            page_index_to: page index of the beginning of the range starting from 0
            style: The numbering style to be used for the numeric portion of each page label:

                       * ``/D`` Decimal Arabic numerals
                       * ``/R`` Uppercase Roman numerals
                       * ``/r`` Lowercase Roman numerals
                       * ``/A`` Uppercase letters (A to Z for the first 26 pages,
                         AA to ZZ for the next 26, and so on)
                       * ``/a`` Lowercase letters (a to z for the first 26 pages,
                         aa to zz for the next 26, and so on)

            prefix: The label prefix for page labels in this range.
            start:  The value of the numeric portion for the first page label
                    in the range.
                    Subsequent pages are numbered sequentially from this value,
                    which must be greater than or equal to 1.
                    Default value: 1.

        Nz.At least one of style and prefix must be givenr   z/page_index_from must be greater or equal than 0z;page_index_to must be greater or equal than page_index_fromz%page_index_to exceeds number of pagesr   z1If given, start must be greater or equal than one)r   r   r   _set_page_label)r   rq  rr  rs  rt  r  rh   rh   ri   set_page_label  s   $zPdfWriter.set_page_labelc                 C   sX  t  }td|td< t  }|durt||td< |dur&t||td< |dkr2t||td< ttj| jvrVt }ttd|| t	 }	||	td< |	| jttj< t
t	| jttj }	t
t|	td }tt||| tt||| tt||^}
}|
|d kr|d t| jk rtt|d || ||	td< |	| jttj< dS )	a   
        Set a page label to a range of pages.

        Page indexes must be given starting from 0.
        Labels must have a style, a prefix or both.
        If a range is not assigned any page label a decimal label starting from 1 is applied.

        Args:
            page_index_from: page index of the beginning of the range starting from 0
            page_index_to: page index of the beginning of the range starting from 0
            style:  The numbering style to be used for the numeric portion of each page label:
                        /D Decimal Arabic numerals
                        /R Uppercase Roman numerals
                        /r Lowercase Roman numerals
                        /A Uppercase letters (A to Z for the first 26 pages,
                           AA to ZZ for the next 26, and so on)
                        /a Lowercase letters (a to z for the first 26 pages,
                           aa to zz for the next 26, and so on)
            prefix: The label prefix for page labels in this range.
            start:  The value of the numeric portion for the first page label
                    in the range.
                    Subsequent pages are numbered sequentially from this value,
                    which must be greater than or equal to 1. Default value: 1.

        rB  r   Nr;  r   z/Stz/Numsr   )r?   rC   rI   rE   r)   ZPAGE_LABELSr   r9   r   rJ   r   r   r   r   r   )r   rq  rr  rs  rt  r  Zdefault_page_labelZnew_page_labelZnumsZpage_labelsZnext_label_posrK  rh   rh   ri   ru    s4   !zPdfWriter._set_page_labelincludeexcludec                    sX   t  }| | d|i}durfdd| D } dur* fdd| D }|S )z
        Integration into Jupyter Notebooks.

        This method returns a dictionary that maps a mime-type to its
        representation.

        .. seealso::

           https://ipython.readthedocs.io/en/stable/config/integrating.html
        zapplication/pdfNc                    s   i | ]\}}| v r||qS rh   rh   r  )rw  rh   ri   r!  "  r  z/PdfWriter._repr_mimebundle_.<locals>.<dictcomp>c                    s   i | ]\}}| vr||qS rh   rh   r  )rx  rh   ri   r!  &  r  )r   r   rB  )r   rw  rx  Zpdf_datar  rh   )rx  rw  ri   _repr_mimebundle_  s   
zPdfWriter._repr_mimebundle_)r|   NFF)rm   r{   )rh   )T)r   rh   r!  )NNr   rn   )r|   r   )rm   N)TT)NNT)NNTN)NNTrh   )rZ   r[   r\   __doc__r   r   r    r   r`  r   propertyr   r?   r   r   r   setterrB   rW   r   r   r   r   BaseExceptionr   r   r   r   r$  rF   r   r   r   r   r   r   r   r   rK   r   r   r   rD   r   r;  r   decimalDecimalr   r>   rI   r;   r   r  r	  r
   r  rS  r<  r>  Z
FFBITS_NULr   r   r   rb  ri  ru  r   ry  rz  ALL_DOCUMENT_PERMISSIONSr1   r  r!   r  r   r	   r   r  r  rx  r  r  r   r  r  r  r9   r:   rA   rC   rE   r  r  r  rJ   r  r  r  r  rT   r  r8   r@   r  r  r  r  r  r  rQ   r  r  rY   r  r,   r  r  r"  rG   r+  r1  rS   r.  r3  r5  r6  r:  rV   r8  r9  rA  rD  r   r   rF  rO   r   rP   rI  r^  r   rX  r]  rW  rU  rj  rV  r  rU   rm  ro  rp  r/   rv  ru  ry  __classcell__rh   rh   r   ri   r{      sz   
 	
 









/!





" $_
$
 
"
m
2*
0
;& "G

K
#
!
)
	

N








 0
>
C
#	


6
)$

H
 ?

A


!



6

4



 
 7C
r{   r   c                 C   s   t | tr| S t | tr"t }|  D ]\}}t||t|< q|S t | tr4| dr0t| S t	| S t | t
tfr?t| S t | trMtdd | D S tdt| d)Nr  c                 s   r[  rn   )r>  )r  rt  rh   rh   ri   r]  :  r^  z!_pdf_objectify.<locals>.<genexpr>z
type(obj)=z! could not be cast to a PdfObject)r   rF   r  r?   rB  r>  rC   r   
startswithrI   r;  r   rA   r   r9   r  type)r   r?  rM  r   rh   rh   ri   r>  +  s$   




r>  r  r  r  r  r  c                 C   s   t  }| d ur| |td< |tdt|i |r3t|tr#t|}|tdtdd |D i |s7|rRd}|r@|tj	7 }|rG|tj
7 }|tdt|i |S )Nr)  r  ri  c                 S   r&  rh   )rA   r  r   rh   rh   ri   r  S  r(  z(_create_outline_item.<locals>.<listcomp>r   r  )rJ   rC   rv   rL   r   r   rM   r9   r.   r  r  rE   )r  r  r  r  r  r  Zformat_flagrh   rh   ri   r  @  s*   


r  rN  rO  rH  rL  rG  rI  rJ  c                    s.  d|j d  d|jd  d| d }t| dddD ]q\}}	|	|v rG|d||| d  d  d|j d	  d|d	  d
| d	 7 }|dkrV|d| d 7 }n|d| d  d 7 } fdd|	D }
tdd |
D r|dd|
   d 7 }q|dd|
 d 7 }q|d7 }|S )Nzq
/Tx BMC 
q
1 1 r   r  z	 re
W
BT
r  r  z1 gffffff?r   z re
0.5 0.5 0.5 rg s
r   z2 z Td
r  c                    s   g | ]}  ||d qS )z	utf-16-be)r   r   r  rL  rh   ri   r  u  s    z.generate_appearance_stream.<locals>.<listcomp>c                 s   s    | ]	}t |d kV  qdS )r   Nr  r  rh   rh   ri   r]  x  s    z-generate_appearance_stream.<locals>.<genexpr>   <rr   s   > Tj
   (s   ) Tj
s   ET
Q
EMC
Q
)	r   r   r   rj  r9  r:  r  rA  hex)rN  rO  rH  rL  rG  rI  rJ  rP  line_numberlineZenc_linerh   r  ri   rD  _  s(   (	.
 rD  )rj   )r~  r^   rs   r`  r  r   ior   r   r   	itertoolsr   pathlibr   typesr   typingr   r	   r
   r   r   r   r   r   r   r   r   r   Z_cmapr   r   Z_doc_commonr   r   r   r   r   Z_pager   Z_page_labelsr   r   r   r   r   Z_utilsr    r!   r"   r#   r$   r%   r&   	constantsr'   r6  r(   r   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r   r3   r<  r4   r   r5   r   r6   r  errorsr7   Zgenericr8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   Z	pagerangerO   rP   rQ   rR   rS   rT   rU   rV   ZxmprW   allr  r@  IntFlagrY   r   r   rz   r{   r;  r>  r`  r  r$  rD  rh   rh   rh   ri   <module>   s   8$	,d                          */


