o
    >e                    @   s  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlmZm	Z	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mZ ddlmZ ddlm Z m!Z! dd	l"m#Z#m$Z$ dd
l%m&Z&m'Z'm(Z( ddl)m*Z* ddl+m,Z,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z3 ddl1m4Z5 ddl1m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z> ddl1m6Z? ddl1m@ZA ddl1mBZC ddl1mDZE ddl1mFZG ddl1mHZI ddlJmKZK ddlLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZambZb ddlcmdZdmeZe ddlmfZfmgZgmhZhmiZimjZjmkZk e7d Zle>m ZnG dd dejoZpd.dedeqderfd d!ZsG d"d# d#Ztd$eeeref ereqee f de[fd%d&Zud'edeWf d(erd)eeevevevf erdf d*ewd+ewde_fd,d-ZxdS )/    N)BytesIOFileIOIOBase)Path)TracebackType)IOAnyCallableDequeDictIterableListOptionalPatternTupleTypeUnioncast   )build_char_map_from_dict)EncryptAlgorithm
Encryption)
PageObject_VirtualList)nums_clear_rangenums_insert	nums_next)	PdfReader)StrByteType
StreamType_get_max_pdf_version_headerb_logger_warning)AnnotationDictionaryAttributes)CatalogAttributes)	CatalogDictionary	FieldFlag"FileSpecificationDictionaryEntriesGoToActionArguments	ImageTypeInteractiveFormDictEntriesPageLabelStyleTypFitArgumentsUserAccessPermissions)r%   )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)	PageRangePageRangeSpec)AnnotationSubtypeBorderArrayType
LayoutTypeOutlineItemTypeOutlineTypePagemodeTypec                   @   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_IMAGESIMAGES rb   rb   N/var/www/html/humari/django-venv/lib/python3.10/site-packages/pypdf/_writer.pyrR      s    rR      stream	blocksizereturnc                    s4   t  }t fdddD ]}|| q| S )Nc                      s
     S N)readrb   rf   re   rb   rc   <lambda>   s   
 z#_rolling_checksum.<locals>.<lambda>    )hashlibmd5iterupdate	hexdigest)re   rf   hashblockrb   rj   rc   _rolling_checksum   s   rt   c                   @   sj  e Zd ZdZ		ddededeeef ddfddZdd	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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	ddedeeegdf dee defd d!Zdd#eddfd$d%Z ede
e! fd&d'Z"de!fd(d)Z#	ddedee defd*d+Z$	,	dded-edee defd.d/Z%d0edefd1d2Z&defd3d4Z'ede(e fd5d6Z)	d d7e
e* d8e
e* defd9d:Z+			,dd7e
ee*e,j-f  d8e
ee*e,j-f  d-edefd;d<Z.edede/e0e1f fd=d>Z2e2jd?edee/ef ddfd@d>Z2dAeddfdBdCZ3dDedEeeef ddfdFdGZ4	ddHedIe
eegdf  ddfdJdKZ5dLe6de
e fdMdNZ7dOe6ddfdPdQZ8e9d"fdedRe:eef dSe;dTe
e ddf
dUdVZ<dHeddfdWdXZ=			ddYede6ef dZe
e:eef  de
e ddfd[d\Z>	ddHedIe
eegdf  ddfd]d^Z?de1fd_d`Z@ddadbZAdd"eBfddcddedee
e dfedgeCdhe
e ddfdidjZDdkeEddfdldmZFdkeeef deGeeHe f fdndoZIdkeEde(e fdpdqZJdkeEdre(e defdsdtZKdkeEdueddfdvdwZLdxe:eef ddfdydzZMd{eeNeOe6ePeeQeeRe0eSf
 ddfd|d}ZTdEedefd~dZUdedefddZVdeWfddZXdeNfddZYedeNfddZZdeNfddZ[			"ddeeeeWf dLedeWef dedeWef dedef
ddZ\			"dde]dLedeWef dedeWef dedef
ddZ^ddddde_d"fded0edeeef dLedeWef dedeWef de
eeGe*e*e*f ef  dedede`dedefddZadddZbde0deeeNf ddfddZcdedefddZdded0edefddZedddZfde
eegeeg f  ddfddZhdeeee6f de
ee  ddfddZideee6f deejeej f ddfddZkeljmfdelddfddZndddZo	dd0ededepde
eN ddf
ddZqdZrde
es fddZtdeeQesf ddfddZudesddfddZvede
es fddZwewjdesddfddZwdZxde
ey fddÄZzede
ey fddńZ{e{jdeyddfddńZ{d0eeef de:eef de6fddʄZ|deeef defdd̄Z}deeeef deGe~e
e f fdd΄Z			"	ddeeeef deedeeGeef eGeeef e(e f dYedeeGeef eGeeef e(e e(e f dede
ee(e eGedf f  ddfddӄZ			"	dde
e deeeef de
e dYe
eee(e f  dede
ee(e eGedf f  ddfddքZde6dYe:eef dHedefddلZdeee ef dYe:eef dHeddfdd܄ZdedeeeeSf dYe:eef dHede
e fddބZdeee(e6 f dedYe:eef dHede(e/ f
ddZdedYe:eef dHede(e/ fddZd?e/deWfddZ	dde(e/ dLeeWef dedeWef ddfddZdddZ	dde:eef d{e
e de
e(e  fddZ	dde:eef d{e
e de
e(e  fddZ	ddHedeef ddfddZ			,ddedede
e de
e de
e ddfddZ			,ddedede
e de
e de
e ddfddZdS (  	PdfWriterz
    Write a PDF file out, given pages produced by another class.

    Typically data is added from a :class:`PdfReader<pypdf.PdfReader>`.
     Nfileobj
clone_fromrg   c                 C   s  d| _ g | _	 i | _	 i | _t }|ttjtdttj	t
dttjt i | || _t }|tdttjdd i | || _t | _| jttjttjttj| ji | | j| _|d ur{t|tsvt|}| | || _d| _d | _d | _d | _ d S )Ns   %PDF-1.3/Pagesr   z	/Producerpypdfzutf-16beF)!_header_objects_idnum_hash_id_translatedr;   rp   r?   PATYPECOUNTrA   KIDSr5   _add_object_pagesrH   codecsBOM_UTF16_BEencode_info_root_objectCOCATALOGPAGES_root
isinstancer   clone_document_from_readerrw   with_as_usage_encryption_encrypt_entry_ID)selfrw   rx   pagesinforb   rb   rc   __init__   sL   


zPdfWriter.__init__c                 C   s
   d| _ | S )z+Store that writer is initialized by 'with'.T)r   r   rb   rb   rc   	__enter__   s   zPdfWriter.__enter__exc_typeexc	tracebackc                 C   s   | j r| | j  dS dS )zWrite data to the fileobj.N)rw   write)r   r   r   r   rb   rb   rc   __exit__   s   zPdfWriter.__exit__c                 C   s   | j S )z
        Header of the PDF document that is written.

        This should be something like ``b'%PDF-1.5'``. It is recommended to set
        the lowest version that supports all features which are used within the
        PDF file.
        r{   r   rb   rb   rc   
pdf_header   s   	zPdfWriter.pdf_header
new_headerc                 C   s
   || _ d S rh   r   )r   r   rb   rb   rc   r      s   
objc                 C   s~   t |d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 )Nindirect_referencer   )hasattrr   pdfr   r;   getPGCONTENTSr5   r   r?   r|   appendr>   len)r   r   rb   rb   rc   r      s   zPdfWriter._add_objectr   c                 C   s:   t |tr| j|d  S |j| krtd| j|jd  S )Nr   pdf must be self)r   intr|   r   
ValueErroridnum)r   r   rb   rb   rc   
get_object   s
   

