
    3vj6                     0   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 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      Z* G d d      Z+ G d d      Z,y)zDocument generation management.    N)md5)Path   )CSSDEFAULT_OPTIONS)gather_anchorsmake_page_bookmark_tree)get_all_computed_styles)CounterStyle)TargetCollector)	draw_page)build_formatting_structure)get_html_metadata)get_image_from_uri)LayoutContextlayout_document)PROGRESS_LOGGER)Matrix)VARIANTSgenerate_pdf)DocumentMetadata)FontConfigurationc                       e Zd ZdZd ZddZy)PagezRepresents a single rendered page.

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

    c                 z   |j                         | _        |j                         | _        dD ci c]  }||j                  d|    j
                  ! c}| _        g | _        g | _        i | _	        d g i| _
        t        || j                  | j                  | j                  | j                         || _        y c c}w )N)toprightbottomleftbleed_)margin_widthwidthmargin_heightheightstylevaluebleed	bookmarkslinksanchorsformsr   	_page_box)selfpage_boxsides      F/root/.hermes/venv/lib/python3.12/site-packages/weasyprint/document.py__init__zPage.__init__!   s    **,
 ,,. ;< (..6$1777<
  
  BZ
xtzz4>>4::V!O<s   $B8c                     |j                         5  |j                  ||       t        | j                  |       ddd       y# 1 sw Y   yxY w)z!Paint the page into the PDF file.adN)stacked	transformr   r,   )r-   streamscales      r0   paintz
Page.paintS   sB    ^^ 	.u.dnnf-	. 	. 	.s   *AAN)r   )__name__
__module____qualname____doc__r1   r:        r0   r   r      s    0"d.r@   r   c                   4    e Zd ZdZd Zd Zd Zd Zd Zd Z	y)		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                     t        |      | _        | j                  j                  dd       i | _        t	               | _        y )NT)parentsexist_ok)r   _pathmkdir_memory_cacheset_disk_paths)r-   folders     r0   r1   zDiskCache.__init__b   s6    &\


55r@   c                 r    t        |j                         d      j                         }| j                  |z  S )NF)usedforsecurity)r   encode	hexdigestrF   )r-   keydigests      r0   _path_from_keyzDiskCache._path_from_keyh   s,    SZZ\59CCEzzF""r@   c                 z    || j                   v r| j                   |   S | j                  |      j                         S N)rH   rR   
read_bytesr-   rP   s     r0   __getitem__zDiskCache.__getitem__l   s;    $$$$%%c**&&s+6688r@   c                     t        |t              r>| j                  |      }| j                  j	                  |       |j                  |       y || j                  |<   y rT   )
isinstancebytesrR   rJ   addwrite_bytesrH   )r-   rP   r&   paths       r0   __setitem__zDiskCache.__setitem__r   sN    eU#&&s+D  &U#&+Ds#r@   c                 `    || j                   v xs | j                  |      j                         S rT   )rH   rR   existsrV   s     r0   __contains__zDiskCache.__contains__z   s1    4%%% .$++-	/r@   c                     	 | j                   D ]  }|j                  d        | j                  j                          y # t        $ r Y y w xY w)NT)
missing_ok)rJ   unlinkrF   rmdir	Exception)r-   r]   s     r0   __del__zDiskCache.__del__   sL    	(( -t,-JJ 		s   =A   	AAN)
r;   r<   r=   r>   r1   rR   rW   r^   ra   rg   r?   r@   r0   rB   rB   Z   s%    !#9,/
r@   rB   c                   N    e Zd ZdZed        Zed        Zd Zd	dZd
dZ	ddZ
y)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 :class:`url_fetcher
    <weasyprint.urls.URLFetcher>`, and a :class:`font_config
    <weasyprint.text.fonts.FontConfiguration>`.

    c                    t               }g }g }g }	|d   }
|
i }
n!t        |
t        t        f      st        |
      }
|d   xs g D ]9  }t	        |d      st        ||j                  |||      }|	j                  |       ; t        ||	|d   |||||||d   
      }t        j                  t        |
