o
    Zh0hB                     @   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 I/var/www/html/rh/venv/lib/python3.10/site-packages/weasyprint/document.py
<dictcomp>*   s    z!Page.__init__.<locals>.<dictcomp>)toprightbottomleft)margin_widthwidthmargin_heightheightbleed	bookmarkslinksanchorsformsr   	_page_box)selfr    r!   r   r"   __init__!   s   


	

zPage.__init__r   c                 C   sH   t | |j||d t| j| W d   dS 1 sw   Y  dS )z!Paint the page into the PDF file.adN)r   	transformr   r1   )r2   streamscaler!   r!   r"   paintS   s   
"z
Page.paintN)r   )__name__
__module____qualname____doc__r3   r:   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 | _|| _|| _|| _|pg | _|	| _|
p$i | _	|| _
d S N)titleauthorsdescriptionkeywords	generatorcreatedmodifiedattachmentslangcustomr   )r2   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   r   r!   r!   r"   r3   _   s   




zDocumentMetadata.__init__)r;   r<   r=   r>   r   r3   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)r2   folderr!   r!   r"   r3      s   
zDiskCache.__init__c                 C   s   t | dd }| j| S )NF)usedforsecurity)r   encode	hexdigestrN   )r2   keydigestr!   r!   r"   _path_from_key   s   
zDiskCache._path_from_keyc                 C   s"   || j v r
| j | S | | S r@   )rP   rY   
read_bytesr2   rW   r!   r!   r"   __getitem__   s   

zDiskCache.__getitem__c                 C   s<   t |tr| |}| j| || d S || j|< d S r@   )
isinstancebytesrY   rR   addwrite_bytesrP   )r2   rW   r   pathr!   r!   r"   __setitem__   s
   

zDiskCache.__setitem__c                 C   s   || j v p| | S r@   )rP   rY   existsr[   r!   r!   r"   __contains__   s   
zDiskCache.__contains__c                 C   s>   z| j D ]}|jdd q| j  W d S  ty   Y d S w )NT)
missing_ok)rR   unlinkrN   rmdir	Exception)r2   ra   r!   r!   r"   __del__   s   
zDiskCache.__del__N)
r;   r<   r=   r>   r3   rY   r\   rb   rd   ri   r!   r!   r!   r"   rK      s    rK   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 p"g D ]}	t|	ds3t|	|j||d}	||	 q#t|||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)rk   url_fetcheroptionsz&Step 4 - Creating formatting structure)r   r]   dictrK   hasattrr   ro   appendr	   	functoolspartialoriginal_get_image_from_urirt   r   infor   )clshtmlrp   rq   ru   target_collector
page_rulesuser_stylesheetsrk   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di t||j|}||_|S )Nc                 S   s   g | ]}t |qS r!   )r   )r   r    r!   r!   r"   
<listcomp>   s    z$Document._render.<locals>.<listcomp>r!   )r   r
   r   r   etree_elementr   r   base_urlr   	footnotesr   r?   r   rt   _html)	r}   r~   rp   rq   ru   r   root_box
page_boxes	renderingr!   r!   r"   _render   s(   
zDocument._renderc                 C   s"   || _ || _|| _i | _|| _d S r@   )pagesmetadatart   fontsrp   )r2   r   r   rt   rp   r!   r!   r"   r3     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)r2   	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   rt   rp   )r2   r   r!   r!   r"   copy  s   
zDocument.copyr   Fc           
      C   sd   g }g }|g}d}t | jD ]!\}}|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   )r5   r6   fr4   )	enumerater   r   r+   r   )
r2   r9   transform_pagesrootskipped_levelslast_by_depthprevious_levelpage_numberpagematrixr!   r!   r"   make_bookmark_tree?  s   zDocument.make_bookmark_treec                 K   s(  t  }|| |}|d  }r3t| \}}d|v r%|d s%|d |d< d|v r3|d s3|d |d< t| ||fi |}	|rD|| |	 |d }
|d  }|d }|du ret }|	|||
| | S t	|drt|	|||
| dS t
|d	}|	|||
| W d   dS 1 sw   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   getvaluerw   open)r2   targetzoomfinisherru   new_optionsvariant_
propertiespdfr   compressr   outputfdr!   r!   r"   	write_pdf`  s0   



"zDocument.write_pdfr@   )r   )r   F)Nr   N)r;   r<   r=   r>   classmethodr   r   r3   r   r   r   r   r!   r!   r!   r"   rj      s    





 !rj   )/r>   ry   r   hashlibr   pathlibr    r   r   r/   r   r   r   r	   css.countersr
   css.targetsr   drawr   r   formatting_structure.buildr   r~   r   imagesr   r{   layoutr   r   loggerr   r   r   r   r   r   pdf.metadatar   
text.fontsr   r   r?   rK   rj   r!   r!   r!   r"   <module>   s0    A:/