a
    QhB                     @   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 )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   )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 )	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)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 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``).

        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:/