zPdfWriter.get_objectc                 C   s^   t |tr|j| krtd|j}| j|d  jj}|| j|d < t||| |_| j|d  S )Nr   r   )r   r>   r   r   r   r|   r   
generation)r   r   r   genrb   rb   rc   _replace_object	  s   

zPdfWriter._replace_objectrb   pageactionexcluded_keysc                 C   s  t t|tj tjksJ |}t|}|tjdg7 }z| jt	|j
j |j
j= W n	 ty1   Y nw t d|| d|}|jd urU|jj}t|trN| }t| j|| _| j|ttj< t t| | j}|j
d usmJ ||tj |j
 t t|tj }t|d |ttj< |S )Nz/StructParentsr   Fr   )r   strr   r   r   PAGElistPARENTr~   idr   r   r   	Exceptioncloner   r   r   r    r   r?   r;   r   r   r   r   rA   )r   r   r   r   page_orgotherr   
page_countrb   rb   rc   	_add_page  s0   

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 appearence 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;   r?   r*   NeedAppearancesr6   r   r   r"   rS   )r   r   need_appearancesr   rb   rb   rc   set_need_appearances_writer9  s"   

z%PdfWriter.set_need_appearances_writerc                 C   sf   | j tjd}|du rdS | }t|ts1t|}t|dr)| |j	| |S || j t
tj< |S )zCReturns the existing ViewerPreferences as an overloaded dictionary.Nr   )r   r   CDVIEWER_PREFERENCESr   r   rG   r   r   r   r?   r   orb   rb   rc   viewer_preferencesY  s   

zPdfWriter.viewer_preferencesc                 C   s    t  }| || jttj< |S rh   )rG   r   r   r?   r   r   r   rb   rb   rc   create_viewer_preferencesh  s   z#PdfWriter.create_viewer_preferencesc                 C   s   |  |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.
        )r   r   r   )r   r   r   rb   rb   rc   add_pagem  s   zPdfWriter.add_pager   indexc                    s   |  | fdd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.
        c                    s   |   |S rh   )insert)kidspr   rb   rc   rk     s    z'PdfWriter.insert_page.<locals>.<lambda>)r   )r   r   r   r   rb   r   rc   insert_page  s   zPdfWriter.insert_pagepage_numberc                 C   s2   t tttf | | j}t t|tj |  S )z
        Retrieve a page by number from this PDF file.

        Args:
            page_number: The page number to retrieve
                (pages begin at zero)

        Returns:
            The page at the index given by *page_number*
        )	r   r   r   r   r   r   r   r   r   )r   r   r   rb   rb   rc   get_page  s   zPdfWriter.get_pagec                 C   s*   t tttf | | j}t|td S )N/Count)r   r   r   r   r   r   r   r?   )r   r   rb   rb   rc   _get_num_pages  s   zPdfWriter._get_num_pagesc                 C   s   t | j| jS )a-  
        Property that emulates a list of :class:`PageObject<pypdf._page.PageObject>`.
        this property allows to get a page or  a range of pages.

        It provides also capability to remove a page/range of page from the list
        (through del operator)
        Note: only the page entry is removed. As the objects beneath can be used
        somewhere else.
        a solution to completely remove them - if they are not used somewhere -
        is to write to a buffer/temporary and to then load it into a new PdfWriter
        object.
        )r   r   r   r   rb   rb   rc   r     s   zPdfWriter.pageswidthheightc                 C   s   t | ||}| |S )a'  
        Append a blank page to this PDF file and returns 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   rb   rb   rc   add_blank_page  s   
