a
    ˜ëj7- ã                   @   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mZmZm	Z	 d dl
mZmZmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZmZmZmZmZmZmZ ejd	krÄd d
lmZ n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( ddl)m*Z*m+Z+m,Z, ddl-m.Z. ddl/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5 ddl6m7Z7m8Z8 ddl9m:Z; ddl9m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZD ddl9mEZF ddl9mGZH ddl9mIZJ ddlKmLZLmMZMmNZN ddlOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZambZbmcZcmdZdmeZemfZfmgZgmhZhmiZi ddljmkZk ddllmmZmmnZn ddlmoZompZpmqZqmrZrmsZsmtZt ddlumvZv eD w¡ ZxG dd„ dejyƒZzd,ee{e|d!œd"d#„Z}G d$d%„ d%e"ƒZ~eee|ef e|e€e�e f e_d&œd'd(„Z‚eeZdf e|eeƒe€e€e€f e|df e„e„edd)œd*d+„Z…dS )-é    N)ÚIterableÚMappingÚSequence)ÚBytesIOÚFileIOÚIOBase)Úcompress)ÚPath)ÚPattern)ÚTracebackType)ÚIOÚAnyÚCallableÚLiteralÚOptionalÚUnionÚcast)é   é   )ÚSelfé   )ÚDocumentInformationÚPdfDocCommon)ÚEncryptAlgorithmÚ
Encryption)Ú
PageObjectÚTransformation)Únums_clear_rangeÚnums_insertÚ	nums_next)Ú	PdfReader)ÚStrByteTypeÚ
StreamTypeÚ_get_max_pdf_version_headerÚdeprecate_with_replacementÚdeprecation_no_replacementÚlogger_warning)ÚActionÚ
JavaScript)ÚAnnotationDictionaryAttributes)	ÚCatalogAttributesÚCoreÚGoToActionArgumentsÚ	ImageTypeÚInteractiveFormDictEntriesÚOutlineFontFlagÚPageLabelStyleÚPagesAttributesÚUserAccessPermissions)ÚFieldDictionaryAttributes)ÚPageAttributes)ÚTrailerKeys)ÚLimitReachedErrorÚPdfReadErrorÚ
PyPdfError)ÚPAGE_FITÚArrayObjectÚBooleanObjectÚByteStringObjectÚContentStreamÚDestinationÚDictionaryObjectÚEmbeddedFileÚFitÚFloatObjectÚIndirectObjectÚNamedReferenceLinkÚ
NameObjectÚ
NullObjectÚNumberObjectÚ	PdfObjectÚRectangleObjectÚReferenceLinkÚStreamObjectÚTextStringObjectÚ
TreeObjectÚViewerPreferencesÚcreate_string_objectÚextract_linksÚ
hex_to_rgbÚis_null_or_none)ÚTextStreamAppearance)Ú	PageRangeÚPageRangeSpec)ÚAnnotationSubtypeÚBorderArrayTypeÚ
LayoutTypeÚOutlineItemTypeÚOutlineTypeÚPagemodeType)ÚXmpInformationc                   @   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© rl   rl   úL/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/pypdf/_writer.pyr]   ‚   s   r]   é   )ÚstreamÚ	blocksizeÚreturnc                    s8   t jdd�}t‡ ‡fdd„dƒD ]}| |¡ q | ¡ S )NF)Úusedforsecurityc                      s
   ˆ  ˆ ¡S ©N)Úreadrl   ©rp   ro   rl   rm   Ú<lambda>‘   ó    z#_rolling_checksum.<locals>.<lambda>rw   )ÚhashlibÚmd5ÚiterÚupdateÚ	hexdigest)ro   rp   Zhash_objectÚblockrl   ru   rm   Ú_rolling_checksum�   s    r~   c                       sL  e Zd ZU dZeed< eee  ed< e	e
e	ee
ed f ef f ed< ee ed< �dd	d
ddœeeeedf eeeedf eeeeee
 ee
 ddœ	dd„Zeedœdd„ƒZeedœdd„ƒZeee dœdd„ƒZejeeeef  ddœdd„ƒZeee dœdd„ƒZejeeedf ddœdd„ƒZeedœdd„ƒZejeddœdd„ƒZedœdd „Zeee   ee  ee! dd!œd"d#„Z"ee#dœd$d%„ƒZ$e$jee#ef dd&œd'd%„ƒZ$eed(œd)d*„Z%ee
ef ed+œd,d-„Z&ee
ef eed.œd/d0„Z'�de(e
e)e# e(d2œd3d4„Z*�dedd6œd7d8„Z+e,dœd9d:„Z-�de(e)e# e(d;œd<d=„Z.�de(e
e)e# e(d2œd?d@„Z/ee
e0edf ee
 d+œdAdB„Z1�dee2 ee2 e(dCœdDdE„Z3�d eee2e4j5f  eee2e4j5f  e
e(dFœdGdH„Z6eee7e8e9df dœ‡ fdIdJ„ƒZ:e:jee#e7e(df ddKœdLdJ„ƒZ:e#ddMœdNdO„Z;e<ddPœdQdR„Z=e#ee#ef dSdTœdUdV„Z>�d!eee?e(gdf  ddWœdXdY„Z@e(eddZœd[d\„ZAe(eBe#e2e2dd]œd^d_„ZCeD Ed>¡ZFeFd5d	fee(ee( df eGe#ee#ee# eHe#e#e2f f f eDjEee edd`œdadb„ZI�d"ee( ee dcœddde„ZJeee
 dfœdgdh„ZKeddfœdidj„ZL�d#eee?e(gdf  ddWœdkdl„ZMe9dœdmdn„ZNddœdodp„ZOdd5ePfddqœe#ee# eeQee# ddrœdsdt„ZRddœdudv„ZSeTddwœdxdy„ZUeeef eHeeVe f dwœdzd{„ZWee dœd|d}„ZXeTddwœd~d„ZYeTeHee
 ee
 f dwœd€d�„ZZeTee
 ee
 e
d‚œdƒd„„Z[eTe
dd…œd†d‡„Z\eee] dœ‡ fdˆd‰„ƒZ^e^jeee]ee	eef f  ddœdŠd‰„ƒZ^e	e#ef dd‹œdŒd�„Z_e`ƒ Zaeaeafd5d5dŽœeeeedd�œd�d‘„Zbeed(œd’d“„Zceddœd”d•„Zeefdœd–d—„Zgeefdœd˜d™„ƒZh�d$eee(edf eededf eededf eedšœd›dœ„Zi�d%ejeededf eededf eed�œdždŸ„Zkdddd	d	eld5fe#ee(ee
df eededf eededf eeeHe2e2e2f e#f  eeemeed œ
d¡d¢„Znddœd£d¤„Zoe8eeeff dd¥œd¦d§„Zpeed¨œd©dª„Zqe
ed«œd¬d­„Zr�d&e#e
eem ed®œd¯d°„Zsddœd±d²„Zteeeue)eu f  dd³œd´dµ„Zveee(ef ee)e#  dd¶œd·d¸„Zw�d'ee(ef eexe)ex f ee	e#ef  dd¹œdºd»„Zy�d(ezee# ee# ee exee	e#ef  dd¼œd½d¾„Z{�d)eee ee exee	e#ef  eHee# ee# f d¿œdÀdÁ„Z|e}j~fe}ddÂœdÃdÄ„Z�d*eee#  ddÅœdÆdÇ„Z€�d+e
e#e�ee‚e  ddÈœdÉdÊ„ZƒdËZ„ee… dœdÌdÍ„Z†ee‡e…f ddÎœdÏdÐ„Zˆe…ddÎœdÑdÒ„Z‰eee… dœdÓdÔ„ƒZŠeŠje…ddÎœdÕdÔ„ƒZŠdÖZ‹eeŒ dœd×dØ„Z�eeeŒ dœdÙdÚ„ƒZŽeŽjeŒddÛœdÜdÚ„ƒZŽee
e(f e	e#ef edÝœdÞdß„Z�ee(ef e(dcœdàdá„Z�eeeef eHe‘ee’ f dâœdãdä„Z“�d,eeeef ee#e”eHe
e
f eHe
e
e
f ee
 df ee”eHe
e
f eHe
e
e
f ee
 ee( df eeeee# eHe#dåf f  ddæœdçdè„Z•�d-ee
 eeeef ee# eee–ee( f  eeeee# eHe#dåf f  ddéœdêdë„Z—ee˜e	e
e(f ddìœdídî„Z™ee	e
e(f eedïœdðdñ„Zšee›e e#f e	e
e(f eddòœdódô„Zœeee(e0e
df e	e
e(f eee dõœdöd÷„Z�ddøœeeee df e(e	e
e(f eee	e
ef  ee7 dùœdúdû„Zžee	e
ef edüœdýdþ„ZŸe	e
ef eddÿœ�d �d„Z d�dœee	e
e(f eee¡e
  ee7 �dœ�d�d„Z¢e7eddKœ�d�d„Z£�d.ee7 eedef eededf d�dœ�d	�d
„Z¤ddœ�d�d„Z¥�d/d�dœeee#f ee¦ ee¡e
  eee
  �dœ�d�d„Z§�d0eeedf ddfœ�d�d„Z¨�d1e
e
ee© ee# ee
 d�dœ�d�d„Zª�d2e
e
ee© ee# ee
 d�dœ�d�d„Z«�d3ee)e# df ee)e# df e	e#ef �dœ�d�d„Z¬‡  Z­S (4  Ú	PdfWriteraP  
    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.

        strict: If true, pypdf will raise an exception if a PDF does not follow the specification.
            If false, pypdf will try to be forgiving and do something reasonable, but it will log
            a warning message. It is a best-effort approach.

        keep_initial_header: If true, the PDF header of the cloned document is kept
            when using ``clone_from`` in non-incremental mode.

    ÚincrementalÚ_objectsZ	PreventGCÚ_id_translatedÚ_readerÚ NFi ¡ i@B )Úkeep_initial_headerÚ$incremental_clone_object_count_limitÚ!incremental_clone_object_id_limit)	ÚfileobjÚ
clone_fromr€   ÚfullÚstrictr…   r†   r‡   rq   c             	   C   sÎ  || _ |p|| _g | _g | _i | _i | _|  d | _d | _g | _i | _	t
|tƒrR|ntj| _t
|tƒrh|ntj| _| jrút
|ttfƒr¼t|dƒ�}	t|	 d¡ƒ}W d   ƒ n1 s²0    Y  t
|tƒrÎt|ƒ}t
|tƒsàtdƒ‚|| _|j ¡ | _d| _n"d| _|  ttdƒtdƒiƒ¡| _t tttt!t" td f t tttt!t" td f t tttt!t" td f dœ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�rt
|tƒ�sìt|ƒ}|  0|¡ d| _&|�rV| j�sV|j ¡ | _n>|  |¡| _1ttt'j(ƒtt2j3ƒtt2j4ƒ| j1iƒ| _5|  | j5¡ |�rh|�shd| _t
| jt6ƒ�rÊt
| jd t7ƒ�r t8| jd  9¡ ƒ| jd< t
| jd t7ƒ�rÊt8| jd  9¡ ƒ| jd< d S )NÚrbéÿÿÿÿz!Invalid type for incremental modeTs   %PDF-1.3z	/ProducerZpypdf)rˆ   r‰   rq   c                 S   sž   t | ttttfƒr&| dks"|d ur&|S d}t | ttfƒr\t| ƒ}| ¡ rV| ¡ jdkr’d}n6t | ttfƒr’|  	¡ }|  
dd¡dkr†d}|  
|d¡ |rš| }|S )Nr„   Tr   Fé   )Ú
isinstanceÚstrr	   r   r   ÚexistsÚstatÚst_sizer   ÚtellÚseek)rˆ   r‰   ZcloningZfileobj_pathÚtrl   rl   rm   Ú_get_clone_from  s&    ÿÿz+PdfWriter.__init__.<locals>._get_clone_fromr„   Fú/Pagesr   r   ):r‹   r€   r�   Ú_original_hashÚ_idnum_hashr‚   rƒ   Ú_IDÚ_unresolved_linksÚ_merged_in_pagesr�   ÚintÚsysÚmaxsizeÚ%_incremental_clone_object_count_limitÚ"_incremental_clone_object_id_limitr�   r	   Úopenr   rt   r    r8   Ú
pdf_headerÚencodeÚ_headerZ	_readonlyÚ_add_objectr?   rE   rO   Ú	_info_objr   r   r   Útemp_fileobjrˆ   Ú_with_as_usageÚ_clonedr1   ÚTYPEÚCOUNTrG   ÚKIDSr:   Úflattened_pagesÚ_encryptionÚ_encrypt_entryÚclone_document_from_readerÚ_pagesr+   ZCATALOGZPAGESÚ_root_objectÚlistrL   r<   Zget_original_bytes)Úselfrˆ   r‰   r€   rŠ   r‹   r…   r†   r‡   Úfr—   Úpagesrl   rl   rm   Ú__init__È   s’    
ÿýÿ,

