U
    :vh                     @   s  d Z ddlZddlmZmZ ddlmZ ddlmZ ddl	m
Z ddlmZ 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 ddlmZmZ ddlmZm Z m!Z!m"Z"m#Z#m$Z$m%Z% ddlm&Z' ddlm(Z) ddlm*Z+ ddl,m-Z-m.Z. zddl/m0Z0 W n e1k
r.   dZ0Y nX ddl2m3Z3 e3rNddl4m5Z5 e6e7Z8ddddZ9G dd dZ:G dd de:Z;G d d! d!e#Z<G d"d# d#e#Z=G d$d% d%e#Z>G d&d' d'Z?G d(d) d)e#Z@G d*d+ d+e#ZAG d,d- d-e!ZBG d.d/ d/e!ZCG d0d1 d1e!ZDG d2d3 d3e!ZEG d4d5 d5ZFG d6d7 d7e#ZGG d8d9 d9e#ZHG d:d; d;e#ZIG d<d= d=e:ZJG d>d? d?ZKG d@dA dAZLG dBdC dCZMdOedEdFdGZNdHdI ZOdJdK ZPdPdMdNZQdS )Qai  
This module contains the serialization logic that produces a PDF document from a FPDF instance.
Most of the code in this module is used when FPDF.output() is called.

