a
    ¥Q•hëB  ã                   @   s0  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m	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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! ddl"m#Z# ddl$m%Z%m&Z& ddl'm(Z( ddl)m*Z* G dd„ dƒZ+G dd„ dƒZ,G dd„ dƒZ-G dd„ dƒZ.dS )zDocument generation management.é    N)Úmd5)ÚPathé   )ÚCSSÚDEFAULT_OPTIONS)Úgather_anchorsÚmake_page_bookmark_tree)Úget_all_computed_styles)ÚCounterStyle)ÚTargetCollector)Ú	draw_pageÚstacked)Úbuild_formatting_structure)Úget_html_metadata)Úget_image_from_uri)ÚLayoutContextÚlayout_document)ÚPROGRESS_LOGGER)ÚMatrix)ÚVARIANTSÚgenerate_pdf)Úgenerate_rdf_metadata)ÚFontConfigurationc                   @   s"   e Zd ZdZdd„ Zddd„ZdS )	ÚPagezRepresents a single rendered page.

    Should be obtained from :attr:`Document.pages` but not
    instantiated directly.

    c                    sf   ˆ   ¡ | _ˆ  ¡ | _‡ fdd„dD ƒ| _g | _g | _i | _d g i| _t	ˆ | j| j| j| jƒ ˆ | _
d S )Nc                    s    i | ]}|ˆ j d |› � j“qS )Úbleed_)ÚstyleÚvalue)Ú.0Úside©Úpage_box© úL/var/www/sistema_ama/venv/lib/python3.9/site-packages/weasyprint/document.pyÚ
<dictcomp>*   s   ÿz!Page.__init__.<locals>.<dictcomp>)ÚtopÚrightÚbottomÚleft)Úmargin_widthÚwidthÚmargin_heightÚheightÚbleedZ	bookmarksÚlinksÚanchorsÚformsr   Ú	_page_box)Úselfr    r!   r   r"   Ú__init__!   s    


þ	
zPage.__init__r   c                 C   sF   t |ƒ�* |j||d� t| j|ƒ W d  ƒ n1 s80    Y  dS )z!Paint the page into the PDF file.©ÚaÚdN)r   Ú	transformr   r0   )r1   ÚstreamÚscaler!   r!   r"   ÚpaintS   s    
z
Page.paintN)r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r2   r9   r!   r!   r!   r"   r      s   2r   c                   @   s0   e Zd ZdZddddddddddefdd„ZdS )ÚDocumentMetadataz€Meta-information belonging to a whole :class:`Document`.

    New attributes may be added in future versions of WeasyPrint.
    Nc                 C   sV   || _ |pg | _|| _|pg | _|| _|| _|| _|p8g | _|	| _|
pHi | _	|| _
d S ©N)ÚtitleÚauthorsÚdescriptionÚkeywordsÚ	generatorÚcreatedÚmodifiedÚattachmentsÚlangÚcustomr   )r1   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   r   r!   r!   r"   r2   _   s    



zDocumentMetadata.__init__)r:   r;   r<   r=   r   r2   r!   r!   r!   r"   r>   Z   s
   þr>   c                   @   s@   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	dS )Ú	DiskCachez¸Dict-like storing images content on disk.

    Bytestring values are stored on disk. Other lightweight Python objects
    (i.e. RasterImage instances) are still stored in memory.

    c                 C   s,   t |ƒ| _| jjddd� i | _tƒ | _d S )NT)ÚparentsÚexist_ok)r   Ú_pathÚmkdirÚ_memory_cacheÚsetÚ_disk_paths)r1   Zfolderr!   r!   r"   r2   œ   s    
zDiskCache.__init__c                 C   s   t | ¡ dd� ¡ }| j| S )NF)Úusedforsecurity)r   ÚencodeÚ	hexdigestrM   )r1   ÚkeyÚdigestr!   r!   r"   Ú_path_from_key¢   s    zDiskCache._path_from_keyc                 C   s&   || j v r| j | S |  |¡ ¡ S d S r?   )rO   rW   Ú
read_bytes©r1   rU   r!   r!   r"   Ú__getitem__¦   s    

zDiskCache.__getitem__c                 C   s:   t |tƒr,|  |¡}| j |¡ | |¡ n
|| j|< d S r?   )Ú
isinstanceÚbytesrW   rQ   ÚaddÚwrite_bytesrO   )r1   rU   r   Úpathr!   r!   r"   Ú__setitem__¬   s
    