ÿÿý
ýÿ

þÿzPdfWriter.__init__)rq   c                 C   s   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.
        Frl   ©r¶   rl   rl   rm   Úis_encryptedY  s    zPdfWriter.is_encryptedc                 C   s   | j S )zw
        Provide direct access to PDF Structure.

        Note:
            Recommended only for read access.

        )r´   rº   rl   rl   rm   Úroot_objectc  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º   rl   rl   rm   Ú_infon  s    ÿýzPdfWriter._info)Úvaluerq   c              	   C   sˆ   |d u r@zd | j | jjjd < W n ttfy6   Y n0 d | _nD| jd u rX|  tƒ ¡| _tt| j 	¡ ƒ}| 
¡  | tt| 	¡ ƒ¡ d S )Nr   )r�   r¨   Úindirect_referenceÚidnumÚKeyErrorÚAttributeErrorr§   r?   r   r½   Úclearr{   )r¶   r¿   Úobjrl   rl   rm   r¾   }  s    
c                 C   s   t t| jjƒS )ú(XMP (Extensible Metadata Platform) data.)r   r\   r¼   Úxmp_metadatarº   rl   rl   rm   rÇ   Œ  s    zPdfWriter.xmp_metadatac                 C   sœ   |du rd| j v r| j d= dS | j  dd¡}t|tƒsf|durF| j d= tƒ }|  |¡}|| j tdƒ< ntt| ¡ ƒ}t|t	ƒrŠ|j
 ¡ }n|}| |¡ dS )rÆ   Nz	/Metadata)r¼   Úgetr�   rC   rK   r§   rE   r   r½   r\   ro   Úget_dataÚset_data)r¶   r¿   ÚmetadataZmetadata_streamZstream_referenceÚ
bytes_datarl   rl   rm   rÇ   ‘  s     



c                 C   s   t ddƒ d S ©NÚwith_as_usagez5.0©r%   rº   rl   rl   rm   rÎ   ©  s    zPdfWriter.with_as_usagec                 C   s   t ddƒ d S rÍ   rÏ   ©r¶   r¿   rl   rl   rm   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–   rl   rl   rm   Ú	__enter__±  s    zPdfWriter.__enter__)Úexc_typeÚexcÚ	tracebackrq   c                 C   s   | j r| js|  | j ¡ dS )zWrite data to the fileobj.N)rˆ   r«   Úwrite)r¶   rÓ   rÔ   rÕ   rl   rl   rm   Ú__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º   rl   rl   rm   r¤   Å  s    zPdfWriter.pdf_header)Ú
new_headerrq   c                 C   s   t |tƒr| ¡ }|| _d S rs   )r�   r�   r¥   r¦   )r¶   rÙ   rl   rl   rm   r¤   Ò  s    
©rÅ   rq   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?   rÈ   ÚPGZCONTENTSr:   r§   rE   r�   ÚappendrC   Úlen)r¶   rÅ   rl   rl   rm   r§   Ø  s    ÿ
þÿzPdfWriter._add_object)rÀ   rq   c                 C   sZ   t |tƒr| j|d  }n$|j| kr.tdƒ‚n| j|jd  }|d u rVtd|›d�ƒ‚|S )Nr   úPDF must be selfzObject z not found!)r�   rž   r�   rÜ   Ú
ValueErrorrÁ   r7   ©r¶   rÀ   rÅ   rl   rl   rm   r½   ç  s    


zPdfWriter.get_object)rÀ   rÅ   rq   c                 C   sŒ   t |tƒr"|j| krtdƒ‚|j}| j|d  jj}t|dd ƒd urZ|jj| krZ| 	| ¡}|| j|d < t||| ƒ|_t |t
ƒsˆJ dƒ‚|S )Nrà   r   rÀ   Úmypy)r�   rC   rÜ   rá   rÁ   r�   rÀ   Z
generationrÛ   ÚclonerH   )r¶   rÀ   rÅ   Úgenrl   rl   rm   Ú_replace_objectõ  s    

ÿ
þ
zPdfWriter._replace_objectrl   )ÚpageÚindexÚexcluded_keysrq   c                 C   sü  t |tƒr| tjd ¡tjkr&tdƒ‚| jd us8J dƒ‚|}t	|ƒ}|tj
dg7 }z| jt|jjƒ |jj= W n$ ty‚   ‚ Y n ty’   Y n0 td| | d|¡ ¡ ƒ}|jd urÌ|jj}t| j|ƒ| _|  |¡\}}|j|ttj
ƒ< |dk�rtt|tj ƒ ||j¡ | j ||¡ n$tt|tj ƒ |j¡ | j |¡ |}d}	t|ƒ�sÂ|d u�sfJ dƒ‚tt| ¡ ƒ}
ttt |
tj! ƒd ƒ|
ttj!ƒ< |
 tj
d ¡}|	d7 }	|	dk�rJt"d	ƒ‚�qJ|jd u�rød
|v�rê| j# $t%||ƒ¡ |j| j&|j< |S )NzInvalid page objectrã   z/StructParentsr   Fr   r   iè  zToo many recursive calls!ú/Annots)'r�   r   rÈ   r1   r¬   r+   ZPAGErá   r¯   rµ   ÚPARENTr‚   ÚidrÀ   rÜ   rÁ   ÚMemoryErrorÚ	Exceptionr   rä   r½   r¤   r#   Z_get_page_in_noderE   r:   r®   ÚinsertrÞ   rR   r?   rG   rž   r­   r8   rœ   ÚextendrP   r�   )r¶   rç   rè   ré   Zpage_orgÚotherÚnodeÚidxÚcurrentZrecurseZ	node_dictrl   rl   rm   Ú	_add_page
  sT    ÿÿ


"

zPdfWriter._add_pageT)Ústaterq   c              
   C   s˜   zLt j| jvr&|  tƒ ¡| jtt jƒ< ttjƒ}t|ƒt	t| jt j ƒ|< W nF t
y`   ‚ Y n4 ty’ } ztdt||d� W Y d}~n
d}~0 0 dS )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

        z6set_need_appearances_writer(%(state)s) catch : %(exc)s)Úsourcerö   rÔ   N)r*   Ú	ACRO_FORMr´   r§   r?   rE   r.   ZNeedAppearancesr;   r   rí   rî   r&   r^   )r¶   rö   Zneed_appearancesrÔ   rl   rl   rm   Úset_need_appearances_writerI  s(    
þÿ
þÿüz%PdfWriter.set_need_appearances_writerc                 C   s    t ƒ }|  |¡| jttjƒ< |S rs   )rN   r§   r´   rE   r*   ZVIEWER_PREFERENCES)r¶   Úorl   rl   rm   Úcreate_viewer_preferenceso  s    þÿz#PdfWriter.create_viewer_preferences)rç   ré   rq   c                 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é   rl   rl   rm   Úadd_pagev  s    zPdfWriter.add_pager   c                 C   s`   | j dusJ dƒ‚|dk r(|t| j ƒ7 }|dk r8tdƒ‚|t| j ƒkrR|  ||¡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é   rl   rl   rm   Úinsert_page�  s    zPdfWriter.insert_pagec                 C   sN   t |ƒrdS |dusJ dƒ‚t|tƒr2t|d| ƒ}| ¡ }t|tƒrJ|jS dS )zŽ
        Generate _page_id2num.

        Args:
            indirect_reference:

        Returns:
            The page number or None

        Nrã   r   )rR   r�   rž   rC   r½   r   Úpage_numberrâ   rl   rl   rm   Ú_get_page_number_by_indirect«  s    

z&PdfWriter._get_page_number_by_indirect)ÚwidthÚheightrq   c                 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ç   rl   rl   rm   Úadd_blank_pageÃ  s    zPdfWriter.add_blank_page)r   r  rè   rq   c                 C   s’   |   ¡ }t|ƒ|kr*td|› d|› d�ƒ‚|rtt||d ƒ}| j| j}|du sX|dkr^|j}|du sn|dkrt|j}t 	| ||¡}|  
||¡ |S )aŠ  
        Insert a blank page to this PDF file and return it.

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

        Args:
            width: The width of the new page in default user space units.
            height: The height of the new page 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.
            IndexError: Index is outside of [-self.get_num_pages(), self.get_num_pages()]
        zIndex should be in range [-ú, ú]r   Nr   )Zget_num_pagesÚabsÚ
