U
    :vh0                     @   s  d Z ddlZddlZddlmZ ddlmZ ddlmZ ddl	m	Z	m
Z
 dd Zd,ddZdd Zdd Zd-ddZG dd deZG dd deZG dd dZG dd deZd.ddZd d! ZG d"d# d#eZG d$d% d%ZG d&d' d'eZG d(d) d)eZG d*d+ d+eZdS )/a  
Classes & functions that represent core elements of the PDF syntax

Most of what happens in a PDF happens in objects, which are formatted like so:
```
3 0 obj
<</Type /Page
/Parent 1 0 R
/Resources 2 0 R
/Contents 4 0 R>>
endobj
```

The first line says that this is the third object in the structure of the document.

There are 8 kinds of objects (Adobe Reference, 51):

* Boolean values
* Integer and real numbers
* Strings
* Names
* Arrays
* Dictionaries
* Streams
* The null object

The `<<` in the second line and the `>>` in the line preceding `endobj` denote
that it is a dictionary object. Dictionaries map Names to other objects.

Names are the strings preceded by `/`, valid Names do not have to start with a
capital letter, they can be any ascii characters, # and two characters can
escape non-printable ascii characters, described on page 57.

`3 0 obj` means what follows here is the third object, but the name Type
(represented here by `/Type`) is mapped to an indirect object reference:
`0 obj` vs `0 R`.

The structure of this data, in python/dict form, is thus:
```
third_obj = {
  '/Type': '/Page'),
  '/Parent': iobj_ref(1),
  '/Resources': iobj_ref(2),
  '/Contents': iobj_ref(4),
}
```

Content streams are of the form:
```
4 0 obj
<</Filter /ASCIIHexDecode /Length 22>>
stream
68656c6c6f20776f726c64
endstream
endobj
```

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)ABC)hexlify)BOM_UTF16_BE)datetimetimezonec                 C   s   dd |   D S )Nc                 S   s   i | ]\}}|r||qS  r   .0kvr   r   //tmp/pip-unpacked-wheel-dvf6lv8i/fpdf/syntax.py
<dictcomp>G   s       z&clear_empty_fields.<locals>.<dictcomp>)items)dr   r   r   clear_empty_fieldsF   s    r   <<>>
 Fc                    s4   |rt | } d|| fdd|  D |gS )a{  format dictionary as PDF dictionary

    @param dict_: dictionary of values to render
    @param open_dict: string to open PDF dictionary
    @param close_dict: string to close PDF dictionary
    @param field_join: string to join fields with
    @param key_value_join: string to join key to value with
    @param has_empty_fields: whether or not to clear_empty_fields first.
     c                 3   s$   | ]\}}  |t|fV  qd S N)joinstrr   key_value_joinr   r   	<genexpr>a   s     z+create_dictionary_string.<locals>.<genexpr>)r   r   r   )Zdict_	open_dict
close_dictZ
field_joinr   Zhas_empty_fieldsr   r   r   create_dictionary_stringJ   s    r   c                 C   s   dd |  dS )z#format list of strings as PDF array[r   ])r   )list_r   r   r   create_list_stringg   s    r"   c                 C   s
   |  dS )z:format an indirect PDF Object reference from its id numberz 0 Rr   )nr   r   r   iobj_refl   s    r$   c                 C   s8   t | ttfrt| d} |r(|| | dd| dgS )Nlatin-1r   streamZ	endstream)
isinstance	bytearraybytesr   encryptr   )r&   Zencryption_handlerZobj_idr   r   r   create_streamq   s
    
r+   c                   @   s   e Zd ZdZdS )RawzVstr subclass signifying raw data to be directly emitted to PDF without transformation.N)__name__
__module____qualname____doc__r   r   r   r   r,   y   s   r,   c                   @   sF   e Zd ZdZededd eddD  d Zde	d	d
dZ
dS )NamezVstr subclass signifying a PDF name, which are emitted differently than normal strings.s   [^c                 c   s   | ]}|d kr|V  qdS )s   ()<>[]{}/%#\Nr   )r	   r   r   r   r   r      s      zName.<genexpr>!         ]N)returnc                 C   s$   | j dd |   }d| S )Nc                 S   s   d| d d  S )Ns   #%02Xr   r   )mr   r   r   <lambda>       z Name.serialize.<locals>.<lambda>/)NAME_ESCsubencodedecode)self_security_handler_obj_idescapedr   r   r   	serialize   s
     zName.serialize)NN)r-   r.   r/   r0   recompiler)   ranger:   r   rB   r   r   r   r   r1   }   s
   r1   c                   @   sV   e Zd Zdd Zedd Zejdd Zedd Zdd	d