The contents of this module are internal to fpdf2, and not part of the public API.
They may change at any time without prior warning or any deprecation period,
in non-backward-compatible ways.
    N)OrderedDictdefaultdict)contextmanager)BytesIO)subset   )PDFAnnotation)PDFResourceTypePageLabelStyleSignatureFlag)OutputIntentSubType)FPDFException)TotalPagesSubstitutionFragment)RasterImageInfo)build_outline_objs)	Signaturesign_content)NamePDFArrayPDFContentStreamPDFDate	PDFObject	PDFStringbuild_obj_dict)create_dictionary_string)create_list_string)iobj_ref)	int2romanint_to_letters)signer)TYPE_CHECKING)FPDF)z/Fit)z/FitHnull)/XYZr"   r"   1)ZfullpageZ	fullwidthrealc                   @   s   e Zd ZdddZdS )ContentWithoutIDNc                 C   s   d S N self_security_handlerr(   r(   //tmp/pip-unpacked-wheel-dvf6lv8i/fpdf/output.py	serialize<   s    zContentWithoutID.serialize)N)__name__
__module____qualname__r-   r(   r(   r(   r,   r&   ;   s   r&   c                   @   s   e Zd Zdd ZdddZdS )	PDFHeaderc                 C   s
   || _ d S r'   pdf_version)r*   r3   r(   r(   r,   __init__A   s    zPDFHeader.__init__Nc                 C   s   d| j  S )Nz%PDF-r2   r)   r(   r(   r,   r-   E   s    zPDFHeader.serialize)Nr.   r/   r0   r4   r-   r(   r(   r(   r,   r1   @   s   r1   c                       s   e Zd Zd fdd	Z  ZS )PDFFontNc                    sh   t    td| _t|| _t|| _|r4t|nd | _|| _|| _d | _	d | _
d | _d | _d | _d S )NZFont)superr4   r   typesubtype	base_fontencodingd_wwdescendant_fonts
to_unicodec_i_d_system_infofont_descriptorc_i_d_to_g_i_d_map)r*   r9   r:   r;   r<   r=   	__class__r(   r,   r4   J   s    



zPDFFont.__init__)NNNr.   r/   r0   r4   __classcell__r(   r(   rC   r,   r6   I   s   r6   c                       s   e Zd Z fddZ  ZS )CIDSystemInfoc                    s0   t    tddd| _tddd| _d| _d S )NZAdobeTencryptZUCSr   )r7   r4   r   registryZorderingZ
supplementr*   rC   r(   r,   r4   Z   s    
zCIDSystemInfo.__init__rE   r(   r(   rC   r,   rG   Y   s   rG   c                       s"   e Zd Zed fddZ  ZS )PDFInfo)creation_datec                    s   t    |rt|ddnd | _|r0t|ddnd | _|rFt|ddnd | _|r\t|ddnd | _|rrt|ddnd | _|rt|ddnd | _|| _	d S )NTrH   )
r7   r4   r   titlesubjectauthorkeywordscreatorproducerrM   )r*   rN   rO   rP   rQ   rR   rS   rM   rC   r(   r,   r4   b   s    

zPDFInfo.__init__)r.   r/   r0   r   r4   rF   r(   r(   rC   r,   rL   a   s   	rL   c                   @   s   e Zd Zdd ZdddZdS )AcroFormc                 C   s   || _ || _d S r'   fields	sig_flags)r*   rV   rW   r(   r(   r,   r4   w   s    zAcroForm.__init__Nc                    s,   t  fddt D ||d}t|ddS )Nc                    s   i | ]}|t  |qS r(   getattr.0keyrK   r(   r,   
<dictcomp>}   s      z&AcroForm.serialize.<locals>.<dictcomp>r+   _obj_id Z
field_joinr   dirpdf_dictr*   r+   r_   obj_dictr(   rK   r,   r-   {   s    zAcroForm.serialize)NNr5   r(   r(   r(   r,   rT   v   s   rT   c                       s   e Zd Zd fdd	Z  ZS )
PDFCatalogNc                    sr   t    td| _|r t|nd | _|| _|| _|| _d | _	d | _
d | _d | _d | _d | _d | _d | _d | _d S )NCatalog)r7   r4   r   r8   r   langpage_layout	page_modeviewer_preferencespages	acro_formopen_action	mark_infometadatanamesoutlinesoutput_intentsstruct_tree_root)r*   ri   rj   rk   rl   rC   r(   r,   r4      s    

zPDFCatalog.__init__)NNNNrE   r(   r(   rC   r,   rg      s
          rg   c                       s   e Zd Z fddZ  ZS )PDFResourcesc                    s2   t    || _|| _|| _|| _|| _|| _d S r'   )r7   r4   proc_setfontx_objectext_g_stateshadingpattern)r*   rw   rx   ry   rz   r{   r|   rC   r(   r,   r4      s    
zPDFResources.__init__rE   r(   r(   rC   r,   rv      s   rv   c                       s   e Zd Z fddZ  ZS )PDFFontStreamc                    s   t  j|dd t|| _d S NTcontentscompress)r7   r4   lenZlength1r*   r   rC   r(   r,   r4      s    zPDFFontStream.__init__rE   r(   r(   rC   r,   r}      s   r}   c                       s   e Zd Z fddZ  ZS )PDFXmpMetadatac                    s,   t  j|dd td| _td| _d S )Nzutf-8r   ZMetadataXML)r7   r4   encoder   r8   r9   r   rC   r(   r,   r4      s    
zPDFXmpMetadata.__init__rE   r(   r(   rC   r,   r      s   r   c                       s"   e Zd ZdZd fdd	Z  ZS )
PDFXObject)_id	_contentsfilterlengthr8   r9   widthheightcolor_spacebits_per_componentdecodedecode_parmss_maskNc
           
         sZ   t  j|d td| _t|| _|| _|| _|| _|| _t|| _	|| _
|	| _d | _d S )Nr   ZXObject)r7   r4   r   r8   r9   r   r   r   r   r   r   r   r   )
r*   r   r9   r   r   r   r   
img_filterr   r   rC   r(   r,   r4      s    


zPDFXObject.__init__)NNN)r.   r/   r0   	__slots__r4   rF   r(   r(   rC   r,   r      s
      r   c                       s$   e Zd ZdZdZ fddZ  ZS )PDFICCProfilezholds values for ICC Profile Stream
    Args:
        contents (str): stream content
        n (int): [1|3|4], # the numbers for colors 1=Gray, 3=RGB, 4=CMYK
        alternate (str): ['DeviceGray'|'DeviceRGB'|'DeviceCMYK']
    )r   r   r   r   n	alternatec                    s$   t  j|dd || _t|| _d S r~   )r7   r4   r   r   r   )r*   r   r   r   rC   r(   r,   r4      s    zPDFICCProfile.__init__)r.   r/   r0   __doc__r   r4   rF   r(   r(   rC   r,   r      s   	r   c                   @   s   e Zd ZdZeeedddZee	dddZ
eeddd	Zd
d Zdd ZedddZedddZedddZedddZdS )PDFPageLabel_style_prefixst)label_stylelabel_prefixlabel_startc                 C   s   || _ || _|| _d S r'   r   )r*   r   r   r   r(   r(   r,   r4      s    zPDFPageLabel.__init__returnc                 C   s   | j rt| j jS d S r'   )r   r   valuerK   r(   r(   r,   s  s    zPDFPageLabel.sc                 C   s   | j rt| j S d S r'   )r   r   rK   r(   r(   r,   p  s    zPDFPageLabel.pc                 C   s   d| j  d| j d| j dS )NzPDFPageLabel(, )r   rK   r(   r(   r,   __repr__	  s    zPDFPageLabel.__repr__c                 C   s   | j r| j nd}| jr| jtjkr2|t| j7 }n~| jtjkrN|t| j7 }nb| jtjkrn|t| j	 7 }nB| jtj
kr|t| jd 7 }n"| jtjkr|t| jd 	 7 }|S )N r   )r   r   r
   NUMBERstrr   ZUPPER_ROMANr   ZLOWER_ROMANlowerZUPPER_LETTERr   ZLOWER_LETTER)r*   retr(   r(   r,   __str__  s    zPDFPageLabel.__str__c                    s   t  fddt D S )Nc                    s   i | ]}|t  |qS r(   rX   rZ   rK   r(   r,   r]     s      z*PDFPageLabel.serialize.<locals>.<dictcomp>)r   rc   rK   r(   rK   r,   r-     s    zPDFPageLabel.serializec                 C   s   | j S r'   )r   rK   r(   r(   r,   	get_style  s    zPDFPageLabel.get_stylec                 C   s   | j S r'   )r   rK   r(   r(   r,   
get_prefix!  s    zPDFPageLabel.get_prefixc                 C   s   | j S r'   )r   rK   r(   r(   r,   	get_start$  s    zPDFPageLabel.get_startN)r.   r/   r0   r   r
   r   intr4   propertyr   r   r   r   r   r   dictr-   r   r   r   r(   r(   r(   r,   r      s     r   c                       s|   e Zd ZdZ fddZdd Zdd Zdd	 Zd
d Ze	e	dddZ
e	dddZedddZdd Zdd Z  ZS )PDFPage)r   r8   r   durtransannotsgroup	media_boxstruct_parents	resourcesparent_index	_width_pt
_height_pt_page_label_text_substitution_fragmentsc                    sv   t    td| _|| _|r"|nd | _|| _t | _d | _	d | _
d | _d | _d | _|| _d\| _| _d | _g | _d S )NZPage)NN)r7   r4   r   r8   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r*   durationZ
transitionr   indexrC   r(   r,   r4   <  s    

zPDFPage.__init__c                 C   s   | j S r'   r   rK   r(   r(   r,   r   T  s    zPDFPage.indexc                 C   s
   || _ d S r'   r   )r*   ir(   r(   r,   	set_indexW  s    zPDFPage.set_indexc                 C   s   | j | jfS )zGReturn a pair (width, height) in the unit specified to FPDF constructorr   r   rK   r(   r(   r,   
dimensionsZ  s    zPDFPage.dimensionsc                 C   s   || | _ | _dS )zHAccepts a pair (width, height) in the unit specified to FPDF constructorNr   )r*   width_pt	height_ptr(   r(   r,   set_dimensions^  s    zPDFPage.set_dimensions)previous_page_label
page_labelc                 C   s|   |r<|r<|  |  kr<| | kr<|js<| d |_|rN| sNd|_|rr|srt|  | | d }|| _d S Nr   )r   r   r   r   r   r   )r*   r   r   r(   r(   r,   set_page_labelb  s*    
zPDFPage.set_page_labelr   c                 C   s   | j S r'   )r   rK   r(   r(   r,   get_page_label{  s    zPDFPage.get_page_labelc                 C   s   | j st|  S t| j S r'   )r   r   r   rK   r(   r(   r,   	get_label~  s    zPDFPage.get_labelc                 C   s   | j S r'   )r   rK   r(   r(   r,   get_text_substitutions  s    zPDFPage.get_text_substitutionsc                 C   s   | j | d S r'   )r   append)r*   fragmentr(   r(   r,   add_text_substitution  s    zPDFPage.add_text_substitution)r.   r/   r0   r   r4   r   r   r   r   r   r   r   r   r   r   r   rF   r(   r(   rC   r,   r   (  s    r   c                       s   e Zd Z fddZ  ZS )PDFPagesRootc                    s*   t    td| _|| _|| _d | _d S )NZPages)r7   r4   r   r8   countr   kids)r*   r   r   rC   r(   r,   r4     s
    

zPDFPagesRoot.__init__rE   r(   r(   rC   r,   r     s   r   c                       s&   e Zd Z fddZdddZ  ZS )PDFExtGStatec                    s   t    || _d S r'   )r7   r4   _dict_as_str)r*   Zdict_as_strrC   r(   r,   r4     s    
zPDFExtGState.__init__Nc                 C   s   | j  d| j dS )Nz 0 obj
z
endobj)idr   )r*   rf   r+   r(   r(   r,   r-     s    zPDFExtGState.serialize)NN)r.   r/   r0   r4   r-   rF   r(   r(   rC   r,   r     s   r   c                   @   s"   e Zd ZdZdd ZdddZdS )PDFXrefAndTrailerz$Cross-reference table & file trailerc                 C   s(   || _ |jd | _d | _d | _d | _d S r   )output_builderobj_idr   catalog_objinfo_objencryption_obj)r*   r   r(   r(   r,   r4     s
    zPDFXrefAndTrailer.__init__Nc                 C   sT  | j }tt|j}g }|d |d| j  |d td| jD ]}||j| dd qJ|d |d |d	| j  |d
