a
    [XhB                     @   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 )Zbleed_)stylevalue).0Zsidepage_box X/var/www/viveiro_mudafortebrasil/venv/lib/python3.9/site-packages/weasyprint/document.py
<dictcomp>*   s   z!Page.__init__.<locals>.<dictcomp>)toprightZbottomleft)Zmargin_widthwidthZmargin_heightheightZbleedZ	bookmarkslinksanchorsZ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   Z	transformr   r)   )r*   streamscaler   r   r    paintS   s    
z
Page.paintN)r   )__name__
__module____qualname____doc__r+   r1   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 )DocumentMetadatazMeta-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   )r*   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   r   r   r   r    r+   _   s    



zDocumentMetadata.__init__)r2   r3   r4   r5   r   r+   r   r   r   r    r6   Z   s
   r6   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 )	DiskCachezDict-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)r*   folderr   r   r    r+      s    
zDiskCache.__init__c                 C   s   t | dd }| j| S )NF)usedforsecurity)r   encode	hexdigestrE   )r*   keydigestr   r   r    _path_from_key   s    zDiskCache._path_from_keyc                 C   s&   || j v r| j | S | | S d S r7   )rG   rP   
read_bytesr*   rN   r   r   r    __getitem__   s    

zDiskCache.__getitem__c                 C   s:   t |tr,| |}| j| || n
|| j|< d S r7   )
isinstancebytesrP   rI   addwrite_bytesrG   )r*   rN   r   pathr   r   r    __setitem__   s
    

zDiskCache.__setitem__c                 C   s   || j v p| | S r7   )rG   rP   existsrR   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)rI   unlinkrE   rmdir	Exception)r*   rX   r   r   r    __del__   s    
zDiskCache.__del__N)
r2   r3   r4   r5   r+   rP   rS   rY   r[   r`   r   r   r   r    rB      s   rB   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cacheZstylesheetsZmatcher)guess
media_typefont_configcounter_styleZpresentational_hintsZ	pdf_forms)rb   url_fetcheroptionsz&Step 4 - Creating formatting structure)r   rT   dictrB   hasattrr   rd   appendr	   	functoolspartialoriginal_get_image_from_urirg   r   infor   )clshtmlre   rf   rh   target_collectorZ
page_rulesZuser_stylesheetsrb   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
   rv   r   etree_elementrt   r   base_urlrr   Z	footnotesr   r6   r   rg   _html)	rp   rq   re   rf   rh   ru   Zroot_boxZ
page_boxesZ	renderingr   r   r    _render   s(    
zDocument._renderc                 C   s"   || _ || _|| _i | _|| _d S r7   )pagesmetadatarg   Zfontsre   )r*   r}   r~   rg   re   r   r   r    r+     s
    zDocument.__init__Nc                 C   sB   |d u r| j j}dd i||< |D ]}d|i||< | || q d S )Nparent)r{   ry   build_element_structure)r*   Z	structurery   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}   rT   listtyper~   rg   re   )r*   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   )r-   r.   fr,   )	enumerater}   r   r&   r   )
r*   r0   Ztransform_pagesrootZskipped_levelsZlast_by_depthZprevious_levelZ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 rt }|	|||
| | 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``).

        Zpdf_variantversionZpdf_version
identifierZpdf_identifierZuncompressed_pdfNwritewb)r   r   updater   r   ioBytesIOr   getvaluerj   open)r*   targetZzoomZfinisherrh   new_optionsvariant_Z
propertiespdfr   compressr   outputfdr   r   r    	write_pdf`  s.    



zDocument.write_pdf)N)r   )r   F)Nr   N)r2   r3   r4   r5   classmethodrv   r|   r+   r   r   r   r   r   r   r   r    ra      s   




 
!ra   )/r5   rl   r   hashlibr   pathlibr    r   r   r(   r   r   rs   r	   Zcss.countersr
   Zcss.targetsr   Zdrawr   r   Zformatting_structure.buildr   rq   r   Zimagesr   rn   Zlayoutr   r   loggerr   r   r   r   r   r   Zpdf.metadatar   Z
text.fontsr   r   r6   rB   ra   r   r   r   r    <module>   s.   A:/