Zdd Z	dddZ
dS )	PDFObjectc                 C   s
   d | _ d S r   _idr>   r   r   r   __init__   s    zPDFObject.__init__c                 C   s"   | j d krt| jj d| j S )Nz  has not been assigned an ID yet)rH   AttributeError	__class__r-   rI   r   r   r   id   s
    
zPDFObject.idc                 C   s
   || _ d S r   rG   )r>   r#   r   r   r   rM      s    c                 C   s
   t | jS r   )r$   rM   rI   r   r   r   ref   s    zPDFObject.refNc                 C   sz   g }| | j d | d |s.| |}| t|ddd | d |  }|rf| t| | d d|S )z8Serialize the PDF object as an obj<</>>endobj text blockz 0 objr   r   )r   r   r   Zendobjr   )appendrM   _build_obj_dictr   content_streamr+   r   )r>   obj_dictr?   outputrQ   r   r   r   rB      s    



zPDFObject.serializec                 C   s   dS )zPSubclasses can override this method to indicate the presence of a content streamr8   r   rI   r   r   r   rQ      s    zPDFObject.content_streamc                    s"   t  fddt D | jdS )z
        Build the PDF Object associative map to serialize,
        based on this class instance properties.
        The property names are converted from snake_case to CamelCase,
        and prefixed with a slash character "/".
        c                    s   i | ]}|t  |qS r   )getattr)r	   keyrI   r   r   r      s      z-PDFObject._build_obj_dict.<locals>.<dictcomp>r?   r@   )build_obj_dictdirrM   )r>   Zsecurity_handlerr   rI   r   rP      s
    zPDFObject._build_obj_dict)NN)N)r-   r.   r/   rJ   propertyrM   setterrN   rB   rQ   rP   r   r   r   r   rF      s   



rF   c                       s8   e Zd ZdZd
 fdd	Zdd Zd fdd		Z  ZS )PDFContentStreamFc                    sF   t    |rtj|| jdn|| _|r0tdnd | _t| j| _	d S )N)levelZFlateDecode)