IndexErrorÚminr¸   Úmediaboxr   r  r   r  rý   )r¶   r   r  rè   Z	num_pagesZfixed_indexr	  rç   rl   rl   rm   Úinsert_blank_pageÜ  s    zPdfWriter.insert_blank_pagec                    s   t ƒ jS rs   )ÚsuperÚopen_destinationrº   ©Ú	__class__rl   rm   r    s    zPdfWriter.open_destination)Údestrq   c                 C   sœ   |d u r*z| j d= W q˜ ty&   Y q˜0 nnt|tƒrHt|ƒ| j tdƒ< nPt|tƒrd|j| j tdƒ< n4t|tƒr˜td|j	d ur‚|j	nt
ƒ tƒj| j tdƒ< d S )Nz/OpenActionZOpening)r´   rÂ   r�   r�   rL   rE   r>   Ú
dest_arrayr   rÀ   rF   r9   )r¶   r  rl   rl   rm   r    s"    


ÿû)Ú
javascriptrq   c                 C   s   t dddƒ |  t|ƒ¡ dS )a…  
        Add JavaScript which will launch upon opening this PDF.

        Args:
            javascript: Your JavaScript.

        Example:
            This will launch the print window when the PDF is opened.

            >>> from pypdf import PdfWriter
            >>> output = PdfWriter()
            >>> output.add_js("this.print({bUI:true,bSilent:false,bShrinkToFit:true});")

        Úadd_jsÚadd_open_actionú7.0.0N)r$   r  r(   )r¶   r  rl   rl   rm   r    s    zPdfWriter.add_js)Úactionrq   c                 C   s   t  | |¡S )aÎ  
        Add an action to the document-level JavaScript name tree.

        Args:
            action: The action to add.

        Example:
            This will launch the print window when the PDF is opened.

            >>> from pypdf import PdfWriter
            >>> from pypdf.actions import JavaScript
            >>> output = PdfWriter()
            >>> output.add_open_action(JavaScript("this.print({bUI:true,bSilent:false,bShrinkToFit:true});"))
        )r'   Z_create_open_action)r¶   r  rl   rl   rm   r  1  s    zPdfWriter.add_open_actionr@   )ÚfilenameÚdatarq   c                 C   s   t  | ||¡S )aq  
        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.

        Returns:
            EmbeddedFile instance for the newly created embedded file.

        )r@   Z_create_new)r¶   r  r  rl   rl   rm   Úadd_attachmentB  s    zPdfWriter.add_attachment)ÚreaderÚafter_page_appendrq   c                 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_pagerl   rl   rm   Úappend_pages_from_readerT  s    


z"PdfWriter.append_pages_from_reader)rç   Únew_content_datarq   c                 C   sÀ   t dƒ|v rš|t dƒ }| ¡ }t|tƒr\tƒ }| |¡ | |  |¡¡ |  |¡|t dƒ< t|tƒr¼| ¡ d | }tƒ }| |¡ |  |¡|t dƒ< n"tƒ }| |¡ |  |¡|t dƒ< dS )a*  
        Combines existing content stream(s) with new content (as bytes).

        Args:
            page: The page to which the new content data will be added.
            new_content_data: A binary-encoded new content stream, for
                instance the commands to draw an XObject.
        ú	/Contentsó   
N)	rE   r½   r�   r:   rK   rÊ   rÞ   r§   rÉ   )r¶   rç   r  Zexisting_content_refZexisting_contentZnew_stream_objZmerged_dataZ
new_streamrl   rl   rm   Ú_merge_content_stream_to_paget  s     




z'PdfWriter._merge_content_stream_to_page)rç   Úappearance_stream_objÚobject_nameÚx_offsetÚy_offsetrq   c                 C   s¨   t t|tj ƒ}|  |¡}td|› �ƒ ¡ }d|vrBtƒ |tdƒ< t t|d ƒ}	||	vrb||	|< ntdt|d� t	ƒ  
||¡}
d|
 ¡ › d|› d� ¡ }|  ||¡ dS )	aµ  
        Adds an appearance stream to the page content in the form of
        an XObject.

        Args:
            page: The page to which to add the appearance stream.
            appearance_stream_obj: The appearance stream.
            object_name: The name of the appearance stream.
            x_offset: The horizontal offset for the appearance stream.
            y_offset: The vertical offset for the appearance stream.
        z/Fm_ú/XObjectzQXObject %(xobject_name)r already added to page resources. This might be an issue.)r÷   Úxobject_namezq
Ú
z Do
QN)r   r?   rÝ   Z	RESOURCESr§   rE   Ú	_sanitizer&   r^   r   Ú	translateZ_to_cmr¥   r!  )r¶   rç   r"  r#  r$  r%  Zpg_resZxobject_refr'  Z	pg_xo_resZ
xobject_cmZxobject_drawing_commandsrl   rl   rm   Ú_add_apstream_object›  s     

ýzPdfWriter._add_apstream_object)rç   ÚfieldsÚflagsÚauto_regenerateÚflattenrq   c                 C   sÌ  t j| jvrtdƒ‚tt| jt j ƒ}tj|vr8tdƒ‚t|t	ƒrL|  
|¡ |du r^t| jƒ}t|tƒr”|D ]"}tj|v rl| j|||d|d� qldS tj|vr®tdtd� dS d}|tj D �]}	tt|	 ¡ ƒ}	|	 dd¡d	krâq¼d
|	v rød|	v rø|	}
n|	 tjtƒ ¡ ¡ }
| ¡ D �]®\}}tt|	tj ƒ}| j|
d�|k�sV|
 dd¡|k�sV�q|
 d
d¡dk�rxd|
v �rx|
d= |�r�t|ƒ|	ttjƒ< |du �r |�st|tƒ�rÎtdd„ |D ƒƒ}||
ttjƒ< n6t|t ƒ�ròt!|d ƒ|	ttjƒ< nt!|ƒ|
ttjƒ< |
 tj"¡dk�r|t|ƒ}tt|	ttj#ƒ ƒ}tt|d ƒ}||v�rRtdƒ}| |¡}||	ttj$ƒ< ||	ttjƒ< �n |
 tj"¡dk�s |
 tj"¡dk�r~t|t ƒ�rÎt% &| ||||
|	|d |d ¡}nt% &| ||||
|	¡}tj#|	v�rttdƒ|  '|¡iƒ|	ttj#ƒ< nldtt|	tj# ƒ }v�rN|  '|¡tt|	ttj#ƒ ƒtdƒ< n.|	tj# d j(j)}|| j*|d < t+|d| ƒ|_(n|	 tj"¡dk�rœtdtd� |�r|�r|  ,||||d |d ¡ �qq¼dS )ai  
        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.

            flatten: Whether or not to flatten the annotation. If True, this adds the annotation's
                appearance stream to the page contents. Note that this option does not remove the
                annotation itself.

        z2No /AcroForm dictionary in PDF of PdfWriter Objectz0No /Fields dictionary in PDF of PdfWriter ObjectN)r/  z No fields to update on this page©r÷   ú/Subtyper„   ú/Widgetú/FTú/T)Úparentz/Chú/Ic                 s   s   | ]}t |ƒV  qd S rs   )rL   ©Ú.0Úvrl   rl   rm   Ú	<genexpr>  rw   z:PdfWriter.update_page_form_field_values.<locals>.<genexpr>r   z/Btnú/Nz/Offz/Txr   rŽ   z/Sigz#Signature forms not implemented yet)-r*   rø   r´   r8   r   r?   r.   ÚFieldsr�   Úboolrù   rµ   r¸   rÝ   ÚANNOTSÚupdate_page_form_field_valuesr&   r^   r½   rÈ   rë   ÚitemsrI   ÚAAÚRectZ_get_qualified_field_namerG   rE   ÚFAZFfr:   ÚVÚtuplerL   ZFTZAPZASrS   Zfrom_text_annotationr§   rÀ   rÁ   r�   rC   r+  )r¶   rç   r,  r-  r.  r/  Z	acro_formÚpr"  Ú
annotationZparent_annotationÚfieldr¿   Z	rectangleÚlstr9  ZapZ	normal_apÚnrl   rl   rm   r?  Ä  s®    &






ÿÿþÿþÿ

ÿþÿÿÿþÿÿz'PdfWriter.update_page_form_field_values)rç   rq   c           
      C   sJ  g }|du r*| j D ]}||  |¡7 }q|S ztt| jtj ƒ}W n( tyh   tƒ }|| jttjƒ< Y n0 ztt	|t
j ƒ}W n& ty¤   t	ƒ }||tt
jƒ< Y n0 d|vr²|S tt	|d ƒ}t|ƒD ]|\}}t|tƒ}	tt| ¡ ƒ}| dd¡dkrÈd|v rÈd|jv �r|j|v �rqÈ|	�s.|  |¡||< | |j¡ | |¡ qÈ|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.

        Nrê   r1  r„   r2  r3  rÀ   )r¸   Úreattach_fieldsr   r?   r´   r*   rø   rÂ   rE   r:   r.   r<  Ú	enumerater�   rC   r½   rÈ   Ú__dict__rÀ   r§   rÞ   )
r¶   rç   rI  rF  Úafr,  Úannotationsró   rG  Zis_indirectrl   rl   rm   rK  R  s@    