t| j	j
  |dt| jj
  |j}| jr|dt| jj
  |jj}n| }|dkr
||j}|r"|d| d |d |d || |d d|S )Nxrefz0 z0000000000 65535 f r   Z010z	 00000 n trailer<<z/Size z/Root z/Info z	/Encrypt z/ID []>>	startxrefz%%EOF
)r   r   r   bufferr   r   rangeoffsetspdf_refr   r   r   fpdfr   r+   file_id_default_file_idjoin)r*   r+   Zbuilderr   outr   r   r   r(   r(   r,   r-     s6    









zPDFXrefAndTrailer.serialize)N)r.   r/   r0   r   r4   r-   r(   r(   r(   r,   r     s   r   c                   @   s8   e Zd ZdZdZd
deeeeedddZddd	ZdS )OutputIntentDictionarya  The optional OutputIntents (PDF 1.4) entry in the document
    catalog dictionary holds an array of output intent dictionaries,
    each describing the colour reproduction characteristics of a possible
    output device.

    Args:
        subtype (OutputIntentSubType, required): PDFA, PDFX or ISOPDF
        output_condition_identifier (str, required): see the Name in
            https://www.color.org/registry.xalter
        output_condition (str, optional): see the Definition in
            https://www.color.org/registry.xalter
        registry_name (str, optional): "https://www.color.org"
        dest_output_profile (PDFICCProfile, required/optional):
            PDFICCProfile | None # (required if
            output_condition_identifier does not specify a standard
            production condition; optional otherwise)
        info (str, required/optional see dest_output_profile): human
            readable description of profile
    )r8   r   output_condition_identifieroutput_conditionregistry_namedest_output_profileinfoNzOutputIntentSubType | str)r9   r   r   r   r   r   c                 C   s   t d| _t t|j| _|r(t|nd | _|r:t|nd | _|rLt|nd | _	|rdt
|trd|nd | _|rvt|nd | _d S )NZOutputIntent)r   r8   r   Zcoercer   r   r   r   r   r   
isinstancer   r   r   )r*   r9   r   r   r   r   r   r(   r(   r,   r4     s     	

zOutputIntentDictionary.__init__c                    s(   t  fddt D ||d}t|S )Nc                    s   i | ]}|t  |qS r(   rX   rZ   rK   r(   r,   r]     s      z4OutputIntentDictionary.serialize.<locals>.<dictcomp>r^   rb   re   r(   rK   r,   r-     s    z OutputIntentDictionary.serialize)NNNN)NN)	r.   r/   r0   r   r   r   r   r4   r-   r(   r(   r(   r,   r     s       r   c                   @   sf   e Zd ZdZdd ZeedddZeddd	Zeed
ddZ	edddZ
eedddZdS )ResourceCatalogzKManage the indexing of resources and association to the pages they are usedc                 C   s   t t| _t t| _d S r'   )r   r   r   setresources_per_pagerK   r(   r(   r,   r4     s    
zResourceCatalog.__init__)resource_typepage_numberc                 C   sx   |t jt jfkr`| j| }||kr@| | t|d  ||< | j||f ||  || S | j||f | d S r   )r	   PATTERNSHADDINGr   _get_prefixr   r   add)r*   r   resourcer   rJ   r(   r(   r,   r    s    
zResourceCatalog.add)r   c                 C   s   | j |  S r'   )r   items)r*   r   r(   r(   r,   	get_items  s    zResourceCatalog.get_items)r   r   c                 C   s   | j ||f S r'   )r   )r*   r   r   r(   r(   r,   get_resources_per_page   s    z&ResourceCatalog.get_resources_per_pagec                 C   s4   t  }| j D ]\\}}}||kr|| q|S r'   )r   r   r  update)r*   r   unique_Zrtyper  r(   r(   r,   get_used_resources#  s
    z"ResourceCatalog.get_used_resourcesc                 C   s.   |t jkrdS |t jkrdS td| d S )NPZShzNo prefix for resource type )r	   r  r  
ValueError)clsr   r(   r(   r,   r  *  s
    

zResourceCatalog._get_prefixN)r.   r/   r0   r   r4   r	   r   r  r  r  r  classmethodr  r(   r(   r(   r,   r     s   r   c                   @   s   e Zd ZdZddddZdd Zdd	 Zd<ddZdd Zdd Z	e
dd
fddZdd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ Zd0d1 Zd2d3 Zd4d5 Zd6d7 Zed8d9 Zd:d; Z d
S )=OutputProducerzVGenerates the final bytearray representing the PDF document, based on a FPDF instance.r!   )r   c                 C   s:   || _ g | _i | _d| _i | _i | _tt| _t	 | _
d S )Nr   )r   pdf_objsiccp_i_to_pdf_ir   r   trace_labels_per_obj_idr   r   sections_size_per_trace_label	bytearrayr   )r*   r   r(   r(   r,   r4   6  s    
zOutputProducer.__init__c              
   C   s   | j }|jr6| }|dkr*|td}|j| |j}|jrV|jj|krV|jj}| j	
t| |  }|  }|  }|  }|jD ]}| |d q| | |  }	|  \}
}|  }|  }|  }t| }| j	
| t||_| j|||d |||	|
d g }|D ]}||_|jD ]}g }|jrB|
|j |jrft |jdrf|
|jj |D ]2}|j!t"|krjt#d|j! d|$  dqj|%| q&|jsd	|_q|D ]}|
|j q|D ]}t&||j!d
  j'|_(q|j)j*j+D ]}||! d
  |_,q||_-||_.||_/| j0rFt1d| j0 | j2rbt1dt"| j2 | j	D ]~}t3|t4r~d	}n t"| j0| j2|j'< | j56|j'}|r| 7| | 8|j9|jd W 5 Q R X n| 8|j9|jd qh| :  |j;rt<t=| j0|j;|j>|j?|j@|jA| _0| j0S )z
        This method alters the target FPDF instance
        by assigning IDs to all PDF objects,
        plus a few other properties on PDFPage instances
        r   r   embedded_files)pages_root_objfirst_page_objsig_annotation_objxmp_metadata_objstruct_tree_root_objoutline_dict_objdestz'Invalid reference to non-existing page z present on page z: Nr   z@Nothing should have been appended to the .buffer at this stage: z.No offset should have been set at this stage: )r+   )Br   r+   r   r   r  Zgenerate_passwordsr3   rl   Z_min_pdf_versionr  r   r1   _add_pages_root_add_catalog
_add_pages_add_annotations_as_objectsr  _add_pdf_obj_insert_resources_add_structure_tree_add_document_outline_add_xmp_metadata	_add_info_add_encryptionr   r   r   _finalize_catalogr   r   r  ahasattrr   r   r  r   extendr   r   Zpage_refstruct_builderZdoc_struct_elemkZpgr   r   r   r   AssertionErrorr   r   r&   r  get_trace_size_outr-   _log_final_sections_sizesZ	_sign_keyr   r   Z
_sign_certZ_sign_extra_certsZ_sign_hashalgoZ
_sign_time)r*   r   r   r3   r  r   	page_objsr  embedded_filer  r  outline_itemsr  r   r   r   Zdestspage_objZannotZ
page_destsr  Zoutline_itemZstruct_elempdf_objtrace_labelr(   r(   r,   	bufferizeA  s    



	



	zOutputProducer.bufferizec                 C   s<   t |ts&t |tst|}|d}|  j|d 7  _dS )zAppend data to the bufferlatin1   
N)r   bytesr   r   r   )r*   datar(   r(   r,   r3    s
    


zOutputProducer._outNc                 C   s8   |  j d7  _ | j |_| j| |r2|| j| j < | j S r   )r   r   r  r   r  )r*   r9  r:  r(   r(   r,   r#    s    zOutputProducer._add_pdf_objc                 C   s(   | j }t|jt|jd}| | |S )N)r   r   )r   r   pages_count_dimensions_to_mediaboxdefault_page_dimensionsr#  )r*   r   r  r(   r(   r,   r    s    
zOutputProducer._add_pages_rootc                 c   sR   t d| jjd D ]:}| jj| }| |ksFtd| d||V  qd S )Nr   zpage_obj.index()=z != page_index=)r   r   r@  rm   r   r0  )r*   Z
page_indexr8  r(   r(   r,   _iter_pages_in_order  s    
z#OutputProducer._iter_pages_in_orderr   c                 C   s   | j }g }t|  | D ]x}|jdkr>tdddddd|_| |jkrZt| |_	| 
|d || t|j|jd	}| 
|d ||_q|S )
Nz1.3z/Groupz/Transparency
/DeviceRGB)z/Typez/Sz/CSr`   ra   rm   r   )r   listrC  r3   rd   r   r   rB  rA  r   r#  r   r   r   r   )r*   Z_slicer   r5  r8  Zcs_objr(   r(   r,   r!    s&    


 zOutputProducer._add_pagesc                 C   sZ   d }| j j D ]D}|jD ]8}t|tr| | t|jtr|d ksNt	d|}qq|S )Nz0A /Sig annotation is present on more than 1 page)