superrJ   zlibcompress_COMPRESSION_LEVEL	_contentsr1   filterlenlength)r>   contentsr`   rL   r   r   rJ      s    
zPDFContentStream.__init__c                 C   s   | j S r   )rb   rI   r   r   r   rQ      s    zPDFContentStream.content_streamNc                    sV   |rH|rt t| jttfs*| jd| _|| j| j| _t| j| _	t
 ||S )Nr%   )AssertionErrorr'   rb   r(   r)   r<   r*   rM   rd   re   r^   rB   )r>   rR   r?   rg   r   r   rB      s    zPDFContentStream.serialize)F)NN)r-   r.   r/   ra   rJ   rQ   rB   __classcell__r   r   rg   r   r[      s   r[   c                 C   s   i }|   D ]\}}t|s|ds|dks|dkr8qt|drH|j}t|trZ|j}n0t|drt|j||d}nt|t	rt
| }||dt| < q|S )z
    Build the PDF Object associative map to serialize, based on a key-values dict.
    The property names are converted from snake_case to CamelCase,
    and prefixed with a slash character "/".
    _)rM   rN   NvaluerB   rV   r9   )r   callable
startswithhasattrrk   r'   rF   rN   rB   boolr   lower
camel_case)
key_valuesr?   r@   rR   rU   rk   r   r   r   rW      s0    


 
rW   c                 C   s   d dd |  D S )Nr   c                 s   s   | ]}|d kr|V  qdS )rj   Nr   )r	   xr   r   r   r     s      zcamel_case.<locals>.<genexpr>)r   title)Z
snake_caser   r   r   rq     s    rq   c                       s,   e Zd ZdZd fdd	Zd	ddZ  ZS )
	PDFStringTFc                    s   t  | |}||_|S )z
        Args:
            content (str): text
            encrypt (bool): if document encryption is enabled, should this string be encrypted?
        )r^   __new__r*   )clscontentr*   r>   rg   r   r   rv     s    zPDFString.__new__Nc                 C   s   |r| j r|st|| |S z| d d|  dW S  tk
rJ   Y nX | jrvtt| d d}d| dS d| dd dS )	Nascii()z	utf-16-ber%   <>zUTF-16)	r*   rh   encrypt_stringr<   UnicodeEncodeErrorUSE_HEX_ENCODINGr   r   r=   )r>   r?   r@   hex_strr   r   r   rB     s    

zPDFString.serialize)F)NN)r-   r.   r/   r   rv   rB   ri   r   r   rg   r   ru     s   
ru   c                   @   s.   e Zd Zd
edddZdd Zddd	ZdS )PDFDateF)datec                 C   s   || _ || _|| _dS )z
        Args:
            date (datetime): self-explanatory
            with_tz (bool): should the timezone be encoded in included in the date?
            encrypt (bool): if document encryption is enabled, should this string be encrypted?
        Nr   with_tzr*   )r>   r   r   r*   r   r   r   rJ   )  s    zPDFDate.__init__c                 C   s   d| j  d| j d| j dS )NzPDFDate(z
, with_tz=z
, encrypt=r{   r   rI   r   r   r   __repr__4  s    zPDFDate.__repr__Nc                 C   s   | j r`| jjst| jjtjkr0d| jd}qnd| jd}|d d d |dd   d }nd| jd}|r| jr|st|||S d| dS )	NzD:z%Y%m%d%H%M%SZz%Y%m%d%H%M%S%z'z%Y%m%d%H%M%Srz   r{   )r   r   tzinforh   r   utcr*   r~   )r>   r?   r@   Zout_strr   r   r   rB   7  s    "
zPDFDate.serialize)FF)NN)r-   r.   r/   r   rJ   r   rB   r   r   r   r   r   (  s   r   c                   @   s   e Zd ZdddZdS )PDFArrayNc                    sl   t dd | D rd| }nBt dd | D rFddd | D }nd fdd| D }d| d	S )
Nc                 s   s   | ]}t |tV  qd S r   )r'   r   r	   elemr   r   r   r   I  s     z%PDFArray.serialize.<locals>.<genexpr>r   c                 s   s   | ]}t |ttfV  qd S r   )r'   intfloatr   r   r   r   r   K  s     c                 s   s   | ]}t |V  qd S r   )r   r   r   r   r   r   L  s     r   c                 3   s,   | ]$}t |tr|jn|j d V  qdS )rV   N)r'   rF   rN   rB   r   r@   r?   r   r   r   N  s    r   r    )allr   )r>   r?   r@   Zserialized_elemsr   r   r   rB   H  s    
zPDFArray.serialize)NNr-   r.   r/   rB   r   r   r   r   r   G  s   r   c                   @   s   e Zd ZdddZdS )DestinationNc                 C   s   t d S r   )NotImplementedError)r>   r?   r@   r   r   r   rB   ]  s    zDestination.serialize)NNr   r   r   r   r   r   \  s   r   c                   @   sB   e Zd ZdddZdd Zdd Zd	d
 ZdddZdddZdS )DestinationXYZr   nullc                 C   s"   || _ || _|| _|| _d | _d S r   page_numbertopleftzoompage_refr>   pager   r   r   r   r   r   rJ   b  s
    zDestinationXYZ.__init__c                 C   s0   | j |j ko.| j|jko.| j|jko.| j|jkS r   )r   r   r   r   )r>   destr   r   r   __eq__i  s    


zDestinationXYZ.__eq__c                 C   s   t | j| j| j| jfS r   )hashr   r   r   r   rI   r   r   r   __hash__q  s    zDestinationXYZ.__hash__c                 C   s.   d| j  d| j d| j d| j d| j dS )NzDestinationXYZ(page_number=z, top=z, left=z, zoom="z", page_ref=r{   r   rI   r   r   r   r   t  s    zDestinationXYZ.__repr__Nc              	   C   sh   t | jtrt| jdn| j}t | jtr6t| jdn| j}| jsFtd| j d| d| d| j d	S )N   r   z /XYZ r   r    )r'   r   r   roundr   r   rh   r   )r>   r?   r@   r   r   r   r   r   rB   w  s    
zDestinationXYZ.serializec                 C   sV   | j rtdt|d kr| jn||d kr.| jn||d kr>| jn||d krN| jn|dS )Nz7DestinationXYZ should not be copied after serialization)r   r   r   r   )r   rh   r   r   r   r   r   r   r   r   r   replace}  s    zDestinationXYZ.replace)r   r   )NN)NNNN)	r-   r.   r/   rJ   r   r   r   rB   r   r   r   r   r   r   a  s   

r   )r   r   r   r   F)NN)NN)r0   rC   r_   abcr   binasciir   codecsr   r   r   r   r   r"   r$   r+   r   r,   r1   rF   r[   rW   rq   ru   r   listr   r   r   r   r   r   r   <module>   s4   >     

;
"