ÿþzPdfWriter.reattach_fields)r  rq   c                 C   s˜   t ƒ }|j ¡ D ]}| td |ƒ¡ q| td |jƒ¡ t|ƒ}|| jkrbtd|› d| j› d�ƒ‚t	|dd�}|| j
kr�td|› d| j
› d�ƒ‚t|ƒS )NzIncremental clone object count z exceeds maximum allowed count Ú.r   )ÚdefaultzIncremental clone object ID z exceeds maximum allowed ID )ÚsetZxrefÚvaluesr{   ÚfilterZxref_objStmrß   r¡   r6   Úmaxr¢   Úsorted)r¶   r  Ú
object_idsZ
xref_entryÚobject_countZmax_object_idrl   rl   rm   Ú%_collect_incremental_clone_object_ids„  s&    
ÿÿ
ÿÿz/PdfWriter._collect_incremental_clone_object_idsc              
   C   s®  d| _ | jr`|  |¡}dg|r&|d nd | _|D ]*}| |¡}|dur2| | ¡| j|d < q2n
| j ¡  |j | ¡| _	| j	 
d¡| _tt|jd ƒ}t| jƒ|krÚ| jrÄtdt| jƒ› d|› �ƒ‚td	tt| jƒ|d
� | jròdd„ | jD ƒ| _z|  ¡  W n0 t�y. } ztdƒ|‚W Y d}~n
d}~0 0 | jdu�s@J ‚| jD ]2}|  tt|jƒj|¡ | j�sF| j|tdƒ< �qF| j�sªtdd„ | jD ƒƒtt| j ¡ ƒ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 which the document root should be copied.

        Nr�   r   r   r˜   ú/SizezObject count z exceeds defined trailer size zKObject count %(object_count)d exceeds defined trailer size %(trailer_size)d)r÷   rX  Útrailer_sizec                 S   s    g | ]}|d ur|  ¡ nd‘qS )Nr   )Úhash_bin)r8  rÅ   rl   rl   rm   Ú
<listcomp>À  s   z8PdfWriter.clone_reader_document_root.<locals>.<listcomp>z!Got index error while flattening.ú/Parentc                 S   s   g | ]
}|j ‘qS rl   )rÀ   )r8  rF  rl   rl   rm   r]  Ñ  rw   ú/Kids)r¨   r€   rY  r�   r½   Z	replicaterÄ   r¼   rä   r´   Zraw_getr³   r   rž   Útrailerrß   r‹   r7   r&   r^   r™   Ú_flattenr  r¯   ræ   rC   rÀ   rÁ   rE   r:   r?   )r¶   r  rW  Z	object_idZreader_objectr[  Ú	exceptionrF  rl   rl   rm   Úclone_reader_document_rootš  sR    



ÿüÿ 
þÿz$PdfWriter.clone_reader_document_rootc                 C   sè   |   |¡ |j}| jrb|dur„tt| | ¡jƒ| _t| jt	ƒsFJ dƒ‚| j 
¡ | j| jjjd < n"|dur„|  t	tt	| ¡ ƒƒ¡| _ztt|jƒ | ¡| _W n ty®   Y n0 t|ƒrätttt	| j ¡ ƒd ƒD ]}|| ¡ ƒ qÒ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   r_  )rc  r¾   r€   r   rC   rä   rÀ   r¨   r�   r?   r\  r™   rÁ   r§   r½   r:   r›   rÃ   r  r³   )r¶   r  r  Úinfrç   rl   rl   rm   r²   Ó  s2    
ÿþÿÿÿz$PdfWriter.clone_document_from_readerc                 C   s,   t ƒ }|  |¡ | d¡ tt|ƒ d¡ƒS )Nr   Úutf8)r   Ú_write_pdf_structurer•   r<   r~   r¥   )r¶   ro   rl   rl   rm   Ú_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›   rg  r:   )r¶   Zid1Zid2rl   rl   rm   Úgenerate_file_identifiers	  s    

z#PdfWriter.generate_file_identifiers)Ú	algorithm)Úuser_passwordÚowner_passwordÚ
use_128bitÚpermissions_flagri  rq   c          	   
   C   s  | j rtdƒ‚|du r|}|durrztt| dd¡ƒ}W q‚ tyn } ztd|› d�ƒ|‚W Y d}~q‚d}~0 0 ntj}|s‚tj}|  	¡  | j
s”J ‚t ||| j
d ¡| _| jj||| jd�}| jrò| jjdusÔJ ‚| 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.

        z<Encrypting incremental PDF files is currently not supported.Nú-Ú_zAlgorithm 'z' NOT supportedr   ©r‹   r   )r€   ÚNotImplementedErrorrÛ   r   ÚreplacerÃ   rá   ZRC4_128ZRC4_40rh  r›   r   Úmaker°   Zwrite_entryr‹   r±   rÀ   r�   rÁ   r§   )	r¶   rj  rk  rl  rm  ri  Úalgrb  Úentryrl   rl   rm   Úencrypt  s,    !*


zPdfWriter.encryptc                 C   sv   d}| j D ]f\}}| ¡ }|s q
| j |¡}|du r6q
t|tƒrd|du rRt| jƒ}|j| ||d� q
| | |¡ q
dS )zyPatch up links that were added to the document earlier, to
        make sure they still point to the same pages.
        N)Úknown_names)	rœ   Zfind_referenced_pager�   rÈ   r�   rD   rR  Únamed_destinationsZpatch_reference)r¶   rw  Únew_linkZold_linkZold_pageZnew_pagerl   rl   rm   Ú_resolve_links[  s    

zPdfWriter._resolve_links)ro   rq   c                 C   sÆ   t |dƒr$d|jvr$tdt|jd� |  ¡  | jrš| jd usDJ dƒ‚t|  	¡ ƒdk}|rh| jj
rhtdƒ‚| jj d¡ | | jj d¡¡ |rÂ|  |¡ n(|  |¡\}}|  |||¡}|  ||¡ d S )	NÚmodeÚbz]File <%(stream_name)s> to write to is not in binary mode. It may not be written to correctly.)r÷   Ústream_namerã   r   zNWriting incremental updates of encrypted PDF files is currently not supported.r�   )Úhasattrr{  r&   r^   Únamerz  r€   rƒ   rß   Úlist_objects_in_incrementr»   rq  ro   r•   rÖ   rt   Ú_write_incrementrf  Ú_write_xref_tableÚ_write_trailer)r¶   ro   Zhas_incrementÚobject_positionsÚfree_objectsÚxref_locationrl   rl   rm   Úwrite_streamn  s.    üÿÿzPdfWriter.write_streamc                 C   s`   d}|dkrt d|›d�ƒ‚t|ttfƒr8t|dƒ}d}|  |¡ |rP| ¡  n| ¡  ||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¶   ro   Zmy_filerl   rl   rm   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 | ]6\}}|d ur|ˆ ks.|  ¡ ˆj| krtt|ƒj‘qS rs   )r\  r™   r   rC   rÀ   )r8  ÚirÅ   ©Úoriginal_hash_countr¶   rl   rm   r]  ¶  s
   úz7PdfWriter.list_objects_in_increment.<locals>.<listcomp>)rß   r™   rL  r�   rº   rl   rŒ  rm   r€  ª  s    
þz#PdfWriter.list_objects_in_incrementc                 C   sr  | j d usJ dƒ‚i }g }d}d}t| jƒ}t| jƒD ]¦\}}|d ur6||ks`| ¡ | j| kr6|d }	t|tƒszJ dƒ‚| ¡ ||	< | 	|	› d� 
¡ ¡ | |¡ | 	d¡ |	|krÔ|dkrÐ| ||| g¡ |	}|	d }q6|dksîJ 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�sæt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 objú/Typez/XRefrZ  z/Rootú/Filterz/FlateDecodez/Indexc                 S   s   g | ]}|D ]}t |ƒ‘qqS rl   ©rG   )r8  Z_suZ_itrl   rl   rm   r]  ï  rw   z.PdfWriter._write_increment.<locals>.<listcomp>z/Wé   Z__streamdata__rw   c                 S   s   g | ]}t  d d|d¡‘qS )s   >BIBr   r   )ÚstructÚpack)r8  Ú_posrl   rl   rm   r]    rw   z
endobj
startxref
ú
%%EOF
)!rƒ   rß   r™   rL  r�   r\  r�   rH   r”   rÖ   r¥   Úwrite_to_streamrÞ   rE   rG   r¼   rÀ   r:   r¾   rÁ   r   rC   ÚTKÚINFOZ
_startxrefZPREVr›   ÚIDrK   Zinitialize_from_dictionaryrÊ   ÚjoinrS  )r¶   ro   r„  Zobject_blocksZcurrent_startZcurrent_stopr�  r‹  rÅ   rÁ   r†  Zxr_idZ	init_dataZxrrl   rl   rm   r�  Â  s‚    
ÿþ


ÿ
ÿÿõÿÿÿÿý
ÿÿ
zPdfWriter._write_incrementc                 C   sÄ   g }g }|  | j ¡ d ¡ |  d¡ t| jdd�D ]|\}}|d urœ| | ¡ ¡ |  |› d� ¡ ¡ | jr†|| jkr†| j 	||d¡}| 
|¡ |  d¡ q4| d¡ | |¡ q4| d¡ ||fS )	Nr   s   %âãÏÓ
r   )Ústartr�  r   r�  r�   )rÖ   r¤   r¥   rL  r�   rÞ   r”   r°   r±   Zencrypt_objectr™  )r¶   ro   r„  r…  rÁ   rÅ   rl   rl   rm   rf    s     



zPdfWriter._write_pdf_structure)ro   r„  r…  rq   c                 C   s¸   |  ¡ }| d¡ | dt| jƒd › d� ¡ ¡ | |d d›ddd	›d
� ¡ ¡ d}|D ]V}|dkrˆ| |d›ddd	›d� ¡ ¡ q\| || d›ddd	›d
� ¡ ¡ |d7 }q\|S )Ns   xref
z0 r   r(  r   z0>10ú iÿÿ  z0>5z f 
z n 
)r”   rÖ   rß   r�   r¥   )r¶   ro   r„  r…  r†  Zfree_idxÚoffsetrl   rl   rm   r‚    s    
 " "