r   rm   valuesr   r   r   r#  vr   r0  )r*   r  r8  Z	annot_objr(   r(   r,   r"    s    


z*OutputProducer._add_annotations_as_objectsc                    sl  i }t | jj dd dD ]H  jdkrf jdkr:dnd }td j|d}| |d	 || j< q jd
krd j } j	
 }t jdkrddd  jd d D }t jdkr|dt jd  d7 }td|| tjddd}| jddddddddddd d!d"d#d$d%d&g7  _t|}|j|d' |	 j  fd(d) j	 D }	t }
 j|
 |
d |
 }td*|d+d}| |d	 || j< td,| jjt d-}| |d	 t|g|_g }d.d/  j	 D ]N\}}t|j dkr
q|!d0|d1d2d3fd4d|j D  d5 qt"d6t| d7d3| d8}| |d	 ||_#t$ }| |d	 ||_% j}t&||_'| |d	 ||_(d9gd: d: d; }|	 D ]6\}}t)|d<? ||d; < t)|d=@ ||d; d> < qd3|}t"|*d?dd@}| |d	 ||_+t,|dA}| |d	 ||_- j	j./   j	j0/   1  q|S )BNc                 S   s   | j S r'   )r   rx   r(   r(   r,   <lambda>      z+OutputProducer._add_fonts.<locals>.<lambda>r\   core)ZSymbolZZapfDingbatsZWinAnsiEncodingZType1)r9   r:   r;   fontsZTTFzMPDFAA+r   r   c                 s   s2   | ]*}d t | dt |d  dV  qdS )'z' (zunicode-escaper   N)chrr   r   )r[   xr(   r(   r,   	<genexpr>  s   z,OutputProducer._add_fonts.<locals>.<genexpr>
   z, ... (and z others)z+Font %s is missing the following glyphs: %sT)Znotdef_outlineZrecommended_glyphsZFFTMZGDEFZGPOSZGSUBZMATHZhdmxmetaZsbixZCBDTZCBLCZEBDTZEBLCZEBSCzSVG ZCPALZCOLRZfvar)glyphsc                    s    i | ]\}}| j |jqS r(   )ttfontZ