|j                  |      }t        j                  d       t        |||||      }|S )	Ncachestylesheetsmatcher)guess
media_typefont_configcounter_stylecolor_profilespresentational_hints	pdf_forms)rk   url_fetcheroptionsz&Step 4 - Creating formatting structure)r   rY   dictrB   hasattrr   ro   appendr
   	functoolspartialoriginal_get_image_from_uriru   r   infor   )clshtmlrp   rq   rr   rv   target_collector
page_ruleslayersuser_stylesheetsrk   css	style_forr   contexts                  r0   _build_layout_contextzDocument._build_layout_context   s    +,
 =EED)#45e$E=)/R 	)C3	*$// +=#13 ##C(	) ,"G,B$C[>:v?OK "	 '..'u(('; 	EF); r@   c           
      B   |
t               }|
t               }|i }|d   x}r=t        |   \  }}t        |j	                               D ]  \  }	}
|
	|	|v s||	   ||	<    | j                  |||||      }t        |j                  |j                  |j                  |j                  |j                  ||j                        }t        |||      } | |D cg c]  }t        |       c}t        di t!        |      |j"                  |||d         }||_        |S c c}w )Npdf_variantoutput_intentr?   )r   r   r   tupleitemsr   r   etree_elementr   r   base_urlr   	footnotesr   r   r   r   ru   _html)r~   r   rp   rq   rr   rv   variant_
propertiesrP   r&   r   root_box
page_boxesr.   	renderings                   r0   _renderzDocument._render   sB   +-K (NM!N m,,7,$W-MAz#GMMO4 3
U=SJ%6#-c?GCL3 +++}ngG . 1 173M3MMM733]
 %T8W=
,67T(^77067k>7?;SU	 		 8s   Dc                 f    || _         || _        || _        i | _        || _        || _        || _        y rT   )pagesmetadataru   fontsrp   rr   r   )r-   r   r   ru   rp   rr   r   s          r0   r1   zDocument.__init__   s?     
 !& 

 ',*r@   c                     |dk(  r| j                   }nt        |t              st        |      } t        |       || j                  | j
                  | 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')

        all)	r   rY   listtyper   ru   rp   rr   r   )r-   r   s     r0   copyzDocument.copy   sd    2 E>JJEE4(KEtDz4==$"2"2D4D4D!3!35 	5r@   c           	          g }g }|g}d}t        | j                        D ]A  \  }}|rt        || |j                  |z        }	nt        ||      }	t	        ||||||	      }C |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	   )
r-   r9   transform_pagesrootskipped_levelslast_by_depthprevious_levelpage_numberpagematrixs
             r0   make_bookmark_treezDocument.make_bookmark_tree  s     
 !*4::!6 	%K%E6T[[55HI%514nm^V%N	% r@   Nc                 L   t        j                         }|j                  |       |}|d   x}r=t        |   \  }}t	        |j                               D ]  \  }	}
|
	|	|v s||	   ||	<    t        | ||fi |}|r	 || |       |d   }|d    }|d   }|8t        j                         }|j                  ||||       |j                         S t        |d      r|j                  ||||       yt        |d      5 }|j                  ||||       ddd       y# 1 sw Y   yxY w)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``).

        r   Npdf_identifieruncompressed_pdfpdf_versionwritewb)r   r   updater   r   r   r   ioBytesIOr   getvaluerx   open)r-   targetzoomfinisherrv   new_optionsr   r   r   rP   r&   pdf
identifiercompressversionoutputfds                    r0   	write_pdfzDocument.write_pdf/  s?   6 &**,7# m,,7,$W-MAz#GMMO4 3
U=SJ%6#-c?GCL3 499T3-.
122-(>ZZ\FIIfgz8<??$$67#IIfgz8<fd# =r		"gz8<= = =s   <DD#)r   )r   F)Nr   N)r;   r<   r=   r>   classmethodr   r   r1   r   r   r   r?   r@   r0   ri   ri      sF      >  B+.5BB8=r@   ri   )-r>   rz   r   hashlibr   pathlibr    r   r   r*   r   r	   r   r
   css.countersr   css.targetsr   drawr   formatting_structure.buildr   r   r   imagesr   r|   layoutr   r   loggerr   r   r   r   r   r   pdf.metadatar   
text.fontsr   r   rB   ri   r?   r@   r0   <module>r      sc    %  	   " < ( & (  B # E 2 #  ' * )>. >.B, ,^^= ^=r@   