zPdfWriter._write_xref_table)ro   r†  rq   c                 C   sª   |  d¡ tttjƒtt| jƒd ƒttjƒ| j	j
iƒ}| jdurT| jj
|ttjƒ< | jdurn| 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   Nz
startxref
r˜  )rÖ   r?   rE   rš  ZSIZErG   rß   r�   ÚROOTr¼   rÀ   r¾   r›  r›   rœ  r±   ZENCRYPTr™  r¥   )r¶   ro   r†  r`  rl   rl   rm   rƒ  /  s    
þÿ


zPdfWriter._write_trailerc                    s   t ƒ jS )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  rË   rº   r  rl   rm   rË   G  s    zPdfWriter.metadatac                 C   s2   |d u rd | _ n| j d ur$| j  ¡  |  |¡ d S rs   )r¾   rÄ   Úadd_metadatarÐ   rl   rl   rm   rË   V  s
    

)Úinfosrq   c                 C   sz   i }t |tƒrtt| ¡ ƒ}t| ¡ ƒD ].\}}t |tƒrB| ¡ }tt|ƒƒ|t	|ƒ< q(| j
du rjtƒ | _
| 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�   rH   r   r?   r½   rµ   r@  rO   r�   rE   r¾   r{   )r¶   r£  ÚargsÚkeyr¿   rl   rl   rm   r¢  c  s    	


zPdfWriter.add_metadata)Úremove_duplicatesÚremove_unreferenced)Úremove_identicalsÚremove_orphansr¦  r§  rq   c                   s  || j kr(tdddƒ t|tƒs$J ‚|}|| j krPtdddƒ t|tƒsLJ ‚|}ttttf ddœ‡ ‡fdd	„‰ i | _d
gt| j	ƒ ‰t
| j	ƒD ]z\}}t|ƒr¢q�|dus²J dƒ‚t|jtƒsÂJ ‚| ¡ }|rú|| jv rú| j| d  |j¡ d| j	|< q�|jg f| j|< q�dd„ | j ¡ D ƒ}i }	| ¡ D ]$\}
}|	 t||
ft|ƒ ƒ¡ �q,| j	D ] }t|ttfƒ�rXˆ ||	ƒ �qX|�rdˆ| jjjd < t| jƒ�s°dˆ| jjjd < zdˆ| jjjd < W n t�yÚ   Y n0 ttt| j	ƒƒˆƒD ]}d| j	|< �qðdS )a�  
        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: Deprecated.
            remove_orphans: Deprecated.
            remove_duplicates: Remove duplicate objects.
            remove_unreferenced: Remove unreferenced objects.

        r¨  r¦  r  r©  r§  N)rÅ   Úcrossrefrq   c                    sˆ   t | tƒr|  ¡ }nt | tƒr(t| ƒ}nd S t | ttfƒs>J ‚|D ]@\}}t |tƒrxdˆ|jd < ||v r‚|| | |< qBˆ ||ƒ qBd S )NFr   )r�   r?   r@  r:   rL  rC   rÁ   )rÅ   rª  Zkey_valÚkr9  ©Úreplace_in_objZunreferencedrl   rm   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ß   r7  rl   rl   rm   Ú
<dictcomp>»  rw   z8PdfWriter.compress_identical_objects.<locals>.<dictcomp>F)Ú_UNSETr$   r�   r=  rH   ÚdictrC   rš   rß   r�   rL  rR   rÀ   Z
hash_valuerÞ   rS  r@  r{   Úzipr?   r:   r¼   rÁ   r¾   r›   rÃ   r   r  )r¶   r¨  r©  r¦  r§  ró   rÅ   ÚhZcnvZcnv_revr«  r9  r‹  rl   r¬  rm   Úcompress_identical_objectsy  sP    

þ
z$PdfWriter.compress_identical_objectsc                 C   s0   | j  |¡d }t|d| ƒ}| ¡ |ks,J ‚|S )Nr   r   )r�   rè   rC   r½   )r¶   rÅ   rÁ   Úrefrl   rl   rm   Úget_referenceÓ  s    zPdfWriter.get_referencec                 C   st   t j| jv rFtt| jt j ƒ}t|tƒspt|ƒ}|  |jj|¡ |}n*tƒ }| 	i ¡ |  
|¡}|| jtt jƒ< |S rs   )r+   ÚOUTLINESr´   r   rM   r�   ræ   rÀ   rÁ   r{   r§   rE   )r¶   Úoutliner–   Zoutline_refrl   rl   rm   Úget_outline_rootÙ  s    


zPdfWriter.get_outline_rootc                 C   s:   t j| jv r tt| jt j ƒ}n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   r:   rE   )r¶   Úthreadsrl   rl   rm   Úget_threads_rooté  s
    zPdfWriter.get_threads_rootc                 C   s   |   ¡ 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º   rl   rl   rm   r¹  ü  s    
zPdfWriter.threads)Úpage_destinationr5  ÚbeforeÚis_openrq   c                 C   s²   t t| ¡ ƒ}t|tƒr>|  td|j› �t t|jƒt	 
¡ ƒ¡S |d u rN|  ¡ }t|ƒ|tdƒ< t t| ¡ ƒ}|  |¡}|d ur„|j}| ||| |j¡ d|vr®tdƒ|tdƒ< |S )Nzpage #z
/%is_open%z/Countr   )r   r   r½   r�   Úadd_outline_item_destinationr>   rþ   rC   rÀ   rA   Úfitr¸  r;   rE   rM   r§   Úinsert_childZinc_parent_counter_outlinerG   )r¶   r»  r5  r¼  r½  Úpage_destination_refrl   rl   rm   r¾    s2    


ýÿ
üz&PdfWriter.add_outline_item_destination)Úoutline_itemr5  r¼  r½  rq   c                 C   s    t ƒ }| |¡ |  ||||¡S rs   )rM   r{   r¾  )r¶   rÂ  r5  r¼  r½  Zoutline_item_objectrl   rl   rm   Úadd_outline_item_dict,  s
    
ÿzPdfWriter.add_outline_item_dict)
Útitlerþ   r5  r¼  ÚcolorÚboldÚitalicr¿  r½  rq   c
                 C   sH  t |tƒr:|dur|du r|}| j|||d|||||	d�	S |du rHd}
nÈt |tƒrX|}n\t |tƒrj|j}nJt |tƒr¢z| j| j}W q´ tyž   t	|ƒ}Y q´0 nt
dt|ƒ› �ƒ‚|du rÐtdt|d� tƒ }ttd| d ƒ||ƒ}|  tttjƒ|jttjƒtdƒiƒ¡}
|  t|
||||ƒ¡}|du �r8|  ¡ }|  ||||	¡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page_number: invalid type z.can not find reference of page %(page_number)s)r÷   rþ   ú/z outline itemú/GoTo)r�   rA   Úadd_outline_itemrC   r   rÀ   rž   r¸   r  rG   Ú	TypeErrorÚtyper&   r^   rF   r>   rE   r§   r?   r,   ÚDr  ÚSÚ_create_outline_itemr¸  r¾  )r¶   rÄ  rþ   r5  r¼  rÅ  rÆ  rÇ  r¿  r½  Ú
action_refÚpage_refr  rÂ  rl   rl   rm   rÊ  C  sV     
ÿ


ýýþÿÿÿ
zPdfWriter.add_outline_itemc                 C   s   t dƒ‚d S )NzIThis method is not yet implemented. Use :meth:`add_outline_item` instead.)rq  rº   rl   rl   rm   Úadd_outline”  s    ÿzPdfWriter.add_outline)rÄ  Údestinationrq   c                 C   sd   |   ¡ }d}|t|ƒk rN||| k rD| ||¡ | |t|ƒ¡ d S |d7 }q| t|ƒ|g¡ d S )Nr   rŽ   )Úget_named_dest_rootrß   rï   rL   rð   )r¶   rÄ  rÓ  Z
named_destr‹  rl   rl   rm   Úadd_named_destination_array™  s    
z%PdfWriter.add_named_destination_array)r»  rq   c                 C   s&   |   |j¡}|  td|d ƒ|¡ |S )NrL   ú/Title)r§   r  rÕ  r   )r¶   r»  rÁ  rl   rl   rm   Úadd_named_destination_object§  s
    ÿz&PdfWriter.add_named_destination_object)rþ   rq   c                 C   sZ   t t|  | j¡ƒ}t t|tj ƒ}t|ƒ}| |  kr@|k sRn td|› d�ƒ‚|| S )z^Look up a page by number, reporting a bad index rather than an IndexError from the kids array.zPage number z is out of range)	r   r?   r½   r³   r:   r1   r®   rß   r  )r¶   rþ   r¸   ÚkidsÚcountrl   rl   rm   Ú_get_page_reference²  s    zPdfWriter._get_page_reference)rÄ  rþ   r¿  rq   c                 C   s¬   |   |¡}|du rJtt| ¡ ƒ tj¡}|dur:t|ƒjnd}t	j
|d�}t|tƒs`tt|ƒƒ}tƒ }| ttjƒt|||ƒjttjƒtdƒi¡ |  |¡}|  ||¡ |S )a»  
        Add a named destination to a page in this PDF.

        Args:
            title: Name of the destination.
            page_number: Index of the destination page, starting at zero.
            fit: How the destination is displayed.
                Defaults to fitting the page horizontally with its
                top edge at the top of the window.

        Returns:
            A reference to the destination's GoTo action.

        Nr   )ÚtoprÉ  )rÚ  r   r?   r½   rÈ   rÝ   ZMEDIABOXrI   rÛ  rA   Zfit_horizontallyr�   rL   r�   r{   rE   r,   rÍ  r>   r  rÎ  r§   rÕ  )r¶   rÄ  rþ   r¿  rÑ  rÛ  r  Zdest_refrl   rl   rm   Ú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_pager]   rh   )r¶   rç   rl   rl   rm   Úremove_linksâ  s    
zPdfWriter.remove_links)Úsubtypesrq   c                 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ç   rl   rl   rm   Úremove_annotationsç  s    
zPdfWriter.remove_annotations)rç   rß  rq   c                 C   s¨   t t| ¡ ƒ}tj|v r¤d}|tt t|tj ƒƒk r¤t t|tj ƒ| }t t| ¡ ƒ}|d u spt t|d ƒ|v ršt|t	ƒrŒt
ƒ | j|jd < |tj |= q|d7 }qd S )Nr   r1  r   )r   r?   r½   rÝ   r>  rß   r:   r�   r�   rC   rF   r�   rÁ   )r¶   rç   rß  r‹  ÚanrÅ   rl   rl   rm   rà  ÷  s    

z"PdfWriter._remove_annots_from_page)rç   Ú	to_deleteÚtext_filtersrq   c           	      C   s   t |ttfƒr(|D ]}|  ||¡ qdS t |tƒs6J ‚|tj@ rL|  |d¡S |tj@ rb|  |d¡S |tj@ rx|  |d¡S |tj	@ rŽ|  |d¡S g }|tj
@ r¤g d¢}|tj@ r¶g d¢}t |tƒsÌt| |jƒ}d|v �rtt| ¡ ƒ}| j|g |||d�\}}| j||||||d	� | |¡ 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ó   'ó   "r  ©ÚeltÚstackÚjump_operatorsrã  rä  ©ÚcontentÚimagesÚformsrÿ  rã  rä  )r�   rµ   rE  rÝ  r]   re   rà  rf   rg   rh   rk   rd   r   rÀ   r   r=   Zget_contentsÚ&_remove_objects_from_page__clean_formsÚ _remove_objects_from_page__cleanZreplace_contents)	r¶   rç   rã  rä  Zto_drÿ  r  r  r  rl   rl   rm   rÝ  	  sD    

ÿ






ÿ
ý
z"PdfWriter.remove_objects_from_page)r  r  r  rÿ  rã  rä  rq   c                 C   sÞ   d }g }|r"|t j@ r"| dg ¡}d}	|	t|jƒk rÒ|j|	 \}
}|dkrR|
d }|dkrd|t j@ sŠ||v sŠ|dkrÈ|t j@ rÈ|
d |v rÈ|t j@ r´|t j@ r¢|r´|t j@ r¾||v r¾|j|	= qÐ|	d7 }	q&|	d7 }	q&| ¡  d S )NÚfont_idsr   s   Tfs   INLINE IMAGEs   Dor   )r]   rd   rÈ   rß   Ú
operationsrj   ri   rÉ   )r¶   r  r  r  rÿ  rã  rä  Zfont_idZfont_ids_to_deleter‹  ZoperandsÚoperatorrl   rl   rm   r  J  sF    	þýûùø	
÷ÿþþýý