zPdfWriter.add_blank_pagec                 C   sX   |du s|du r|   d |kr| j| }|jj}|jj}t| ||}| || |S )aT  
        Insert a blank page to this PDF file and returns 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 appended page

        Raises:
            PageSizeNotDefinedError: if width and height are not defined
                and previous page does not exist.
        Nr   )r   r   mediaboxr   r   r   r   r   )r   r   r   r   oldpager   rb   rb   rc   insert_blank_page  s    
zPdfWriter.insert_blank_pagec              
   C   s   d| j vrdS | j d }t|ttfrtt|S t|trQz|dd \}}|dd }t|t|}td||W S  t	yP } z
t	d| d| d}~ww dS )z
        Property to access the opening destination (``/OpenAction`` entry in
        the PDF catalog). It returns ``None`` if the entry does not exist is not
        set.

        Raises:
            Exception: If a destination is invalid.
        /OpenActionNr      
OpenActionzInvalid Destination : )
r   r   r   bytesrH   r5   r<   tupler:   r   )r   oar   typarrayfitr   rb   rb   rc   open_destination  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 )Nr   Opening)r   KeyErrorr   r   rE   r?   r:   
dest_arrayr   r   r@   r4   )r   r   rb   rb   rc   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;   r?   CANAMESr   r5   rp   r   r   rE   r   rH   r   uuiduuid4r   )r   r   namesjs_listjsrb   rb   rc   add_js$  s&   
	zPdfWriter.add_jsfilenamedatac                 C   s.  t  }|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rR| t | jttj< dtt| jtj vrxt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://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/PDF32000_2008.pdf
        Section 7.11.3

        Args:
            filename: The filename to display.
            data: The data in the file.
        z/EmbeddedFile/Fz	/Filespecz/EmbeddedFilesN)r9   set_datar!   rp   r?   r   r   r;   r   r'   FrH   EFr   r   r   r   r5   extend)r   r   r   
file_entryef_entryfilespecembedded_files_names_dictionaryrb   rb   rc   add_attachmentG  sB   


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 prefered.

        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  reader_num_pagesreader_page_numberreader_pagewriter_pagerb   rb   rc   append_pages_from_reader  s   


z"PdfWriter.append_pages_from_readerparentc                 C   sj   d|v rt t|d S d|vrd S d|v r.| t t|d }|d ur.|d t t|d  S t t|d S )Nz/TM/T/Parent.)r   r   _get_qualified_field_namer;   )r   r  qualified_parentrb   rb   rc   r    s   z#PdfWriter._get_qualified_field_namefieldc                    s  t t|tj }tdd|d |d  |d |d  f}t t|tj }|ddddd}dd	 |D }||d
d  }t	||d
d  }|dkre|j
d }t|||d
d < d|}|j
d | }t tt t|dt  }	|	dt  }	||	vrt tttf t t| jd di }	t|	tr|	 }	|	dt  }	|	|}
|
d urt t|
 }
td|
\}} }z|d= W n	 ty   Y nw t tr fdd| D n/dd   D dd   D }| D ]\}}||||< qntd| dt i |tjd}|tjddkrJ|tjj@ dkrJd|tji }|dg }t|tsI|g}n|dd}g }|dddddd}d |j d  d|j
d  d!| d! }t"|dddD ]y\}}||v r|d"||| d#  d  d|j d  d|d  d$|tj  d	! 7 }|dkr|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|d07 }t%&t'd1t'd2t'd3t'd4t'd5|d6t(|d7di}|
d ur3tt'dtt'|t)|
d8|
ii|t'd9< tj*|vrKtt'd:| +|i|t'tj*< d S d:t t|tj* vri| +|t t|t'tj* t'd:< d S |tj* d: j,j-}|| j.|d < t|d| |_,d S );Nr   r      r   
 c                 S   s   g | ]}|d kr|qS )rv   rb   ).0xrb   rb   rc   
<listcomp>  s    z0PdfWriter._update_text_field.<locals>.<listcomp>Tfz/DRz/Font	/AcroForm   c                    s   i | ]
\}}||  qS rb   )r   r  kv)font_encodingrb   rc   
<dictcomp>  s    z0PdfWriter._update_text_field.<locals>.<dictcomp>c                 S      i | ]
\}}|t |fqS rb   r   r  rb   rb   rc   r#        c                 S   r$  rb   r%  r  rb   rb   rc   r#    r&  zFont dictionary for z not found./Tx/Ch/Vrv   \z\\(z\()z\)zq
/Tx BMC 
q
1 1 z	 re
W
BT
z1 gffffff?z re
0.5 0.5 0.5 rg s
z2 z Td
0 c                    s   g | ]}  ||d qS )z	utf-16-be)r   r   r  c)font_full_revrb   rc   r    s    c                 s   s    | ]	}t |d kV  qdS )r   N)r   r.  rb   rb   rc   	<genexpr>!  s    z/PdfWriter._update_text_field.<locals>.<genexpr>   <rl   s   > Tj
   (s   ) Tj