zDiskCache.__setitem__c                 C   s   || j v p|  |¡ ¡ S r?   )rO   rW   ÚexistsrY   r!   r!   r"   Ú__contains__´   s    
þzDiskCache.__contains__c                 C   s>   z&| j D ]}|jdd� q| j ¡  W n ty8   Y n0 d S )NT)Ú
missing_ok)rQ   ÚunlinkrM   ÚrmdirÚ	Exception)r1   r_   r!   r!   r"   Ú__del__¹   s    
zDiskCache.__del__N)
r:   r;   r<   r=   r2   rW   rZ   r`   rb   rg   r!   r!   r!   r"   rJ   ”   s   rJ   c                   @   sX   e Zd ZdZedd„ ƒZedd„ ƒZdd„ Zdd	d
„Zddd„Z	ddd„Z
ddd„ZdS )ÚDocumentaŸ  A rendered document ready to be painted in a pydyf stream.

    Typically obtained from :meth:`HTML.render() <weasyprint.HTML.render>`, but
    can also be instantiated directly with a list of :class:`pages <Page>`, a
    set of :class:`metadata <DocumentMetadata>`, a :func:`url_fetcher
    <weasyprint.default_url_fetcher>` function, and a :class:`font_config
    <weasyprint.text.fonts.FontConfiguration>`.

    c              
   C   sÂ   t ƒ }g }g }|d }|d u r$i }nt|ttfƒs:t|ƒ}|d pDg D ]*}	t|	dƒsft|	|j||d�}	| |	¡ qFt|||d |||||d ƒ}
t	j
t||j|d�}t d¡ t|
||||ƒ}|S )	NÚcacheÚstylesheetsÚmatcher)ÚguessÚ
media_typeÚfont_configÚcounter_styleÚpresentational_hintsÚ	pdf_forms)ri   Úurl_fetcherÚoptionsz&Step 4 - Creating formatting structure)r   r[   ÚdictrJ   Úhasattrr   rm   Úappendr	   Ú	functoolsÚpartialÚoriginal_get_image_from_urirr   r   Úinfor   )ÚclsÚhtmlrn   ro   rs   Útarget_collectorÚ
page_rulesÚuser_stylesheetsri   ÚcssÚ	style_forr   Úcontextr!   r!   r"   Ú_build_layout_contextÎ   s<    
þ
ýþ
þzDocument._build_layout_contextc           	      C   sŠ   |d u rt ƒ }|d u rtƒ }|  ||||¡}t|j|j|j|j|j||j	ƒ}t
|||ƒ}| dd„ |D ƒtf i t|ƒ¤Ž|j|ƒ}||_|S )Nc                 S   s   g | ]}t |ƒ‘qS r!   )r   )r   r    r!   r!   r"   Ú
<listcomp>ý   ó    z$Document._render.<locals>.<listcomp>)r   r
   rƒ   r   Úetree_elementr�   r   Úbase_urlr}   Ú	footnotesr   r>   r   rr   Ú_html)	r{   r|   rn   ro   rs   r‚   Úroot_boxZ
page_boxesZ	renderingr!   r!   r"   Ú_renderë   s(    ÿ
ýýzDocument._renderc                 C   s"   || _ || _|| _i | _|| _d S r?   )ÚpagesÚmetadatarr   Úfontsrn   )r1   rŒ   r�   rr   rn   r!   r!   r"   r2     s
    zDocument.__init__Nc                 C   sB   |d u r| j j}dd i||< |D ]}d|i||< |  ||¡ q d S )NÚparent)r‰   r†   Úbuild_element_structure)r1   Z	structurer†   Úchildr!   r!   r"   r�     s    z Document.build_element_structureÚallc                 C   s:   |dkr| j }nt|tƒs"t|ƒ}t| ƒ|| j| j| jƒS )aP  Take a subset of the pages.

        :type pages: :term:`iterable`
        :param pages:
            An iterable of :class:`Page` objects from :attr:`pages`.
        :return:
            A new :class:`Document` object.

        Examples:

        Write two PDF files for odd-numbered and even-numbered pages::

            # Python lists count from 0 but pages are numbered from 1.
            # [::2] is a slice of even list indexes but odd-numbered pages.
            document.copy(document.pages[::2]).write_pdf('odd_pages.pdf')
            document.copy(document.pages[1::2]).write_pdf('even_pages.pdf')

        Combine multiple documents into one PDF file,
        using metadata from the first::

            all_pages = [p for doc in documents for p in doc.pages]
            documents[0].copy(all_pages).write_pdf('combined.pdf')

        r’   )rŒ   r[   ÚlistÚtyper�   rr   rn   )r1   rŒ   r!   r!   r"   Úcopy  s    
ÿzDocument.copyr   Fc           
      C   sd   g }g }|g}d}t | jƒD ]B\}}|r@t|| |j| d�}	nt||d�}	t||||||	ƒ}q|S )aE  Make a tree of all bookmarks in the document.

        :param float scale:
            Zoom scale.
        :param bool transform_pages:
            A boolean defining whether the default PDF page transformation
            matrix has to be applied to bookmark coordinates, setting the
            bottom-left corner as the origin.
        :return: A list of bookmark subtrees.
            A subtree is ``(label, target, children, state)``. ``label`` is
            a string, ``target`` is ``(page_number, x, y)``  and ``children``
            is a list of child subtrees.

        r   )r4   r5   Úfr3   )Ú	enumeraterŒ   r   r+   r   )
r1   r8   Ztransform_pagesÚrootZskipped_levelsZlast_by_depthÚprevious_levelÚpage_numberÚpageÚmatrixr!   r!   r"   Úmake_bookmark_tree?  s    þzDocument.make_bookmark_treec                 K   s&  t  ¡ }| |¡ |}|d  }rft| \}}d|v rJ|d sJ|d |d< d|v rf|d sf|d |d< t| ||fi |¤Ž}	|rˆ|| |	ƒ |d }
|d  }|d }|du rÊt ¡ }|	 |||
|¡ | ¡ S t	|dƒræ|	 |||
|¡ n<t
|d	ƒ� }|	 |||
|¡ W d  ƒ n1 �s0    Y  dS )
a¤  Paint the pages in a PDF file, with metadata.

        :type target:
            :class:`str`, :class:`pathlib.Path` or :term:`file object`
        :param target:
            A filename where the PDF file is generated, a file object, or
            :obj:`None`.
        :param float zoom:
            The zoom factor in PDF units per CSS units.  **Warning**:
            All CSS units are affected, including physical units like
            ``cm`` and named sizes like ``A4``.  For values other than
            1, the physical CSS units will thus be "wrong".
        :type finisher: :term:`callable`
        :param finisher:
            A finisher function or callable that accepts the document and a
            :class:`pydyf.PDF` object as parameters. Can be passed to perform
            post-processing on the PDF right before the trailer is written.
        :param options:
            The ``options`` parameter includes by default the
            :data:`weasyprint.DEFAULT_OPTIONS` values.
        :returns:
            The PDF as :obj:`bytes` if ``target`` is not provided or
            :obj:`None`, otherwise :obj:`None` (the PDF is written to
            ``target``).

        Úpdf_variantÚversionÚpdf_versionÚ
identifierÚpdf_identifierÚuncompressed_pdfNÚwriteÚwb)r   r•   Úupdater   r   ÚioÚBytesIOr¤   Úgetvalueru   Úopen)r1   ÚtargetÚzoomÚfinisherrs   Únew_optionsÚvariantÚ_Ú
propertiesÚpdfr¡   ÚcompressrŸ   ÚoutputÚfdr!   r!   r"   Ú	write_pdf`  s.    



zDocument.write_pdf)N)r’   )r   F)Nr   N)r:   r;   r<   r=   Úclassmethodrƒ   r‹   r2   r�   r•   r�   r¶   r!   r!   r!   r"   rh   Ã   s   




 
!rh   )/r=   rw   r§   Úhashlibr   Úpathlibr   Ú r   r   r.   r   r   r€   r	   Zcss.countersr
   Zcss.targetsr   Údrawr   r   Zformatting_structure.buildr   r|   r   Úimagesr   ry   Úlayoutr   r   Úloggerr   rœ   r   r²   r   r   Zpdf.metadatar   Z
text.fontsr   r   r>   rJ   rh   r!   r!   r!   r"   Ú<module>   s.   A:/