
    >wg!+                         d dl Z d dlZd dlZd dlmZ ddlmZ ddlmZ d dl	Z	d dl
Z
	 e e  G d de      Zy# e$ r eZeZY w xY w)    N)OrderedDict   )Source)Configurationc                   ~    e Zd ZdZ G d de      Z	 	 ddZd ZddZddZ	e
d	        Zdd
Zd Zd Zd Zd Zd Zy)PDFKita,  
    Main class that does all generation routine.

    :param url_or_file: str - either a URL, a path to a file or a string containing HTML
                       to convert
    :param type_: str - either 'url', 'file' or 'string'
    :param options: dict (optional) with wkhtmltopdf options, with or w/o '--'
    :param toc: dict (optional) - toc-specific wkhtmltopdf options, with or w/o '--'
    :param cover: str (optional) - url/filename with a cover html page
    :param configuration: (optional) instance of pdfkit.configuration.Configuration()
    c                       e Zd ZdZd Zd Zy)PDFKit.ImproperSourceErrorz!Wrong source type for stylesheetsc                     || _         y Nmsg)selfr   s     D/var/www/horilla/myenv/lib/python3.12/site-packages/pdfkit/pdfkit.py__init__z#PDFKit.ImproperSourceError.__init__#   s	    DH    c                     | j                   S r   r   )r   s    r   __str__z"PDFKit.ImproperSourceError.__str__&   s    88Or   N)__name__
__module____qualname____doc__r   r    r   r   ImproperSourceErrorr
       s    /		r   r   Nc
                 h   t        ||      | _        |
t               n|| _        	 | j                  j                  j                  d      | _        t               | _        | j                  j                         r*| j                  j                  | j                  |             | j                  j                  | _        || j                  j                  |       |i n|| _        || _        || _        |	| _        || _        g | _        y # t        $ r | j                  j                  | _        Y w xY w)Nutf-8)r   sourcer   configurationwkhtmltopdfdecodeAttributeErrorr   optionsisStringupdate_find_options_in_metaenvirontoccovercover_firstverbosecssstylesheets)
r   url_or_filetype_r"   r'   r(   r+   r   r)   r*   s
             r   r   zPDFKit.__init__)   s    [%01>1Fmo#0 		>#11==DDWMD #};;!LL : :; GH))11LL(2#
&#  	>#11==D	>s   *D
 
$D10D1c              #      K   | j                  |      D ]Q  \  }}| t        |t        t        f      r.t	        |      dk(  r
|d   r|d   sJ d       |d    |d    N| S yw)z
        Generator of args parts based on options specification.

        Note: Empty parts will be filtered out at _command generator
           r   r   zFOption value can only be either a string or a (tuple, list) of 2 itemsN)_normalize_options
isinstancelisttuplelen)r   optsoptkeyoptvals       r   _genargszPDFKit._genargsD   s~      #55d; 	NFFL&4-06{a'F1I&)  N  FN  NCQiQi	s   A'A)c              #   t  K   | j                   r| j                  | j                          | j                   | j                  s| j                  j                  ddi       | j                  | j                        D ]	  }|s|  | j                  r| j                  rd | j                   | j                  r+d | j                  | j                        D ]	  }|s|  | j                  r| j                  sd | j                   | j                  j                         s| j                  j                         rd n`t        | j                  j                  t              r| j                  j                          n| j                  j                  D ]  }|  |r| yd yw)z0
        Generator of all command parts
        --quiet r(   r'   -N)r+   _prepend_cssr   r*   r"   r$   r9   r(   r)   r'   r   r#   	isFileObjr2   
basestringto_s)r   pathargpartss       r   _commandzPDFKit._commandT   sX     88dhh'||LLB0}}T\\2 	G	 ::$**M**88K==2 "!M" ::d..M** ;;!T[[%:%:%<I$++,,j9kk&&((++ AG
 JIs   A?F8A F8#CF8c                 6    t        | j                  |            S r   )r3   rE   )r   rB   s     r   commandzPDFKit.command   s    DMM$'((r   c                    | dk(  ry |j                         }t        |      dkD  r%|j                         d   j                         dk(  ry d|v rt        d|z        d|v rt        d|z         |xs d	}t        d
j	                  | |            )Nr   r   Donezcannot connect to X serverz%s
You will need to run wkhtmltopdf within a "virtual" X server.
Go to the link below for more information
https://github.com/JazzCore/python-pdfkit/wiki/Using-wkhtmltopdf-without-X-serverErrorzwkhtmltopdf reported an error:
zUnknown Errorz5wkhtmltopdf exited with non-zero code {0}. error:
{1})
splitlinesr5   stripIOErrorformat)	exit_codestderrstderr_lines	error_msgs       r   handle_errorzPDFKit.handle_error   s    >((*
 |q V%6%6%8%<%B%B%D%N'61 n qww x x
 f<vEFF-o	NUUV_ajkllr   c                    | j                  |      }t        j                  dk(  rt        j                         }|xj
                  t        j                  z  c_        t        j                  |_        t        j                  |t        j                  t        j                  t        j                  | j                  |      }nNt        j                  |t        j                  t        j                  t        j                  | j                        }| j                  j                         s&| j                  j                         r6| j                  r*| j                  j!                         j#                  d      }nP| j                  j%                         r4| j                  j                  j'                         j#                  d      }nd }|j)                  |      \  }}|xs |xs d}|j+                  dd      }|j,                  }| j/                  ||       d	|vrt        j0                  j3                  |       |s|S 	 t5        j6                  |d
      5 }	|	j'                  d      }