z*PdfWriter._remove_objects_from_page__clean)rý  rþ  rÿ  rã  rä  rq   c              
      sü  ˆ |v s(t ˆ dƒr0t‡ fdd„|D ƒƒr0g g fS z$ttttf ttˆ d ƒd ƒ}W n tyj   i }Y n0 g }g }| ¡ D �]\}	}
|
 ¡ }zîd }|t	j
@ rº|d dkrºtƒ }| |	¡ |d dk�rD| |	¡ t|tƒrâ|}nDt|| ƒ}| d	d
„ | ¡ D ƒ¡ z|j|_W n t�y$   Y n0 | ˆ ¡ | j|||||d� |d u�rzt|
tƒ�rl|| j|
jd < n|  |¡||	< W q| ttf�y”   Y q|0 q||D ]}||= �qœtˆ tƒ�rôtˆ tƒ�sÞtˆ | ƒ}| ˆ  ¡ ¡ |‰ | jˆ |||||d� ||fS )NrÀ   c                 3   s    | ]}ˆ j t|d dƒkV  qdS )rÀ   r�   N)rÀ   rÛ   )r8  Úx©rý  rl   rm   r:    s   ÿzCPdfWriter._remove_objects_from_page__clean_forms.<locals>.<genexpr>ú
/Resourcesr&  r1  z/Imagez/Formc                 S   s   i | ]\}}|d vr||“qS ))z/Lengthr’  z/DecodeParmsrl   )r8  Zk1Zv1rl   rl   rm   r®     s   þzDPdfWriter._remove_objects_from_page__clean_forms.<locals>.<dictcomp>rü  r   r   )r~  Úanyr   r°  r   r?   rÂ   r@  r½   r]   ri   rF   rÞ   r�   r=   r{   rÀ   rÃ   r  rC   r�   rÁ   r§   rË  rK   r  )r¶   rý  rþ  rÿ  rã  rä  Údr  r  r«  r9  rú   r  ZimÚerl   r
  rm   r  u  s€    	ÿþÿ
þ
ÿ
þ



þÿ
þ


þz0PdfWriter._remove_objects_from_page__clean_forms)rã  rq   c                 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)

        )ri   rj   rk   N)r�   r=  r-   ÚALLr]   ra   r¸   rÝ  )r¶   rã  r‹  Úimagerç   rl   rl   rm   Úremove_imagesÈ  s    

zPdfWriter.remove_images)Ú
font_namesrq   c                    s¦   |sg }| j D ]’}g }|r~d	tttttf  tt tttf dœ‡ fdd„‰ ˆ | d¡ƒ}|D ]}||v r^| || d ¡ q^i }|rŽ||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.
        N)rÅ   Ú	font_infor¥  rq   c                    sÐ   |d u ri }t | tƒr|  ¡ } t | tƒrª|  d¡dkrŽ|  dd¡}| d¡ d¡d }||vrl|g dœ||< ||| d	 vrŽ|| d	  |¡ | D ]}ˆ | | ||ƒ}q’n"t | tt	fƒrÌ| D ]}ˆ ||ƒ}q¼|S )
Nr‘  z/Fontz	/BaseFontr„   rÈ  ú+r�   )Únormalized_font_nameÚresource_idsr  )
r�   rC   r½   r°  rÈ   ÚlstripÚsplitrÞ   rµ   r:   )rÅ   r  r¥  Ú	font_namer  r«  Z	child_obj©Úget_font_inforl   rm   r  ò  s(    

þ
z,PdfWriter.remove_text.<locals>.get_font_infor  r  r  )rä  )NN)
r¸   r   r   r°  r�   rÈ   rð   rÝ  r]   rd   )r¶   r  rç   Zresource_ids_to_remover  r  rä  rl   r  rm   Úremove_textà  s*    
  ý
üzPdfWriter.remove_text)rþ   ÚuriÚrectÚborderrq   c                 C   s’  |   |¡}ttttf |  |¡ƒ}|durndd„ |dd… D ƒ}t|ƒdkr„tdd„ |d D ƒƒ}| |¡ nt	dƒt	dƒt	dƒg}t
|tƒr´dd„ | ¡  d	¡ ¡ D ƒ}	t|	ƒ}nt
|tƒrÀn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 �rz|tj  |¡ n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   s   g | ]}t |ƒ‘qS rl   r“  ©r8  rJ  rl   rl   rm   r]  4	  rw   z%PdfWriter.add_uri.<locals>.<listcomp>r   r”  c                 S   s   g | ]}t |ƒ‘qS rl   r“  r   rl   rl   rm   r]  6	  rw   rŽ   c                 S   s   g | ]}t |ƒ‘qS rl   )Úfloatr   rl   rl   rm   r]  <	  rw   z[]ú/Sz/URIz/Annotrå  z/Hr6  ú/A)rÚ  r   r°  r�   r   r½   rß   r:   rÞ   rG   r�   Ústripr  rI   r?   r{   rE   rL   rA  ÚTypeZSubtypeÚPrB  ZBorderr§   rÝ   r>  )r¶   rþ   r  r  r  Z	page_linkrÑ  Z
border_arrZdash_patternZcoordsZlnk2ZlnkZlnk_refrl   rl   rm   Úadd_uri	  sF    



þÿ

ùÿ
zPdfWriter.add_uri)z	/NoLayoutz/SinglePagez
/OneColumnz/TwoColumnLeftz/TwoColumnRightz/TwoPageLeftz/TwoPageRightc                 C   s,   zt t| jd ƒW S  ty&   Y d S 0 d S )Nú/PageLayout)r   rX   r´   rÂ   rº   rl   rl   rm   Ú_get_page_layoutg	  s    zPdfWriter._get_page_layout)Úlayoutrq   c                 C   sJ   t |tƒs2|| jvr*tdtd | j¡d� 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: %(layouts)sr  )r÷   Zlayoutsr(  N)r�   rE   Ú_valid_layoutsr&   r^   r�  r´   r{   ©r¶   r*  rl   rl   rm   Ú_set_page_layoutm	  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©r-  r,  rl   rl   rm   Úset_page_layout‘	  s    zPdfWriter.set_page_layoutc                 C   s   |   ¡ S )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º   rl   rl   rm   Úpage_layout­	  s    zPdfWriter.page_layoutc                 C   s   |   |¡ d S rs   r.  r,  rl   rl   rm   r0  Æ	  s    )z/UseNonez/UseOutlinesz
/UseThumbsz/FullScreenz/UseOCz/UseAttachmentsc                 C   s,   zt t| jd ƒW S  ty&   Y d S 0 d S )Nú	/PageMode)r   r[   r´   rÂ   rº   rl   rl   rm   Ú_get_page_modeÓ	  s    zPdfWriter._get_page_modec                 C   s   |   ¡ S )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
        )r2  rº   rl   rl   rm   Ú	page_modeÙ	  s    zPdfWriter.page_mode)r{  rq   c                 C   sP   t |tƒr|}n(|| jvr0tdtd | j¡d� t|ƒ}| j tdƒ|i¡ d S )Nz Mode should be one of: %(modes)sr  )r÷   Úmodesr1  )r�   rE   Ú_valid_modesr&   r^   r�  r´   r{   )r¶   r{  Z	mode_namerl   rl   rm   r3  ð	  s    


ý)rþ   rG  rq   c           
      C   s~  |}t |tƒr| j| }nt |tƒs,tdƒ‚ttt|ƒƒ}|j|t	dƒ< |j
