o
    Df!+                     @   s   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
ze e W n ey9   eZeZY nw G dd deZdS )    N)OrderedDict   )Source)Configurationc                   @   s   e Zd ZdZG dd deZ		dddZdd	 Zdd
dZdddZ	e
dd ZdddZdd Zdd Zdd Zdd Zdd ZdS )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                   @   s    e Zd ZdZdd Zdd ZdS )zPDFKit.ImproperSourceErrorz!Wrong source type for stylesheetsc                 C   s
   || _ d S Nmsg)selfr	    r   F/home/ubuntu/webapp/venv/lib/python3.10/site-packages/pdfkit/pdfkit.py__init__#   s   
z#PDFKit.ImproperSourceError.__init__c                 C   s   | j S r   r   )r
   r   r   r   __str__&   s   z"PDFKit.ImproperSourceError.__str__N)__name__
__module____qualname____doc__r   r   r   r   r   r   ImproperSourceError    s    r   NFc
           
      C   s   t ||| _|d u rt n|| _z
| jjd| _W n ty(   | jj| _Y nw t | _| j	 r;| j
| | | jj| _|d urJ| j
| |d u rPi n|| _|| _|| _|	| _|| _g | _d S )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"   r   r   r   r   )   s*   


zPDFKit.__init__c                 c   sn    |  |D ].\}}|V  t|ttfr1t|dkr"|d r"|d s&J d|d V  |d V  q|V  qdS )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optvalr   r   r   _genargsD   s   $
zPDFKit._genargsc                 c   s   | j r
| | j  | jV  | js| jddi | | jD ]}|r&|V  q| jr4| jr4dV  | jV  | j	rHdV  | | j	D ]}|rG|V  q@| jrU| jsUdV  | jV  | j
 s_| j
 rcdV  nt| j
j
trq| j
 V  n
| j
j
D ]}|V  qu|r|V  dS dV  dS )z0
        Generator of all command parts
        --quiet r    r   -N)r#   _prepend_cssr   r"   r   r   r0   r    r!   r   r   r   	isFileObjr)   
basestringto_s)r
   pathargpartsr   r   r   _commandT   s>   

zPDFKit._commandc                 C   s   t | |S r   )r*   r;   )r
   r8   r   r   r   command   s   zPDFKit.commandc                 C   sx   | dkrd S |  }t|dkr|  d  dkrd S d|v r&td| d|v r0td| |p3d	}td
| |)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})
splitlinesr,   stripIOErrorformat)	exit_codestderrstderr_lines	error_msgr   r   r   handle_error   s    zPDFKit.handle_errorc              
   C   s  |  |}tjdkr*t }| jtjO  _tj|_tj	|tj
tj
tj
| j|d}ntj	|tj
tj
tj
| jd}| j sE| j rN| jrN| j d}n| j r]| jj d}nd }|j|d\}}|pl|pld}|jddd}|j}| || d	|vrtj| |s|S z/tj|dd
}	|	d}
|
dkrtdd| 	 W d    W dS 1 sw   Y  W d S  ttfy } ztdd||f d }~ww )Nwin32)stdinstdoutrE   envstartupinfo)rJ   rK   rE   rL   r   )input    replace)errorsr1   encoding   r2   zBCommand failed: %s
Check whhtmltopdf output without 'quiet' option TzFCommand failed: %s
Check whhtmltopdf output without 'quiet' option
%s )r<   sysplatform
subprocessSTARTUPINFOdwFlagsSTARTF_USESHOWWINDOWSW_HIDEwShowWindowPopenPIPEr   r   r   isFiler#   r7   encoder5   readcommunicater   
returncoderH   rK   writecodecsopenrB   joinOSError)r
   r8   argsrM   resultrN   rK   rE   rD   ftexter   r   r   to_pdf   sb   

	

(zPDFKit.to_pdfc                 c   s    t | D ];\}}d|vrd| | }n| |}t|t tfr.|D ]}||fV  q%qt|tr5dn|}||r>t|n|fV  qdS )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--%sr2   N)r*   items_normalize_argr)   r+   boolunicode)r
   r   keyvaluenormalized_keyr/   normalized_valuer   r   r   r(      s   
zPDFKit._normalize_optionsc                 C   s   |  S r   )lower)r
   argr   r   r   rq         zPDFKit._normalize_argc                 C   s   d| S )Nz<style>%s</style>r   )r
   
stylesheetr   r   r   _style_tag_for   rz   zPDFKit._style_tag_forc              	   C   sJ  | j  st| j j tr| dt|ts|g}g }|D ] }tj|dd}||  W d    n1 s8w   Y  qd	|}| j 
 rwtj| j  dd}| }W d    n1 saw   Y  t|d| |d d| _ d S | j  rd| j  v r| j  d| |d | j _ d S | || j   | j _ d S d S )Nz6CSS files can be added only to a single file or stringzUTF-8rR   
z</head>string)r   isUrlr)   r*   r   rf   rg   appendrb   rh   r`   r7   r   rP   r|   r   )r
   r8   css_dataprl   inpr   r   r   r4      s4   







zPDFKit._prepend_cssc                 C   sz   t |tjs|jjdkr| }i }td|D ]"}td| j	j
 |r:td| j	j
 |d }td|d ||< q|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=["']([^"']*))r)   ioIOBase	__class__r   rb   refindallsearchr   meta_tag_prefix)r
   contentfoundxnamer   r   r   r     s    zPDFKit._find_options_in_meta)NNNNNFFr   )r   r   r   r   	Exceptionr   r   r0   r;   r<   staticmethodrH   ro   r(   rq   r|   r4   r   r   r   r   r   r      s"    	


0

Ar   )r   rX   rV   collectionsr   r   r   r   r   r   rf   r6   rs   	NameErrorstrobjectr   r   r   r   r   <module>   s    