|
dk(  rt9        ddj;                  |      z        	 d d d        y# 1 sw Y   y xY w# t8        t<        f$ r&}t9        ddj;                  |      d|d      d }~ww xY w)Nwin32)stdinstdoutrQ   envstartupinfo)rW   rX   rQ   rY   r   )inputr   replace)errorsr;   encoding   r<   zBCommand failed: %s
Check whhtmltopdf output without 'quiet' option TzCommand failed: z1
Check whhtmltopdf output without 'quiet' option
)rG   sysplatform
subprocessSTARTUPINFOdwFlagsSTARTF_USESHOWWINDOWSW_HIDEwShowWindowPopenPIPEr&   r   r#   isFiler+   rA   encoder?   readcommunicater    
returncoderT   rX   writecodecsopenrN   joinOSError)r   rB   argsrZ   resultr[   rX   rQ   rP   ftextes               r   to_pdfzPDFKit.to_pdf   s?   ||D!<<7"$002K:#B#BB&0&8&8K#%% oo!!LL'F  %% oo!!LLF ;;!dkk&8&8&:txxKK$$&--g6E[[""$KK&&++-44W=EE++%+8(6(Swy9%%	)V, D JJV$M	7TG4 vvay2:! #+-0XXd^#< = =    ! 	7#&88D>16 7 7	7s6   J" 5JJ" JJ" J" "K1!KKc              #   8  K   t        |j                               D ]z  \  }}d|vrd| j                  |      z  }n| j                  |      }t        |t         t        f      r|D ]  }||f 
 Tt        |t
              rdn|}||rt        |      n|f | yw)ah   Generator of 2-tuples (option-key, option-value).
        When options spec is a list, generate a 2-tuples per list item.

        :param options: dict {option name: value}

        returns:
          iterator (option-key, option-value)
          - option names lower cased and prepended with
          '--' if necessary. Non-empty values cast to str
        z--z--%sr<   N)r3   items_normalize_argr2   r4   boolunicode)r   r"   keyvaluenormalized_keyr8   normalized_values          r   r1   zPDFKit._normalize_options   s      w}}/ 	VJC3!'$*=*=c*B!B!%!4!4S!9%$/# 3F)6223 *4E$)?2U %Ew/?'@uUU	Vs   BBc                 "    |j                         S r   )lower)r   args     r   r~   zPDFKit._normalize_arg   s    yy{r   c                     d|z  S )Nz<style>%s</style>r   )r   
stylesheets     r   _style_tag_forzPDFKit._style_tag_for   s    "Z//r   c                 V   | j                   j                         s$t        | j                   j                   t              r| j	                  d      t        |t              s|g}g }|D ]A  }t        j                  |d      5 }|j                  |j                                d d d        C dj                  |      }| j                   j                         r|t        j                  | j                   j                         d      5 }|j                         }d d d        t        j                  d| j                  |      dz         d      | _         y | j                   j                         rd| j                   j                         v rL| j                   j                         j                  d| j                  |      dz         | j                   _         y | j                  |      | j                   j                         z   | j                   _         y y # 1 sw Y   xY w# 1 sw Y   
xY w)Nz6CSS files can be added only to a single file or stringzUTF-8r^   
z</head>string)r   isUrlr2   r3   r   rr   rs   appendrn   rt   rl   rA   r   r\   r   r#   )r   rB   css_dataprx   inps         r   r>   zPDFKit._prepend_css   s   ;;*T[[-?-?"F** ,< = = $%6D 	*AQ1 *Q)* *	* 99X&;;T[[--/'B affh It':':8'Dy'PQDK [[!!#DKK,,..%)[[%5%5%7%?%?t228<yH&J" &*%8%8%BT[[EUEUEW%W" $* *
 s    HHH	H(c                    t        |t        j                        s|j                  j                  dk(  r|j                         }i }t        j                  d|      D ]|  }t        j                  d| j                  j                  z  |      s1t        j                  d| j                  j                  z  |      d   }t        j                  d|      d   ||<   ~ |S )zReads 'content' and extracts options encoded in HTML meta tags

        :param content: str or file-like object - contains HTML to parse

        returns:
          dict: {config option: value}
        StreamReaderWriterz<meta [^>]*>zname=["']%szname=["']%s([^"']*)r   zcontent=["']([^"']*))r2   ioIOBase	__class__r   rn   refindallsearchr   meta_tag_prefix)r   contentfoundxnames        r   r%   zPDFKit._find_options_in_meta  s     w		*$$--1EEllnGNG4 	IAyy$*<*<*L*LLaPzz"9"&"4"4"D"D#EFGIIJL jj)A1EaHd		I r   )NNNNNFFr   )r   r   r   r   	Exceptionr   r   r9   rE   rG   staticmethodrT   r{   r1   r~   r   r>   r%   r   r   r   r   r      si    
i  JNJO6 .`) m m0?7BV20X8r   r   )r   rd   rb   collectionsr   r   r   r   r   r   rr   r@   r   	NameErrorstrobjectr   r   r   r   <module>r      sQ    	  
 #  ( 	 ]V ]  JGs   8 	AA