s   ET
Q
EMC
Q
/Type/XObject/Subtype/Formz/BBox__streamdata__/Lengthr   
/Resources/N)/r   rC   AARectr   DAreplacesplitr   floatr   joinr;   r   r   r   r   r   r   r>   r   r   itemsr"   rS   FAFfFTFfBitsComboOptr   r   r   	enumerateanyhexr9   initialize_from_dictionaryr?   r7   getattrAPr   r   r   r|   )r   r  _rctrctdafont_properties	font_namefont_heighty_offsetdrfont_resfont_subtype_font_mapfont_encoding_revkkr!  field_flagstxtsel	ap_streamline_numberlineenc_linedctnrb   )r"  r0  rc   _update_text_field  s   (








&(
.

"
zPdfWriter._update_text_field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&| 
| tj|vr2tdt dS |tjtd}|tj D ]}tt| }|tjt  }| D ]\}	}
|tj|	ksj| ||	krt|
trtdd |
D }||ttj< n	t|
|ttj< |tjdv rt|
|ttj< nU|tjd	ks|tjd
krtj|vr|}|}tj|vr|d}|du rn| }tj|v r|tj }tj|vs||ttj< | | n|tjdkrtdt |rt ||ttj!< qW|tj|	ks| ||	kr:t|
|ttj< |ttj" D ]}| }t|
|tj# d v r0|
nd|ttj< qqWq@d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: Page reference from PDF writer where the
                annotations and field data will be updated.
            fields: a Python dictionary of field names (/T) and text
                values (/V)
            flags: An integer (0 to 7). The first bit sets ReadOnly, the
                second bit sets Required, the third bit sets NoExport. See
                PDF Reference Table 8.70 for details.
            auto_regenerate: set/unset the need_appearances flag ;
                the flag is unchanged if auto_regenerate is None
        z+No /AcroForm dictionary in PdfWriter Objectz0No /Fields dictionary in Pdf in PdfWriter Objectz No fields to update on this pageNz/Helvetica 0 Tf 0 gc                 s       | ]}t |V  qd S rh   )rE   )r  r!  rb   rb   rc   r1        z:PdfWriter.update_page_form_field_values.<locals>.<genexpr>z/Btnr'  r(  r  z/Sigz#Signature forms not implemented yetr;  z/Off)$r%   r   r   r3   r   r;   r*   Fieldsr   boolr   r   ANNOTSr"   rS   r   r>  rE   r   r   rC  rD  Tr  r   r5   r?   VrF  r<  ASrg  rA   rE  KidsrO  )r   r   rh  ri  rj  af
default_dawriter_annotwriter_parent_annotr  valuelstfrR  r   rb   rb   rc   update_page_form_field_valuesL  sx   













z'PdfWriter.update_page_form_field_valuesc                 C   s   | j   tt|jtj | | _| jj	| _
| jd| _|   | jD ]}| }t| || j |jd < | j |jd  |  q%| j| jtd td< | `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 the document root should be copied.
        ry   r   /KidsN)r|   clearr   r;   trailerTKROOTr   r   r   r   raw_getr   _flattenflattened_pagesr   r   r   rp   rC  r?   )r   r  r   r   rb   rb   rc   clone_reader_document_root  s   
	

z$PdfWriter.clone_reader_document_rootr   inheritc                 C   sT  t tjt tjt tjt tjf}|d u ri }|d u r(tt| jd }t	 | _
|d us.J tj|v r;t|tj }n
tj|vrCd}nd}|dkr||D ]}||v rW|| ||< qKtt	|tj D ]}i }t|trm||d< | j| |fi | q`d S |dkrt| D ]\}	}
|	|vr|
||	< qtt| jd|t d< | j
| d S d S )Nry   /Pager   r  )r?   r   	RESOURCESMEDIABOXCROPBOXROTATEr   r;   r   r5   r  r   r   r   r   r   r>   r  r   r   rC  r  r   )r   r   r  r   inheritable_page_attributestattrr   addtattr_inrx  rb   rb   rc   r    sJ   


zPdfWriter._flattenc                 C   s   |  | tj|jv r|jtj | j| _ztt|jtj	 | | _
W n	 ty.   Y nw t|rItttt| j d D ]
}||  q@dS dS )az  
        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.
        r|  N)r  r  INFOr~  r   r   r   r   r5   IDr   r   r  r;   r   r   )r   r  r  r   rb   rb   rc   r     s   
z$PdfWriter.clone_document_from_readerc                 C   s,   t  }| | |d tt|dS )Nr   utf8)r   _write_pdf_structureseekr7   rt   r   )r   re   rb   rb   rc   _compute_document_identifier  s   

z&PdfWriter._compute_document_identifierc                 C   s8   | j r| j d }|  }n|  }|}t||f| _ dS )a   
        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   r  r5   )r   id1id2rb   rb   rc   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 grantend.
                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 maybe one of "RC4-40", "RC4-128",
                "AES-128", "AES-256-R5", "AES-256". If it's valid,
                `use_128bit` will be ignored.
        N-rZ  zalgorithm 'z' NOT supportedr   r   )rN  r   r?  AttributeErrorr   RC4_128RC4_40r  r   r   maker   write_entryr   r   r|   r   r   )r   r  r  r  r  r  algentryrb   rb   rc   encrypt'  s*    