du r`tƒ |t	dƒ< |j
dusnJ ‚| d¡}| d¡dk�r.t |tƒ�r.d|v �r.tt|d ƒ}tt|d	 ƒ}ttt t|ƒd
 ƒ}d|  krìt| jƒk �rn ntt| j| jƒ}	nt|ƒ}	tt	dƒ|	t||d�ƒj|t	dƒ< |j
 |  |¡¡ | d¡dk�rzt	dƒ|v �rz|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ú/PNrê   ú/Destr1  rå  Útarget_page_indexr¿  Úfit_argsr   z	/LinkName)Úfit_typer9  z/Popupr^  )r�   rž   r¸   r   rË  r   r?   Ú_pdf_objectifyrÀ   rE   rO  r:   rÈ   r�   r   r   r°  rß   rC   rG   r>   rA   r  rÞ   r§   r½   )
r¶   rþ   rG  rç   Úto_addrÓ  r8  r:  r9  Ztarget_page_referencerl   rl   rm   Úadd_annotationþ	  sL    



ÿþý 
þ
ýþÿzPdfWriter.add_annotationc                 C   s–   t d| ¡ ƒ}| dg ¡D ]v}| ¡ }| dd¡}| dd¡}t|tƒrZt|ƒ|tdƒ< q|dur| ¡ }| dd¡}t|tƒrt|ƒ|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   rê   r7  Nr#  ú/D)r   r½   rÈ   r�   rE   rL   )r¶   rç   ÚaÚa_objr  Zactrl   rl   rm   Ú
clean_pageE
  s    

zPdfWriter.clean_page)rˆ   rq   c                 C   sÒ   d }t |ttfƒrJt|dƒ�}t| ¡ ƒ}W d   ƒ qÊ1 s>0    Y  n€t |tƒr’|jr`|j}|j 	¡ }|j 
d¡ t|j ¡ ƒ}|j 
|¡ n8t|dƒrÂt|dƒrÂ| 
d¡ | ¡ }t|ƒ}ntdƒ‚||fS )NrŒ   r   r•   rt   zÕMerging 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   rt   r    r°   ro   r”   r•   r~  rq  )r¶   rˆ   Zencryption_objr·   ro   Z	orig_tellZfilecontentrl   rl   rm   Ú_create_stream`
  s&    	,



ÿzPdfWriter._create_stream.)rˆ   rÂ  r¸   Úimport_outlineÚexcluded_fieldsrq   c                 C   sj   |du rd}t |tttfƒrRt |tƒr8t |tƒs4|}|}|}|  d|d|||¡ n|  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

        Nrl   )r�   rE  rµ   rT   r=  Úmerge)r¶   rˆ   rÂ  r¸   rC  rD  rl   rl   rm   rÞ   „
  s0    !

ú	úzPdfWriter.append)Úpositionrˆ   rÂ  r¸   rC  rD  rq   c              	   C   s®  t |tƒr|}n|  |¡\}}	t|dd�}|du r6d}|du rRttt|jƒƒƒ}nft |tƒrvtt| 	t|jƒ¡Ž ƒ}nBt |tƒr‚n6t |t
ƒr¦t|ƒdkr¦tt|Ž ƒ}nt |t
ƒs¸tdƒ‚i }
|D ]¨}t |tƒrÔ|}n
|j| }|jdusìJ ‚|du �r$|  |g t|ƒ¢d‘d‘d‘d	‘¡|
|jj< n6|  ||g t|ƒ¢d‘d‘d‘d	‘¡|
|jj< |d7 }||
|jj _qÀ|j|_|j ¡ D ]}| j|||
d
� �q||du�rÌtd| jt|ƒtt|
 ¡ ƒƒjtd� ¡ ƒ}n|  ¡ }|j}|�rtj |v �r| j!| "tj d¡|
|d�}|  #||d¡ d	|v�r€i }|
 ¡ D ]H}| j$|j "d	g ¡||
||d�}t|ƒdk�rf||t%d	ƒ< |  &|¡ �q*|  '||¡ d|v �r’t(|d ƒ�s’d| j)v�rÖ|  *tt+|jd ƒ ,| dd¡¡| j)t%dƒ< t-ƒ }ntt-tt+| j)d ƒd ƒ}| j.t/|ƒ }zZ|jd d D ]F}z*t0||j d| ƒ}||v�r:| 1|¡ W n t2�yP   Y n0 �qW n  t2�yx   |  *t-ƒ ¡}Y n0 |tt+| j)d ƒt%dƒ< d|v�rª|  3d|
|¡ 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

        Frp  Nrl   r   z:"pages" must be a tuple of (start, stop[, step]) or a listr   ú/Brê   )r  r  ÚsrcpagesrM   )r¿  )rò   r¸   r  )Úannotsrç   r¸   r  Úparent_fieldsr   z	/AcroForm)ú/FieldsrK  r„   )4r�   r   rB  r    rµ   r  rß   r¸   rT   ÚindicesrE  rË  r   rÀ   rü   rÁ   rý   Úoriginal_pagerx  Z_named_destinationsrS  Ú_merge__process_named_destsr   rÊ  rL   Únextrz   r9   r½   r¸  r¼   r+   r¶  Ú_get_filtered_outlinerÈ   Ú_insert_filtered_outlineÚ_insert_filtered_annotationsrE   rA  Ú_set_cloned_kidsrR   r´   r§   r?   rä   r:   r‚   rì   rC   rÞ   rÂ   Úadd_filtered_articles)r¶   rF  rˆ   rÂ  r¸   rC  rD  r  ro   Z_encryption_objrH  rç   Zpgr  Zoutline_item_typZ_ror·  rJ  ZpagrI  ÚarrZtrslatr·   Úindrl   rl   rm   rE  ¿
  sÊ    &



ÿ


ÿÿÿ
ýþ	ÿÿ
ûþýÿþ
þÿ
zPdfWriter.merge)r  r  rH  rq   c              	   C   s2  |j }d| jv rN|d ttt tttt| jd ƒ dtƒ ¡ƒ dtƒ ¡ƒv rNnà|d d u sht|d tƒrjnÄt|d t	ƒròz|j
|d  }W n tyž   Y d S 0 |jd us®J ‚z.t||jj jƒ|tdƒ< |  |d |¡ W n tyî   Y n0 n<|d jj|v �r.||d jj j|tdƒ< |  |d |¡ d S )Nz/NamesrÖ  z/Destsú/Pager   )r  r´   r   rµ   r   r?   rÈ   r�   rF   rž   r¸   r  rÀ   rG   rÁ   rþ   rÕ  rÂ   )r¶   r  r  rH  rU  rF  rl   rl   rm   rN  a  s>    þýþÿ
ÿz%PdfWriter._merge__process_named_dests)Úthreadr¸   r  rq   c                 C   s¢  |j | ddd�}| j |j¡ td|d ƒ}|}d}tƒ }|du�rŒt|ƒ}	|	|v r\tdƒ‚| |	¡ |  	td|d	 ƒ||¡}
|
du�rT|du rºtd|  
tƒ ¡ ¡ ƒ}|}|j|tdƒ< n4td|  
ttd
ƒ|jiƒ¡ ¡ ƒ}|j|tdƒ< |}|
|td	ƒ< |j|tdƒ< |d |tdƒ< td|
 ¡ ƒ}d|v�r>tƒ |tdƒ< td|d ƒ |j¡ td|d ƒ}||kr:|j|tdƒ< |j|td
ƒ< d}q:|jdu�sœJ ‚|jS )aM  
        Clone the thread with only the applicable articles.

        Args:
            thread: Thread entry from the reader's array of threads
            pages: Mapping of object numbers to page objects.
            reader: The corresponding reader.

        Returns:
            The added thread as an indirect reference

        T)ú/F)Zforce_duplicateÚignore_fieldsr?   rY  Nz"Detected cyclic article structure.r   r6  z/Vr;  r4  z/RrG  r:   )rä   r¹  rÞ   rÀ   r   rR  rì   r6   ÚaddÚ_get_cloned_pager§   r?   r½   rE   r:   )r¶   rX  r¸   r  Z
new_threadZfirst_articleZcurrent_articleZnew_articleÚvisitedZ
article_idrç   Z	new_firstZnew_article2Zpage_objectrl   rl   rm   Ú_add_articles_threadƒ  sd    ÿ

ÿ
þÿÿþ
ÿzPdfWriter._add_articles_thread)Úfltrr¸   r  rq   c           	      C   sÀ   t |tƒrt |¡}nt |tƒs*t d¡}| ¡ D ]ˆ}|j}| dd¡D ]p}| ¡ }t	|ƒr^qH| d¡}|du rrqH| ¡ }|j
j| jt|ƒ vrH| | di ¡ dd¡¡rH|  |||¡ qHq2dS )z†
        Add articles matching the defined criteria.

        Args:
            fltr:
            pages:
            reader:

        r„   rG  rl   r4  Nr6  rÖ  )r�   r�   ÚreÚcompiler
   rS  rM  rÈ   r½   rR   rÀ   rÁ   r‚   rì   Úsearchr^  )	r¶   r_  r¸   r  rF  Úppr?  r@  Zthrrl   rl   rm   rT  Í  s(    




ÿþzPdfWriter.add_filtered_articles)rç   r¸   r  rq   c                 C   s¨   t |tƒrd S t |tƒr>z|j| j}W n ty<   Y d S 0 t |tƒr`| dd¡dkr`|j}nt |tƒrn|}z||j	 jW S  t
y�   ‚ Y n ty¢   Y d S 0 d S )Nr‘  r„   rW  )r�   rF   rž   r¸   rÀ   r  r?   rÈ   rC   rÁ   rí   rî   )r¶   rç   r¸   r  Z_irl   rl   rm   r\  ñ  s"    


zPdfWriter._get_cloned_page)rJ  )rI  rç   r¸   r  rJ  rq   c                C   sh  t ƒ }t|tƒrtd| ¡ ƒ}|d u r*|S t|tƒsLtdt||jjd� |S |D �]}td| ¡ ƒ}| 	d¡dksšd|vsštd|d ƒd d	ksšd
|v �rš|d urÔ| 	d¡dkrÔt| 	d¡tƒrÔ| 
|  ||¡¡ nÄd
|vrô| 
|  | | ¡¡¡ n¤|d
 }	t|	tƒ�r.t|	ƒ|  ¡ v �r˜| 
| | ¡j¡ njt|	t ƒrP|	�s@qP|  |	d ||¡}
|
d u�rb|j| dd�}t |
g|	dd … ¢ƒ|td
ƒ< | 
|  |¡¡ qPtd|d ƒ 	dtƒ ¡}	t|	ƒ�r¾qPt|	tƒ�rðt|	ƒ|  ¡ v �rb| 
| | ¡j¡ qPt|	t ƒrP|	�sqP|  |	d ||¡}
|
d urP|j| dd�}t |
g|	dd … ¢ƒtd|d ƒtdƒ< | 
|  |¡¡ qP|S )Nz	list[Any]zEExpected list of annotations, got %(annots)s of type %(annots_type)s.)r÷   rI  Zannots_typer?   r1  rå  r#  r"  rÉ  r7  r2  r^  r   )r7  ©rZ  r   r>  )r>  )r:   r�   rC   r   r½   rµ   r&   r^   r  rÈ   rÞ   Ú_clone_widget_annotationr§   rä   r�   rÔ  rÀ   r\  rE   rF   rR   )r¶   rI  rç   r¸   r  rJ  Zoutlistrâ  Zanor  rF  Zancrl   rl   rm   rR    sx    	

ü
ÿþýüÿþý

þÿz&PdfWriter._insert_filtered_annotations)rG  rJ  rq   c           	      C   sž   |j | dd�}|| }}t| d¡tƒrŠtt| d¡ƒ}| ¡ }t|tƒsLqŠ|j | dd�}|j|tdƒ< |j	|v rtqŠ|||j	< || }}q|jdus˜J ‚|jS )aÖ  
        Clone a widget annotation and link it to its parent fields.

        Cloning ``/Parent`` directly would also clone the ``/Kids`` of the
        parent fields, and with them the widgets and pages of sibling fields
        which are not part of the merge. Instead, the parent fields are cloned
        without ``/Kids`` and collected in ``parent_fields``, so that their kids
        can be set by :meth:`_set_cloned_kids` once all annotations are cloned.
        )r   r^  rd  r^  )r   r_  r   r^  N)
rä   r�   rÈ   rC   r   r½   r?   rÀ   rE   rÁ   )	r¶   rG  rJ  rä   r÷   ÚtargetZparent_referenceÚsource_parentr5  rl   rl   rm   re  W  s    



z"PdfWriter._clone_widget_annotation)rJ  r  rq   c                    sp   ˆ j  t|ƒi ¡‰| ¡ D ]P\}}| dtƒ ¡}ttˆ  ˆ| ¡ƒ}t‡ ‡fdd„tt|ƒD ƒƒ|tdƒ< qdS )zZSet the ``/Kids`` of the cloned parent fields to the cloned kids, in their original order.r_  c                 3   s4   | ],}t |tƒr|jˆv rtˆ|j d ˆ ƒV  qdS )r   N)r�   rC   rÁ   )r8  Zkid©r¶   Z
translatedrl   rm   r:  z  s   þz-PdfWriter._set_cloned_kids.<locals>.<genexpr>N)	r‚   rÈ   rì   r@  r:   r   r?   r½   rE   )r¶   rJ  r  rÁ   rg  rØ  r5  rl   rh  rm   rS  t  s    þzPdfWriter._set_cloned_kids)r]  )rò   r¸   r  r]  rq   c          	      C   sÆ  |du rt ƒ }g }|du r|S | ¡ }t|ƒr4tƒ }t|tƒsPtdt|d� |S | dd¡dkshd|vrÆt|ƒ}||v rˆtdtd	� g S | 	|¡ | d
d¡}|durÄ| ¡ }|| j
||||d�7 }nü| ¡ }t|tƒsêtdt|d� �qÂt|ƒ}||v �rtdtd	� �qÂ| 	|¡ td| |¡ƒ}|  td|d ƒ||¡}|du �rNtƒ }||tdƒ< d
|v �r~| j
|d
 |||d�|_ng |_t|tƒ�r t|jƒdk�rª| |¡ d|v�r¸�qÂ|d }qÆ|S )z•
        Extract outline item entries that are part of the specified page set.

        Returns:
            A list of destination objects.

        Nz*Outline node is not a dictionary: %(node)s)r÷   rò   r‘  r„   ú	/OutlinesrÖ  zDetected cycle in outlines.r0  ú/First)rò   r¸   r  r]  r>   r   rW  r   ú/Next)rR  r½   rR   r?   r�   r&   r^   rÈ   rì   r[  rP  r   Z_build_outline_itemr\  rF   rE   Ú_filtered_childrenrß   rÞ   )	r¶   rò   r¸   r  r]  Znew_outlineZnode_idrÓ  Zcloned_pagerl   rl   rm   rP  €  sb    






ÿ
ÿþ


zPdfWriter._get_filtered_outlinec                 C   sÚ   t ƒ }|  |¡ t|d ƒ|tdƒ< t|d tƒsn|jd ur`d|jv r`|jd  | ¡|tdƒ< n|j|tdƒ< |jd urÖt	|j 
dd¡ƒ|tdƒ< |j 
dtƒ ¡ ¡ }t|tƒsÆtdƒtdƒtdƒg}t|ƒ|tdƒ< |S )	NrÖ  rW  r#  r7  rY  r   ú/Cg        )rM   r§   rL   rE   r�   rF   rò   rä   r  rG   rÈ   r½   rµ   rB   r:   )r¶   r  Zn_olrÅ  rl   rl   rm   Ú_clone_outlineÉ  s    


zPdfWriter._clone_outline)Úoutlinesr5  r¼  rq   c                 C   s^   |D ]T}|  dd¡dks d|vr&|}n"|  |¡}tt| ¡ ƒ ||| ¡ |  |j|d ¡ qd S )Nr‘  r„   ri  rÖ  )rÈ   rn  r   rM   r½   rÀ  rQ  rl  )r¶   ro  r5  r¼  r  Únprl   rl   rm   rQ  Û  s    
z"PdfWriter._insert_filtered_outlinec                 C   s   dS )z"Implemented for API harmonization.Nrl   rº   rl   rl   rm   r‰  ë  s    zPdfWriter.close)rÂ  Úrootr]  rq   c                C   sæ   |d u r|   ¡ }n
td|ƒ}|d u r*tƒ }d}|d urÚ|j|ksP| dd ¡|krV|gS t|ƒ}||v rntdƒ‚| |¡ d|v r´| j|tt	|d ƒ|d�}|r´d|v r¬|gng | S d|v rÔ|d7 }tt
|d ƒ}q.d S q.td	ƒ‚d S )
NrM   r   rÖ  z"Detected cyclic outline hierarchy.rj  )rÂ  rq  r]  rk  r   z'This line is theoretically unreachable.)r¸  r   rR  rÀ   rÈ   rì   r6   r[  Úfind_outline_itemrZ   rM   r8   )r¶   rÂ  rq  r]  r·  rè   Z
outline_idÚresultrl   rl   rm   rr  ï  s:    

ÿþ
ýzPdfWriter.find_outline_itemc                 C   s¨   |du ri | _ n”t|tƒrRz| j t|ƒ= W q¤ ty>   ‚ Y q¤ tyN   Y q¤0 nRt|tƒr–z| j t|jƒ= W q¤ ty‚   ‚ Y q¤ ty’   Y q¤0 ntd|› �ƒ‚dS )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 )	r‚   r�   r    rì   rí   rî   rC   rÜ   rË  )r¶   r  rl   rl   rm   Úreset_translation  s"    

zPdfWriter.reset_translation)Úpage_index_fromÚpage_index_toÚstyleÚprefixrž  rq   c                 C   s²   |du r|du rt dƒ‚|durF|ttƒvrFt dd t¡› d|›�ƒ‚|dk rVt dƒ‚||k rft dƒ‚|t| jƒkr|t d	ƒ‚|durœ|dkrœ|d
k rœt 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 givenzstyle must be one of: r  z, got r   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á   rE  r0   r�  rß   r¸   Ú_set_page_label)r¶   ru  rv  rw  rx  rž  rl   rl   rm   Úset_page_label9  s"    $ÿÿzPdfWriter.set_page_labelc                 C   s\  t ƒ }tdƒ|tdƒ< t ƒ }|dur4t|ƒ|tdƒ< |durLt|ƒ|tdƒ< |dkrdt|ƒ|tdƒ< ttjƒ| jvr¬tƒ }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 �r<t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.

        r>  r"  Nr6  r   z/Stz/Numsr   )r?   rE   rL   rG   r*   ZPAGE_LABELSr´   r:   r   rM   r   r   r   rß   r¸   )r¶   ru  rv  rw  rx  rž  Zdefault_page_labelZnew_page_labelÚnumsZpage_labelsZnext_label_posro  rl   rl   rm   ry  p  s4    !ÿ"zPdfWriter._set_page_label)ÚincludeÚexcluderq   c                    sX   t ƒ }|  |¡ d|i}ˆdur6‡fdd„| ¡ D ƒ}ˆ durT‡ 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 rl   rl   ©r8  r«  r9  )r|  rl   rm   r®  È  rw   z/PdfWriter._repr_mimebundle_.<locals>.<dictcomp>c                    s   i | ]\}}|ˆ vr||“qS rl   rl   r~  )r}  rl   rm   r®  Ì  rw   )r   rÖ   r@  )r¶   r|  r}  Zpdf_datar  rl   )r}  r|  rm   Ú_repr_mimebundle_±  s    
ÿzPdfWriter._repr_mimebundle_)r„   NFFF)rl   )T)rl   )r   rl   )NN)NNr   )N)N)N)NNT)NNT)N)N)N)N)N)N)NNTN)NNTrl   )N)N)N)NNr   )NNr   )NN)®r^   r_   r`   Ú__doc__r=  Ú__annotations__rµ   r   rH   r°  rž   r   r   r   r    r!   r	   r¹   Úpropertyr»   r?   r¼   r¾   ÚsetterrC   r\   rÇ   ÚbytesrÎ   r   rÒ   rÌ  ÚBaseExceptionr   r×   r�   r¤   r§   r½   ræ   r   r   rõ   rù   rN   rû   rü   rý   rF   rÿ   r!  r  ÚdecimalÚDecimalr
  r>   rL   r<   r  r  r'   r  r  r   r  r!  rK   r+  rC  ZFfBitsZ