getGlyphIDZ
glyph_name)r[   glyphZchar_idrH  r(   r,   r]   B  s    z-OutputProducer._add_fonts.<locals>.<dictcomp>ZType0z
Identity-HZCIDFontType2)r9   r:   r<   r=   c                 S   s<   | dkr4d| d d? B }d| d@ B }|d|dS | dS )Ni  i   i   rR  i   i  04Xr(   )unicodeZ	code_highZcode_lowr(   r(   r,   format_codeg  s
    z.OutputProducer._add_fonts.<locals>.format_code<rW  z> <r   c                 3   s   | ]} |V  qd S r'   r(   )r[   code)rY  r(   r,   rQ  s  s     z>
z/CIDInit /ProcSet findresource begin
12 dict begin
begincmap
/CIDSystemInfo
<</Registry (Adobe)
/Ordering (UCS)
/Supplement 0
>> def
/CMapName /Adobe-Identity-UCS def
/CMapType 2 def
1 begincodespacerange
<0000> <FFFF>
endcodespacerange
z beginbfchar
zGendbfchar
endcmap
CMapName currentdict /CMap defineresource pop
end
end             r   r<  r   r   )2sortedr   rM  rF  r8   namer6   r#  r   r   Zget_all_glyph_namesr   Zmissing_glyphsr   LOGGERwarningftsubsetOptionsZdrop_tablesZ	SubsetterZpopulaterU  r  r   saveseekreaddescZmissing_width_tt_font_widthsr   r>   rX  r   r   r?   rG   r@   r   Z	font_namerA   rO  r   rB   r}   Z
font_file2Zpickcache_clearZ	get_glyphclose)r*   font_objs_per_indexr;   Zcore_font_objZfontnameZglyph_namesmsgoptionsZ	subsetterZcode_to_glyphoutputZttfontstreamZcomposite_font_objZcid_font_objZbfCharrV  Zcode_mappedZto_unicode_objZcid_system_info_objZfont_descriptor_objZcid_to_gid_mapccZcid_to_gid_map_objZfont_file_cs_objr(   )rx   rY  r,   
_add_fonts  s    
  


  
	

  
(

 

zOutputProducer._add_fontsc                 C   sF   i }t | jjj dd dD ]"}|d dkr| |||d < q|S )Nc                 S   s   | d S )Nr   r(   )imgr(   r(   r,   rI    rJ  z,OutputProducer._add_images.<locals>.<lambda>rK  usagesr   r   )ra  r   image_cacheimagesrF  
_add_image)r*   img_objs_per_indexrt  r(   r(   r,   _add_images  s     
zOutputProducer._add_imagesc                 C   s   |d }|| j kr| j | S d}| jjj D ]\}}||kr.|} qHq.|dk	sTtt||d |d d}| |d}|| j |< |S )z~
        Returns the PDF object of the ICC profile indexed iccp_i in the FPDF object.
        Adds it if not present.
        iccp_iNZdpncs)r   r   r   Ziccp)r  r   rv  Zicc_profilesr  r0  r   r#  )r*   Zimg_infor{  Ziccp_contentZiccp_cr   Ziccp_obj
