U
    7h!+                     @   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k
rt   eZeZY nX 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   G/var/www/formularioweb/env/lib/python3.8/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 krt n|| _z| jjd| _W n tk
rR   | jj| _Y nX t | _| j	 rx| j
| | | jj| _|d k	r| j
| |d kri 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cssZstylesheets)
r
   Zurl_or_filetype_r   r   r    r#   r   r!   r"   r   r   r   r   )   s(    

zPDFKit.__init__c                 c   sl   |  |D ]\\}}|V  t|ttfr`t|dkrB|d rB|d sJt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AssertionError)r
   optsZoptkeyoptvalr   r   r   _genargsD   s    $
zPDFKit._genargsc                 c   s  | j r| | j  | jV  | js0| jddi | | jD ]}|r<|V  q<| jrf| jrfdV  | jV  | j	rdV  | | j	D ]}|r~|V  q~| jr| jsdV  | jV  | j
 s| j
 rdV  n0t| j
j
tr| j
 V  n| j
j
D ]
}|V  q|r|V  ndV  dS )z0
        Generator of all command parts
        --quiet r    r   -N)r#   _prepend_cssr   r"   r   r   r.   r    r!   r   r   r   	isFileObjr'   
basestringto_s)r
   pathZargpartsr   r   r   _commandT   s8    zPDFKit._commandc                 C   s   t | |S r   )r(   r8   )r
   r6   r   r   r   command   s    zPDFKit.commandc                 C   s|   | dkrd S |  }t|dkr8|  d  dkr8d S d|krLtd| d|kr`td| |pfd	}td
| |d S )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stderrZstderr_lines	error_msgr   r   r   handle_error   s     zPDFKit.handle_errorc              
   C   s  |  |}tjdkrTt }| 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 s| j r| jr| j d}n"| j r| jj d}nd }|j|d\}}|p|pd}|jddd}|j}| || d	|krtj| |s|S zPtj|dd
8}	|	d}
|
dkrRtdd| W 5 Q R  W dS Q R X W n> ttfk
r } ztdd||f W 5 d }~X Y nX d S )Nwin32)stdinstdoutrB   envstartupinfo)rF   rG   rB   rH   r   )input    replace)errorsr/   encoding   r0   zBCommand failed: %s
Check whhtmltopdf output without 'quiet' option TzFCommand failed: %s
Check whhtmltopdf output without 'quiet' option
%s )r9   sysplatform
subprocessZSTARTUPINFOZdwFlagsZSTARTF_USESHOWWINDOWZSW_HIDEZwShowWindowPopenPIPEr   r   r   isFiler#   r5   encoder3   readcommunicater   
returncoderD   rG   writecodecsopenr?   joinOSError)r
   r6   argsrI   resultrJ   rG   rB   rA   ftexter   r   r   to_pdf   s\    

	



zPDFKit.to_pdfc                 c   s   t | D ]v\}}d|kr,d| | }n
| |}t|t tfrZ|D ]}||fV  qHqt|trhdn|}||rzt|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--%sr0   N)r(   items_normalize_argr'   r)   boolunicode)r
   r   keyvalueZnormalized_keyr-   Znormalized_valuer   r   r   r&      s    
zPDFKit._normalize_optionsc                 C   s   |  S r   )lower)r
   argr   r   r   rh      s    zPDFKit._normalize_argc                 C   s   d| S )Nz<style>%s</style>r   )r
   
stylesheetr   r   r   _style_tag_for   s    zPDFKit._style_tag_forc              
   C   s  | j  st| j j tr"| dt|ts2|g}g }|D ],}tj|dd}||  W 5 Q R X q:d	|}| j 
 rtj| j  dd}| }W 5 Q R X t|d| |d d| _ nV| j  rd| j  kr| j  d| |d | j _ n| || j   | j _ d S )Nz6CSS files can be added only to a single file or stringzUTF-8rN   
z</head>string)r   ZisUrlr'   r(   r   r]   r^   appendrY   r_   rW   r5   r   rL   rp   r   )r
   r6   Zcss_dataprc   Zinpr   r   r   r2      s.    




 
zPDFKit._prepend_cssc                 C   sz   t |tjs|jjdkr | }i }td|D ]D}td| j	j
 |r0td| j	j
 |d }td|d ||< q0|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   rY   refindallsearchr   Zmeta_tag_prefix)r
   contentfoundxnamer   r   r   r     s     
zPDFKit._find_options_in_meta)NNNNNFF)N)N)N)r   r   r   r   	Exceptionr   r   r.   r8   r9   staticmethodrD   rf   r&   rh   rp   r2   r   r   r   r   r   r      s&   	        

0


Ar   )ry   rT   rR   collectionsr   r   r   r   r   rv   r]   r4   rj   	NameErrorstrobjectr   r   r   r   r   <module>   s   