zPdfWriter.encryptre   c                 C   sn   t |drd|jvrtd|j dt | js| | j| _| | j | 	|}| 
||}| || d S )NmodebzFile <zH> to write to is not in binary mode. It may not be written to correctly.)r   r  r"   namerS   r   r   r   _sweep_indirect_referencesr  _write_xref_table_write_trailer)r   re   object_positionsxref_locationrb   rb   rc   write_streama  s   
zPdfWriter.write_streamc                 C   s^   d}|dkrt d| dt|ttfrt|d}d| _d}| | | jr+|  ||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)
        Frv   zOutput(stream=z) is empty.wbT)r   r   r   r   r   r   r  close)r   re   my_filerb   rb   rc   r   r  s   

zPdfWriter.writec                 C   s   g }| | jd  | d t| jD ]7\}}|d urK|d }||  | | d  | jrA|| jkrA| j	||d}|
| | d q|S )N   
s   %
r   z 0 obj
r   s   
endobj
)r   r   rJ  r|   r   tellr   r   r   encrypt_objectwrite_to_stream)r   re   r  ir   r   rb   rb   rc   r    s   


zPdfWriter._write_pdf_structurer  c                 C   s|   |  }|d |dt| jd  d  |ddddd	d
  |D ]}||dddd	d  q*|S )Ns   xref
r-  r   r  r   z0>10r  i  z0>5z f 
z n 
)r  r   r   r|   r   )r   re   r  r  offsetrb   rb   rc   r    s   
  zPdfWriter._write_xref_tabler  c                 C   s   | d t }|ttjtt| jd ttj	| j
ttj| ji | jr0| j|ttj< | jr<| 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   z
startxref
z
%%EOF
N)r   r;   rp   r?   r  SIZErA   r   r|   r  r   r  r   r   r  r   r   ENCRYPTr  r   )r   re   r  r~  rb   rb   rc   r    s   

zPdfWriter._write_trailerinfosc                 C   sr   i }t |trtt| }t| D ]\}}t |tr!| }tt||t	|< qtt| 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   rB   r   r;   r   r   rC  rH   r   r?   r   rp   )r   r  argskeyrx  rb   rb   rc   add_metadata  s   

zPdfWriter.add_metadatarootc                 C   s|  t  }g }d}g }d}|||||f t|r| \}}}}t|ttfrD| D ]\}}	||	|||dur>||g ng f q,n't|t	rk|j
| krk| |}t||vrk|t| || ddg f t|ttfrt|tr| | |}g }
|| |kr| gdd |D  }
|||< |
D ]}| j|d}|dur| }|dur|| j| < qt|sdS 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.
        Nc                 S   s   g | ]}|  qS rb   )
hash_value)r  grant_parentrb   rb   rc   r  !  s    z8PdfWriter._sweep_indirect_references.<locals>.<listcomp>)collectionsdequer   r   popr   r5   r;   rC  r>   r   _resolve_indirect_objectr   r   rD   r   r  r}   )r   r  stack
discoveredr  grant_parents	key_or_idr   r  rx  update_hashesold_hashr   indirect_reference_objrb   rb   rc   r    sX   %	

z$PdfWriter._sweep_indirect_referencesc                 C   s   t |jdr|jjjrtd|jjj |j| kr|S |j|}|du r7td|jj	 d| dt	 t
 }| }|| jv rE| j| S |j| krUt|jd| | j|< n| || j|< | j| 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.
        re   zI/O operation on closed file: NzUnable to resolve [r   z], returning NullObject insteadr   )r   r   re   closedr   r  r   r"   	__class__rS   r@   r  r}   r>   r   r   )r   r   real_objr  rb   rb   rc   r  2  s$   




z"PdfWriter._resolve_indirect_objectc                 C   s0   | j |d }t|d| }| |ksJ |S Nr   r   )r|   r   r>   r   )r   r   r   refrb   rb   rc   get_referencej  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   rF   r   r   r   r   r|   r   r>   r   rp   r   r?   )r   outliner  r   outline_refrb   rb   rc   get_outline_rootp  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 §8.3.2 from PDF 1.7 spec.

        Returns:
            An array (possibly empty) of Dictionaries with ``/F`` and
            ``/I`` properties.
        )r   THREADSr   r   r5   r?   )r   threadsrb   rb   rc   get_threads_root  s   
zPdfWriter.get_threads_rootc                 C      |   S )u   
        Read-only property for the list of threads.

        See §8.3.2 from PDF 1.7 spec.

        Each element is a dictionaries with ``/F`` and ``/I`` keys.
        )r  r   rb   rb   rc   r    s   	zPdfWriter.threadsc                 C   s(  t j| jv rit| jt j tritt| jt j }|j}t j|v rNt|t j trNtt|t j }|j}t j|v rBtt|t j }|S t }||t	t j< |S t }| 
|}||t	t j< t }||t	t j< |S t }| 
|}|| jt	t j< t }| 
|}||t	t j< t }||t	t j< |S rh   )r   r   r   r   r;   r   r   DESTSr5   r?   r   )r   r   	names_refdests	dests_refndrb   rb   rc   get_named_dest_root  s:   



zPdfWriter.get_named_dest_rootpage_destination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      dS )Nr   rb   )r  yrb   rb   rc   rk     s    z8PdfWriter.add_outline_item_destination.<locals>.<lambda>r   r   )r   r   r   r   add_outline_item_destinationr:   r   r>   r   r<   r   r  r6   r?   rF   r   insert_childinc_parent_counter_outlinerA   )r   r  r  r  r  page_destination_refrb   rb   rc   r    s6   



z&PdfWriter.add_outline_item_destinationoutline_itemc                 C   sx   t  }|| d|v r4t }tt|d }t| D ]\}}	|	|tt|< q| |}
|
|td< | 	||||S )N/A)
rF   rp   r;   r   r   rC  r?   r   r   r  )r   r  r  r  r  outline_item_objectr   a_dictr   r!  
action_refrb   rb   rc   add_outline_item_dict  s   