iccp_pdf_ir(   r(   r,   _ensure_iccp  s"    

  
zOutputProducer._ensure_iccpc           
      C   sj  t |d }d }|d}|dkrDtddt|d d d  g}nD|d k	rp| |}td	t|td
dg}n|dkr|d dkrd}d|d  d|d  d}td|d |d |d ||d |d ||d	}| |d | jj	r*d|kr*d|d  }| 
|d |d dd|d ||d d |_d|krft|d | jjd!}	| |	d |jt|	j |S )"Nr|  r{  ZIndexedz/IndexedrD  Zpal   r   z	/ICCBased0RZ
DeviceCMYKinvertedTz[1 0 1 0 1 0 1 0]r   dpz /BitsPerComponent bpcr   ZImager?  r=   hf)	r9   r   r   r   r   r   r   r   r   rw  Zsmaskz!/Predictor 15 /Colors 1 /Columns Z
DeviceGrayr_  )r=   r  r|  r  r  r  r?  r   )r   r1  r   r   r~  r   r   r#  r   Zallow_images_transparencyrx  r   r   r   r   r   r   r   )
r*   r   r   r   r{  r}  r   img_objr  Z
pal_cs_objr(   r(   r,   rx    s\    


 zOutputProducer._add_imagec                 C   s<   t  }| jj D ]$\}}t|}| |d |||< q|S )NZgfxstate)r   r   Z _drawing_graphics_state_registryr  r   r#  )r*   gfxstate_objs_per_nameZ
state_dictrb  gfxstate_objr(   r(   r,   _add_gfxstates  s    
zOutputProducer._add_gfxstatesc                 C   sX   t  }| jjtjD ]<\}}|jD ]}| |d q$| }| |d |||< q|S )Nfunctionr{   )	r   r   _resource_catalogr  r	   r  Z	functionsr#  Zget_shading_object)r*   shading_objs_per_namer{   rb  r  shading_objr(   r(   r,   _add_shadings  s    

