U
    üßŽi!+  ã                   @   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   úK/var/www/html/IITS/school/venv/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r¢i 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	rŽdV  |  | j	¡D ]}|r~|V  q~| jr¨| js¨dV  | jV  | j
 ¡ s¼| j
 ¡ rÄd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   éþÿÿÿZ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Ø|pØd}|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ÚstdoutrA   ÚenvÚstartupinfo)rE   rF   rA   rG   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   Ú
returncoderC   rF   ÚwriteÚcodecsÚopenr>   ÚjoinÚOSError)r
   r6   ÚargsrH   ÚresultrI   rF   rA   r@   Ú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   rg   ú   s    zPDFKit._normalize_argc                 C   s   d| S )Nz<style>%s</style>r   )r
   Z
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  
¡ rÄt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-8rM   Ú
z</head>Ústring)r   ZisUrlr'   r(   r   r\   r]   ÚappendrX   r^   rV   r5   r   rK   rn   r   )r
   r6   Zcss_dataÚprb   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 )zÊReads '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   rX   Ú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   ÚstaticmethodrC   re   r&   rg   rn   r2   r   r   r   r   r   r      s&   	        ÿ

0


Ar   )rw   rS   rQ   Úcollectionsr   r   r   r   r   rt   r\   r4   ri   Ú	NameErrorÚstrÚobjectr   r   r   r   r   Ú<module>   s   