zPdfWriter.add_outline_item_dictFtitle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_itemr>   r   r   r   r   
IndexErrorrA   r"   rS   r@   r:   r?   r   r;   r(   Dr   S_create_outline_itemr  r  )r   r  r   r  r  r  r  r  r   r  r  page_refr   r  rb   rb   rc   r    sT   



zPdfWriter.add_outline_itemc                 C   s   t d)NzIThis method is not yet implemented. Use :meth:`add_outline_item` instead.)NotImplementedErrorr   rb   rb   rc   add_outlineL  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   )r  r   r   rE   r   )r   r  r  r  r  rb   rb   rc   add_named_destination_arrayQ  s   z%PdfWriter.add_named_destination_arrayc                 C   s&   |  |j}| td|d | |S )NrE   /Title)r   r   r  r   )r   r  r  rb   rb   rc   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;   rp   r?   r(   r  r5   r,   FIT_HrA   r  r   r   rE   r   r  )r   r  r   r  r   dest_refrb   rb   rc   add_named_destinationk  s   

	
zPdfWriter.add_named_destinationc                 C      | j D ]	}| |tj qdS )z.Remove links and annotations from this output.N)r   remove_objects_from_pagerR   r]   r   r   rb   rb   rc   remove_links     
zPdfWriter.remove_linkssubtypesc                 C   s   | j D ]}| || qdS )aB  
        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   rb   rb   rc   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   r6  r   )r   r;   r   r   ro  r   r5   r   r   r>   r@   r|   r   )r   r   r
  r  anr   rb   rb   rc   r    s   

z"PdfWriter._remove_annots_from_page	to_deletec              	      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
@ rag dddg g d g d	 d
g tj@ rjg ddtdtt dtt 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
        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formsrg   c                    s   d}|t | jk r<| j| \}}|dkrtj@ s,| v s,|dkr1tj@ r1|d |v r1| j|= n|d7 }|t | jk s	|   d S )Nr   s   INLINE IMAGEs   Dor   )r   
operationsrR   r_   r^   get_data)r&  r'  r(  r  operandsoperator)jump_operatorsr  rb   rc   clean  s   
z1PdfWriter.remove_objects_from_page.<locals>.cleaneltr  c              
      s  | |v rg g fS zt tttf t t| d d }W n ty%   i }Y nw g }g }| D ]o\}}| }z\d }tj@ rL|d dkrLt	 }|
| |d dkrx|
| t|tr_|}nt|}|dd | D  ||| g  |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:  r5  r6  z/Imager7  c                 S   s   i | ]\}}|d vr||qS ))r9  z/Filterz/DecodeParmsrb   )r  k1v1rb   rb   rc   r#  	  s
    zKPdfWriter.remove_objects_from_page.<locals>.clean_forms.<locals>.<dictcomp>r   )r   r   r   r;   r   rC  r   rR   r^   r@   r   r   r8   rp   r>   r|   r   r   	TypeErrorrD   )r/  r  dr'  r(  r   r!  r   r&  ime)r.  clean_formsr   r  rb   rc   r6    sb   








z7PdfWriter.remove_objects_from_page.<locals>.clean_formsz	/Contents)r   r   r   r  rR   rZ   r  r[   r\   r]   r`   rY   r8   r   r   r;   r   r   r   r   get_contentsreplace_contents)r   r   r  to_dr&  r'  r(  rb   )r.  r6  r-  r   r  rc   r    sZ   





(
;z"PdfWriter.remove_objects_from_pagec                 C   sn   t |trtj}|tj@ rtjntj|tj@ rtjntjB |tj@ r%tjntjB }| 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)
        N)r   rn  r)   ALLr^   rR   rV   r_   r`   r   r  )r   r  r  r   rb   rb   rc   remove_images-  s"   

zPdfWriter.remove_imagesc                 C   r  )zRemove text from this output.N)r   r  rR   rY   r  rb   rb   rc   remove_textN  r	  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 rb   r?   r  rf  rb   rb   rc   r  m      z%PdfWriter.add_uri.<locals>.<listcomp>r     c                 S   r@  rb   rA  rB  rb   rb   rc   r  o  rC  r   r   z/URIz/Annotr  z/H/Ir  )r   r   r   r   r   r   r   r   r   r5   r   rA   r   r?   rC   r;   rp   rE   r<  r   SubtypePr=  Borderr   r   ro  )r   r   r=  r>  r?  	page_linkr  
border_arrdash_patternlnk2lnklnk_refrb   rb   rc   add_uriS  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   rN   r   r   r   rb   rb   rc   _get_page_layout  
   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: rv   rQ  N)r   r?   _valid_layoutsr"   rB  rS   r   rp   r   rT  rb   rb   rc   _set_page_layout  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rW  rV  rb   rb   rc   set_page_layout  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
        )rR  r   rb   rb   rc   page_layout  s   zPdfWriter.page_layoutc                 C   s   |  | d S rh   rX  rV  rb   rb   rc   rZ    s   )z/UseNonez/UseOutlinesz
/UseThumbsz/FullScreenz/UseOCz/UseAttachmentsc                 C   rP  )N	/PageMode)r   rQ   r   r   r   rb   rb   rc   _get_page_mode  rS  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
        )r\  r   rb   rb   rc   	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, r[  )r   r?   _valid_modesr"   rB  rS   r   rp   )r   r  	mode_namerb   rb   rc   r]  %  s   