zOutputProducer._add_shadingsc                 C   s8   t  }| jjtjD ]\}}| |d |||< q|S )Nr|   )r   r   r  r  r	   r  r#  )r*   pattern_objs_per_namer|   rb  r(   r(   r,   _add_patterns  s    
zOutputProducer._add_patternsc           
         s       }  jjrT |}|D ]
}||_qFnt	|ddD ]\} fddjj
tjD }fddjj
tjD }fdd| D }fddjj
tjD }fddjj
tjD }	|||||	|_q`d S )	Nr   )startc                    s   i | ]}| | qS r(   r(   )r[   Zfont_id)rn  r(   r,   r]   6  s    z4OutputProducer._insert_resources.<locals>.<dictcomp>c                    s   i | ]}| | qS r(   r(   )r[   Zimg_id)ry  r(   r,   r]   <  s    c                    s,   i | ]$\}}|j j tjkr||qS r(   )r   r  r  r	   ZEXT_G_STATE)r[   Zgfx_nameZ	gfx_state)r   r*   r(   r,   r]   B  s     c                    s   i | ]}| | qS r(   r(   )r[   Zshading_name)r  r(   r,   r]   J  s    c                    s   i | ]}| | qS r(   r(   )r[   Zpattern_name)r  r(   r,   r]   P  s    )rs  rz  r  r  r  r   Zsingle_resources_object_add_resources_dictr   	enumerater  r  r	   ZFONTZX_OBJECTr  r  r  )
r*   r5  r  Zresources_dict_objr8  Zpage_font_objs_per_indexZpage_img_objs_per_indexZpage_gfxstate_objs_per_nameZpage_shading_objs_per_nameZpage_pattern_objs_per_namer(   )rn  ry  r   r  r*   r  r,   r$  #  sd    

 
 
 
 z OutputProducer._insert_resourcesc                 C   s   d}d\}}}	}
}|r0t dd t| D }|rNt dd t| D }|rht dd | D }	|rt dd t| D }
|rt dd t| D }t||||	|
|d	}| | |S )
Nz$[/PDF /Text /ImageB /ImageC /ImageI])NNNNNc                 S   s"   i | ]\}}d | t |jqS )z/Fr   r   )r[   r   Zfont_objr(   r(   r,   r]   p  s    z6OutputProducer._add_resources_dict.<locals>.<dictcomp>c                 S   s"   i | ]\}}d | t |jqS )z/Ir  )r[   r   r  r(   r(   r,   r]   x  s    c                 S   s"   i | ]\}}d | t |jqS /r  )r[   rb  r  r(   r(   r,   r]     s    c                 S   s"   i | ]\}}d | t |jqS r  r  )r[   rb  r  r(   r(   r,   r]     s    c                 S   s"   i | ]\}}d | t |jqS r  r  )r[   rb  Zpattern_objr(   r(   r,   r]     s    )rw   rx   ry   rz   r{   r|   )rd   ra  r  rv   r#  )r*   rn  ry  r  r  r  rw   rx   ry   rz   r{   r|   Zresources_objr(   r(   r,   r  ^  sT    




z"OutputProducer._add_resources_dictc                 C   s>   | j j rdS d}| j jD ]}|dkr,|}| |d q|S )zDBuilds a Structure Hierarchy, including image alternate descriptionsNZstructure_tree)r   r.  emptyr#  )r*   r  r9  r(   r(   r,   r%    s    z"OutputProducer._add_structure_treec                 C   sT   | j jsdS d g  }}t| j jD ](}|d kr4|}n
|| | |d q"||fS )N)Nr(   Zdocument_outline)r   Z_outliner   r   r#  )r*   r  r7  r9  r(   r(   r,   r&    s    

z$OutputProducer._add_document_outlinec                 C   s2   | j jsd S d| j j d}t|}| | |S )Nu9   <?xpacket begin="ï»¿" id="W5M0MpCehiHzreSzNTczkc9d"?>
z
<?xpacket end="w"?>
)r   Zxmp_metadatar   r#  )r*   Zxpacketr9  r(   r(   r,   r'    s    
z OutputProducer._add_xmp_metadatac              
   C   s   | j }d }|jrZzt|jddd}W n4 tk
rX } ztd|j |W 5 d }~X Y nX t|jt|dd t|dd t|dd t|dd t|dd |d	}| | |S )
NT)Zwith_tzrI   zCould not format date: rO   rP   rQ   rR   rS   )rN   rO   rP   rQ   rR   rS   rM   )	r   rM   r   	Exceptionr   rL   rN   rY   r#  )r*   r   rM   errorr   r(   r(   r,   r(    s,    





	
zOutputProducer._add_infoc                 C   s*   | j jr&| j j}| }| | |S d S r'   )r   r+   Zget_encryption_objr#  )r*   Zencryption_handlerr9  r(   r(   r,   r)    s    
zOutputProducer._add_encryptionc                 C   s4   | j j}|sdS |D ]}|jr| |j qt|S )zshould be added in _add_catalogN)r   rt   r   r#  r   )r*   rt   Zoutput_intentr(   r(   r,   _add_output_intents  s    z"OutputProducer._add_output_intentsc                 C   s<   | j }tt|dd |j|j|jd}|  |_| | |S )Nri   )ri   rj   rk   rl   )	r   rg   rY   rj   rk   rl   r  rt   r#  )r*   r   r   r(   r(   r,   r     s    


zOutputProducer._add_catalogc                 C   s&  | j }||_||_||_||_|rBtjtj }	tt	|g|	d|_
|jtkrdt|jft|j }
nt|jdddt|jd g}
t|
|_|rtddi|_|jrdd |jD }td	td
t|ii|_dd t|  D }|r|jd  s|dd |r"tdt	| i|_d S )NrU   r#   r"   d   z/Markedtruec                 S   s4   g | ],}|j rt|   d |   qS r`   )Zglobally_enclosedr   basenamer-   Z	file_spec)r[   r6  r(   r(   r,   
<listcomp>  s   z4OutputProducer._finalize_catalog.<locals>.<listcomp>z/EmbeddedFilesz/Namesc                 S   s2   g | ]*\}}|  r| d t|    qS r  )r   rd   r-   )r[   r   pager(   r(   r,   r  !  s   r   r   z0 <<>>z/Nums)r   rm   ru   rs   rq   r   ZSIGNATURES_EXISTZAPPEND_ONLYrT   r   rn   Z	zoom_modeZOOM_CONFIGSr   r   r   pdf_listro   rd   rp   r  rr   r  rC  r   insertr-   page_labels)r*   r   r  r  r  r  r  r  r   flagsZzoom_configZfile_spec_namesr  r(   r(   r,   r*    sR    
 


z OutputProducer._finalize_catalogc                 c   s0   t | j}d V  | j|  t | j| 7  < d S r'   )r   r   r  )r*   labelZ	prev_sizer(   r(   r,   r2  .  s    
zOutputProducer._trace_sizec                 C   s4   t d | j D ]\}}t d|t| qd S )Nz4Final size summary of the biggest document sections:z- %s: %s)rc  debugr  r  _sizeof_fmt)r*   r  Zsection_sizer(   r(   r,   r4  4  s    
z(OutputProducer._log_final_sections_sizes)N)!r.   r/   r0   r   r4   r;  r3  r#  r  rC  slicer!  r"  rs  rz  r~  rx  r  r  r  r$  r  r%  r&  r'  r(  r)  r  r   r*  r   r2  r4  r(   r(   r(   r,   r  3  s<   v
		 5	6	;B
:
r  F)r   c           
      C   s   |r|  ||||\}}}}|r2|}|| | }	n| }|| }	d|| dd|| dd|| dd|	| dd| d  dS )Nzq .2fz 0 0 r`   z cm /Ir   z Do Q)Zscale_inside_box)
r   rP  yr=   r  Zkeep_aspect_ratioZscaleZpdf_height_to_flipZstream_hZstream_yr(   r(   r,   stream_content_for_raster_image:  s    
>r  c              
   C   s@  d}i }i }d}d}d}t t| j dd d}|D ]}|| }	|	|d kr|j|kr|j|| d kr||g |j n||   |}||jg||< d	}d	||< q|r|	}|jg||< n|| |j d}n|	}|jg||< d}|	}|j}q6d}
d}d}|}t| D ]\}}t|}||krt|st||ksH|d
k rt||krX||= ||
 ||  ||
< ||= n|}
|| }||kr|d
k}||= |d8 }nd}qg }t| D ]r\}}tt	|dkr|d| d|t| d  d|d   n(|d| dd
dd |D  d qdd
| dS )Nr   r   Fc                 S   s   | d S r   r(   )itemr(   r(   r,   rI  \  rJ  z!_tt_font_widths.<locals>.<lambda>rK  r   Tr  r`   z [ c                 s   s   | ]}t t|V  qd S r'   )r   r   )r[   r  r(   r(   r,   rQ    s     z"_tt_font_widths.<locals>.<genexpr>z ]
[r   r   )r   ra  r   r  Zglyph_width
setdefaultr   popr   r   r   )rx   ZrangeidZrange_Zrange_intervalZprevcidZ	prevwidthintervalrT  rV  Z
cid_mappedZprevkZnextkZprevintrir/  wsZcwsr=   r(   r(   r,   rk  S  sh    

$


.,rk  c                 C   s   | \}}d|dd|ddS )Nz[0 0 r  r`   r   r(   )r   r   r   r(   r(   r,   rA    s    rA  Bc                 C   sD   dD ].}t | dk r*| d| |   S | d } q| dd| S )N)r   ZKiZMiZGiZTiPiZEiZZii   z3.1fz.1fZYi)abs)numsuffixunitr(   r(   r,   r    s
    
r  )Fr   N)r  )Rr   loggingcollectionsr   r   
contextlibr   ior   Z	fontToolsr   re  annotationsr   enumsr	   r
   r   r   errorsr   Z
line_breakr   Zimage_datastructuresr   outliner   signr   r   Zsyntaxr   r   r   r   r   r   r   r   rd   r   r  r   r   utilr   r   Zendesiver   ImportErrortypingr    r   r!   	getLoggerr.   rc  r  r&   r1   r6   rG   rL   rT   rg   rv   r}   r   r   r   r   r   r   r   r   r   r   r  r  rk  rA  r  r(   r(   r(   r,   <module>   s   
$	

	*1`	
*C+         D