FFBITS_NULr   rE  r?  rK  rY  rc  r²   rg  rh  ÚALL_DOCUMENT_PERMISSIONSr2   rv  rz  r"   r‡  r   rÖ   r€  r�  rf  r‚  rƒ  r   rË   r¢  Úobjectr¯  r³  rµ  rM   r¸  r:   rº  r¹  r¾  rY   rÃ  r9   rA   rÊ  rÒ  rÕ  r×  rÚ  rÜ  rÞ  rV   rá  rà  r]   rÝ  r=   r  r  r-   r  r  r  rI   r   r'  r+  rX   r)  rE   r-  r/  r0  r5  r[   r2  r3  r=  rA  r   r   rB  rT   rÞ   rU   rE  r   rN  r^  r
   rT  r\  rR  re  rS  rR  rP  rn  rQ  r‰  rZ   rr  rt  r0   rz  ry  r  Ú__classcell__rl   rl   r  rm   r   –   st  
$    úöõ 	

û

ý
üüû?&
ýü üûþÿþ  üû)þýü"ü)ù'
ú"ù ÿþ2<ýü0ûùø>$ I þýýúùZ  ûú'  ûúöõQþýüû'þ
üü
ûHùø1úùUþý>û
úD
$	

üGþ'   ú(,ù?   ùø #$
ûL
ÿ
ù&
û%ù
øIþú

ùIü
ûýû


ú+ÿþ$  úù;  úùC ý
ür   rÚ   c                 C   s²   t | tƒr| S t | tƒrDtƒ }|  ¡ D ]\}}t|ƒ|t|ƒ< q&|S t | tƒrh|  d¡r`t| ƒS t	| ƒS t | t
tfƒr~t| ƒS t | tƒrštdd„ | D ƒƒS tdt| ƒ›d�ƒ‚d S )NrÈ  c                 s   s   | ]}t |ƒV  qd S rs   )r;  )r8  r‹  rl   rl   rm   r:  à  rw   z!_pdf_objectify.<locals>.<genexpr>z
type(obj)=z! could not be cast to a PdfObject)r�   rH   r°  r?   r@  r;  rE   r�   Ú
startswithrL   r!  rž   rB   rµ   r:   rq  rÌ  )rÅ   r<  r¥  r¿   rl   rl   rm   r;  Ñ  s$    




ÿr;  )rÐ  rÄ  rÅ  rÇ  rÆ  rq   c                 C   s¨   t ƒ }| d ur| |tdƒ< | tdƒt|ƒi¡ |rft|tƒrFt|ƒ}| tdƒtdd„ |D ƒƒi¡ |sn|r¤d}|r€|tj	7 }|rŽ|tj
7 }| tdƒt|ƒi¡ |S )Nr#  rÖ  rm  c                 S   s   g | ]}t |ƒ‘qS rl   )rB   )r8  rÑ   rl   rl   rm   r]  ù  rw   z(_create_outline_item.<locals>.<listcomp>r   rY  )rM   rE   r{   rO   r�   r�   rQ   r:   r/   rÇ  rÆ  rG   )rÐ  rÄ  rÅ  rÇ  rÆ  rÂ  Zformat_flagrl   rl   rm   rÏ  æ  s*    ÿÿ
ÿ

rÏ  )rn   )†r†  rb   rx   r`  r•  rŸ   Úcollections.abcr   r   r   Úior   r   r   Ú	itertoolsr   Úpathlibr	   r
   Útypesr   Útypingr   r   r   r   r   r   r   Úversion_infor   Ztyping_extensionsZ_doc_commonr   r   r°   r   r   Z_pager   r   Z_page_labelsr   r   r   rƒ   r    Ú_utilsr!   r"   r#   r$   r%   r&   Úactionsr'   r(   Ú	constantsr)   rA  r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   rC  r4   rÝ   r5   rš  Úerrorsr6   r7   r8   Zgenericr9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   Zgeneric._appearance_streamrS   Z	pagerangerT   rU   rV   rW   rX   rY   rZ   r[   Úxmpr\   Úallrˆ  ÚIntFlagr]   rž   r�   r~   r   r°  r!  rµ   r;  rE  r=  rÏ  rl   rl   rl   rm   Ú<module>   sŽ   $

 ,p                           U(
ú