annotationc                 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 can not 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 pop-up creation, for example
        zpage: invalid type/PN/Annotsr6  r  /Destz	/LinkNametarget_page_indexr   fit_args)fit_typere  z/Popupr  )r   r   r   r   r2  r   r;   _pdf_objectifyr   r?   annotationsr5   r   r   r   r:   r<   dictr   r   r   r   )r   r   r`  r   to_addtmpr   rb   rb   rc   add_annotation1  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 nameddestination to TextStringObject
        (required for names/dests list)

        Args:
            page:

        Returns:
            The cleaned PageObject
        r   rb  rc  Nr  /D)r   r   r   r   r?   rE   )r   r   aa_objr3  actrb   rb   rc   
clean_pagef  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)Nrbr   r  ri   zPdfMerger.merge 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   ri   r   r   re   r  r  r   r  )r   rw   encryption_objrz  re   	orig_tellfilecontentrb   rb   rc   _create_stream  s0   	



zPdfWriter._create_stream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 )aP  
        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
        Nrb   )r   r   r   rJ   rn  merge)r   rw   r  r   rw  rx  rb   rb   rc   r     s0   )

	zPdfWriter.appendpositionc              
   C   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 ]G}t |trj|}n|j| }|jdusvJ |du r| |t|g d |
|jj< n| ||t|g d |
|jj< |d7 }||
|jj _q`|j|_|j D ]}|j}d	| jv r|d
 ttt tttt| jd	 d d	 v rqt |d trqt |d tr|j|d  }|jdusJ zt|
|jj j|td< | |d
 | W q ty   Y qw |d jj|
v r2|
|d jj j|td< | |d
 | q|durOtd| j t!|t"t#|
 jt$d% }n| & }td|j't(j) }|rxt*j+|v rx| ,|-t*j+d|
|}| .||d d|vr|
 D ]"}| /|j-dd||
|}t|dkr||t0d< | 1| qd|v r4|d dur4d| jvr| 2tttt|j'd d 3| dd| jt0d< t4 }ntt4tt| jd d }| j5t6| }z/|j'd d d D ]#}zt7||j d| }||vr|8| W q ty   Y qw W n ty'   | 2t4 }Y nw |tt| jd t0d< d|vrB| 9d|
| 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)strictNrb   r  z:"pages" must be a tuple of (start, stop[, step]) or a list)r   /Br   rb  r   r   r   z/Destsr  r   rF   )r   r;   rb  r  z/Root)/Fieldsr}  r|  rv   ):r   r   rv  r   r  r   r   rJ   indicesr   r2  r   r   r   r   r   original_pagenamed_destinations_namedDestsvaluesr   r   r   r   r   r;   r@   r   rA   r   r  r   r  rE   nextro   r4   r   r  r~  r  r  r   r  _get_filtered_outliner   _insert_filtered_outline_insert_filtered_annotationsr?   rq  r   r   r5   r~   r   r>   r   add_filtered_articles)r   rz  rw   r  r   rw  rx  r  re   rs  srcpagesr   pgr   arrr   outline_item_typ_ror  pagry  trslatrz  indrb   rb   rc   ry    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   )force_duplicateignore_fieldsr;   r   Nr   ra  r)  r;  r  z/Rr|  r5   )r   r  r   r   r   _get_cloned_pager   r;   r   r?   r5   )r   r  r   r  nthreadfirst_articlecurrent_articlenew_articler  	new_firstnew_article2pag_objrb   rb   rc   _add_articles_thread	  s^   %zPdfWriter._add_articles_threadfltrc                 C   s   t |trt|}n
t |tstd}| D ]A}|j}|ddD ]5}| d}|du r2q$| }|j	j
| jt| vrY|d|v rK|d ni ddrY| ||| q$qdS )z
        Add articles matching the defined criteria.

        Args:
            fltr:
            pages:
            reader:
        rv   r|  rb   r  NrE  r   )r   r   recompiler   r  r  r   r   r   r   r~   r   searchr  )r   r  r   r  r   pprn  thrrb   rb   rc   r  	  s(   



 zPdfWriter.add_filtered_articlesc                 C   sz   t |trd S t |tr|j| j}nt |tr$|dddkr$|j}nt |tr+|}z||j jW S  t	y<   Y d S w )Nr4  rv   r  )
r   r@   r   r   r   r;   r   r>   r   r   )r   r   r   r  _irb   rb   rc   r  	  s   


zPdfWriter._get_cloned_pageannotsc                 C   s  t  }t|trtd| }|D ]}td| }|d dks3d|vs3td|d d dks3d|v rd|vrC|| ||  q|d }t|tr^t|| 	 v r]||| j
 qtd	|}| |d
 ||}	|	d ur|j| dd}
t |	g|dd   |
td< || |
 qtd|d d }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;   r6  r  r  r   r  rc  r5   r   )rc  )r  r   rm  )rm  )r5   r   r>   r   r   r   r   r   r   r  r   r  r?   )r   r  r   r   r  outlistr  anor3  r   ancrb   rb   rc   r  
  sN   




z&PdfWriter._insert_filtered_annotationsnodec                 C   s(  g }|du r	t  }| }t|t rt }|dddks!d|vr:|dd}|dur8| }|| |||7 }|S |dur| }td||}| td|d	 ||}|du r]t  }||t	d	< d|v rr| |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.
        Nr4  rv   	/Outlinesr   /Firstr:   r   r  r   /Next)r@   r   r   r;   r   r  r   _build_outline_itemr  r?   childsr   r   )r   r  r   r  new_outliner   r!  rb   rb   rc   r  A
  s6   

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   r  r  rc  r   r   /Cg        )rF   r   rE   r?   r   r@   r  r   r   rA   r   r5   r=   )r   r   n_olrb   rb   rc   _clone_outlineo
  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 )Nr4  rv   r  r   )r   r  r   rF   r   r  r  r  )r   r  r  r  r   nprb   rb   rc   r  
  s   
z"PdfWriter._insert_filtered_outlinec                 C   r  )z#To match the functions from Merger.Nrb   r   rb   rb   rc   r  
  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 )NrF   r   r   r  r  r   )r  r   r   r   find_outline_itemrP   rF   )r   r  r  r   r  resrb   rb   rc   r  
  s&   


zPdfWriter.find_outline_itemc                 C   s   |  ||S )zZ
        .. deprecated:: 2.9.0
            Use :meth:`find_outline_item` instead.
        )r  )r   r  r  rb   rb   rc   find_bookmark
  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)a/  
        Reset the translation table between reader and the writer object.

        Late cloning will create new independent objects.

        Args:
            reader: PdfReader or IndirectObject refering a PdfReader object.
                if set to None or omitted, all tables will be reset.
        Nzinvalid parameter {reader})r~   r   r   r   r   r>   r   )r   r  rb   rb   rc   reset_translation
  s   


zPdfWriter.reset_translationpage_index_frompage_index_tostyleprefixstartc                 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 )	aL  
        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 to 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.
        Nz3at least one between style and prefix must be givenr   z/page_index_from must be equal or greater then 0z;page_index_to must be equal or greater then page_index_fromz%page_index_to exceeds number of pagesr   z1if given, start must be equal or greater than one)r   r   r   _set_page_label)r   r  r  r  r  r  rb   rb   rc   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 to 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.
        rm  r   Nra  r   z/Stz/Numsr   )r;   r?   rE   rA   r%   PAGE_LABELSr   r5   r   rF   r   r   r   r   r   )r   r  r  r  r  r  default_page_labelnew_page_labelnumspage_labelsnext_label_posrZ  rb   rb   rc   r    s4   !zPdfWriter._set_page_label)rv   N)rg   ru   )rb   )T)r   rb   )NN)NNr   rh   )NNN)rg   N)NNT)NNTN)NNTrb   )rS   rT   rU   __doc__r   r   r   r   r   r   r   r   BaseExceptionr   r   propertyr   r   setterrB   r>   r   r   r   r   r   r	   r   r   r   r   rn  r   rG   r   r   r   r   r   r   r   r   rA  r   decimalDecimalr   r:   rE   r7   r   r   r  r  r;   r  rg  OPTIONAL_READ_WRITE_FIELDr   r&   r{  r  r  r   r  r  ALL_DOCUMENT_PERMISSIONSr-   r  r   r  r   r   r   r  r  r  r  r5   r6   r=   r?   rA   r@   r  r  r  rF   r  r  r  r  r  rO   r  r4   r<   r  r  r  r  r  r  rL   r  r  rR   r  r)   r:  r;  r<  rC   rO  rU  rN   rR  rW  rY  rZ  r^  rQ   r\  r]  rl  rq  r   r   rv  rJ   r   rK   ry  r  r   r  r  r  r  r  r  r  rP   r  r  r  r+   r  r  rb   rb   rb   rc   ru      s   

:









" 



! #[
  

[
2
 
:&	
`8
&
)
	

M








 
!

B
"	


5
)$

G
 5

@


!



2

.




 




6ru   r   c                 C   s   t | tr| S t | tr&t }|  D ]\}}t|}t|}|||< q|S t | tr4tdd | D S t | t	rF| 
drBt| S t| S t | ttfrQt| S tdt|  d)Nc                 s   rk  rh   )rg  )r  elrb   rb   rc   r1  X  rl  z!_pdf_objectify.<locals>.<genexpr>r  z
type(obj)=z! could not be casted to PdfObject)r   rB   ri  r;   rC  r?   rg  r   r5   r   
startswithrE   r   rA  r=   r  type)r   rj  r  rx  name_keycasted_valuerb   rb   rc   rg  M  s(   





rg  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|rPd}|r?|d7 }|rE|d7 }|td	t|i |S )
Nr  r   r  c                 S   r@  rb   )r=   r.  rb   rb   rc   r  y  rC  z(_create_outline_item.<locals>.<listcomp>r   r   r   r   )	rF   r?   rp   rH   r   r   rI   r5   rA   )r  r  r  r  r  r  format_flagrb   rb   rc   r  f  s*   
r  )rd   )yr   r  r  rW   rm   r  r   ior   r   r   pathlibr   typesr   typingr   r   r	   r
   r   r   r   r   r   r   r   r   r   _cmapr   r   r   r   _pager   r   _page_labelsr   r   r   _readerr   _utilsr   r   r    r!   r"   	constantsr#   r<  r$   r   r%   r&   r'   r(   r)   r*   r+   r,   r-   r   r.   r   r/   rD  r0   r   r1   r   r2   r  errorsr3   genericr4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   	pagerangerJ   rK   rL   rM   rN   rO   rP   rQ   r  allr  IntFlagrR   r   r   rt   ru   rg  rA  rn  r  rb   rb   rb   rc   <module>   s   <,` 	                     *N
