B
    ]t\z             '   @   s"  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 ddlZddl	m
Z
mZmZmZmZ ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlmZmZmZ ddlmZ dd	lm Z m!Z!m"Z"m#Z#m$Z$ dd
l%m&Z& ddl'm(Z(m)Z)m*Z* ddl+m,Z, ddl-m.Z.m/Z/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8m9Z9m:Z:m;Z;m<Z< ddl=m>Z> ddl?m@Z@mAZA ddlBmCZC ddlDmEZE ddlmFZF ddlmGZG ddlmHZH eIeJZKd_ddZLeMdZNdd ZOdd ZPG dd  d eQZReG d!d" d"eQZSG d#d$ d$eQZTG d%d& d&eQZUeVd'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdL%ZWejXf dMdN eWY D ZZdOdP Z[e[eZ_\G dQdR dReQZ]G dSdT dTeQZ^G dUdV dVe$Z_G dWdX dXe#Z`G dYdZ dZeQZaG d[d\ d\e!Zbe"Zce jdG d]d^ d^e ZedS )`uA   
A PDF matplotlib backend
Author: Jouni K Seppänen <jks@iki.fi>
    N)datetime)total_ordering)BytesIO)ceilcosfloorpisin)cbook__version__rcParams)Gcf)_BackendFigureCanvasBaseFigureManagerBaseGraphicsContextBaseRendererBase)MixedModeRenderer)get_realpath_and_statis_writable_file_likemaxdict)Figure)findfontis_opentype_cff_fontget_font)AFM)FIXED_WIDTHITALICLOAD_NO_SCALELOAD_NO_HINTINGKERNING_UNFITTED)MathTextParser)Affine2DBboxBase)Path)UTC)_path)_png)ttconvK   c             C   s   d}d}g }xVt | D ]J\}}t|}|| |k r@||d 7 }q|d| ||  |}|}qW |d| |d  d|S )zMake one string from sequence of strings, with whitespace
    in between. The whitespace is chosen to form lines of at most
    linelen characters, if possible.r          N   
)	enumeratelenappendjoin)ZstringsZlinelenZcurrposZlastiresultislength r5   >lib/python3.7/site-packages/matplotlib/backends/backend_pdf.pyfilla   s    r7   s   ([\\()\r\n])c             C   s>   |  d}|dkrd| S |dkr&dS |dkr2dS ds:td S )	Nr   s   \()   \r,   s   \n   s   \rF)groupAssertionError)matchmr5   r5   r6   _string_escape|   s    
r>   c                sD  t  dr  S t ttjfrLt s4tdd  }|ddS t t	rbddg  S t t
tjfrzd  S t try d	}t|S  tk
r   tj d
 }t|S X n|t trdtt  d S t tr"dg}| fddt D  |d t|S t ttfr^dg}|dd  D  |d t|S  dkrldS t tr d}  }|dk	r|j}nt j!rt j"}nt j#}|dkr|d7 }n@|dk r|d| d | d f 7 }n|d|d |d f 7 }t|S t t$r.tdd  j%D S t&d't( dS )z!Map Python objects to PDF syntax.pdfReprz%Can only output finite numbers in PDFs   %.10f   0   .s   falses   trues   %dASCIIzUTF-16BE   (   )s   <<c                s(   g | ] }t | d  t |  qS )r+   )Namer?   ).0key)objr5   r6   
<listcomp>   s   zpdfRepr.<locals>.<listcomp>s   >>   [c             S   s   g | ]}t |qS r5   )r?   )rF   valr5   r5   r6   rI      s       ]Ns   nullzD:%Y%m%d%H%M%Sr   Zz+%02d'%02d'i  z-%02d'%02d'c             S   s   g | ]}t |qS r5   )r?   )rF   rK   r5   r5   r6   rI      s    z.Don't know a PDF representation for {} objects))hasattrr?   
isinstancefloatnpZfloatingisfinite
ValueErrorrstripboolintZintegerstrencodeUnicodeEncodeErrorcodecsBOM_UTF16_BEbytes_string_escape_regexsubr>   dictextendsortedr/   r7   listtupler   ZstrftimeZ	utcoffsetZsecondstimeZdaylightZaltzoneZtimezoner#   Zbounds	TypeErrorformattype)rH   rr3   zr5   )rH   r6   r?      sf    













r?   c               @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )	ReferencezPPDF reference object.
    Use PdfFile.reserveObject() to create References.
    c             C   s
   || _ d S )N)id)selfrk   r5   r5   r6   __init__   s    zReference.__init__c             C   s
   d| j  S )Nz<Reference %d>)rk   )rl   r5   r5   r6   __repr__   s    zReference.__repr__c             C   s
   d| j  S )Ns   %d 0 R)rk   )rl   r5   r5   r6   r?      s    zReference.pdfReprc             C   s,   |j }|d| j  |t| |d d S )Ns	   %d 0 obj
s   
endobj
)writerk   r?   )rl   contentsfilero   r5   r5   r6   ro      s    zReference.writeN)__name__
__module____qualname____doc__rm   rn   r?   ro   r5   r5   r5   r6   rj      s
   rj   c               @   sb   e Zd ZdZdZedZdd Zdd Z	dd	 Z
d
d Zdd Zdd Zedd Zdd ZdS )rE   zPDF name object.)namez[^!-~]c             C   sD   t |tr|j| _n,t |tr(|d}| jtj|d| _d S )Nascii)	rO   rE   rv   r\   decode_regexr^   hexifyrX   )rl   rv   r5   r5   r6   rm      s
    



zName.__init__c             C   s
   d| j  S )Nz	<Name %s>)rv   )rl   r5   r5   r6   rn     s    zName.__repr__c             C   s   dt | j S )N/)rW   rv   )rl   r5   r5   r6   __str__	  s    zName.__str__c             C   s   t |to| j|jkS )N)rO   rE   rv   )rl   otherr5   r5   r6   __eq__  s    zName.__eq__c             C   s   t |to| j|jk S )N)rO   rE   rv   )rl   r}   r5   r5   r6   __lt__  s    zName.__lt__c             C   s
   t | jS )N)hashrv   )rl   r5   r5   r6   __hash__  s    zName.__hash__c             C   s   dt |   S )Nz#%02x)ordr:   )r<   r5   r5   r6   rz     s    zName.hexifyc             C   s
   d| j  S )N   /)rv   )rl   r5   r5   r6   r?     s    zName.pdfReprN)rr   rs   rt   ru   	__slots__recompilery   rm   rn   r|   r~   r   r   staticmethodrz   r?   r5   r5   r5   r6   rE      s   
rE   c               @   s,   e Zd ZdZdZdd Zdd Zdd Zd	S )
OperatorzPDF operator object.)opc             C   s
   || _ d S )N)r   )rl   r   r5   r5   r6   rm   !  s    zOperator.__init__c             C   s
   d| j  S )Nz<Operator %s>)r   )rl   r5   r5   r6   rn   $  s    zOperator.__repr__c             C   s   | j S )N)r   )rl   r5   r5   r6   r?   '  s    zOperator.pdfReprN)rr   rs   rt   ru   r   rm   rn   r?   r5   r5   r5   r6   r     s
   r   c               @   s    e Zd ZdZdd Zdd ZdS )VerbatimzIStore verbatim PDF command content for later inclusion in the
    stream.c             C   s
   || _ d S )N)_x)rl   xr5   r5   r6   rm   .  s    zVerbatim.__init__c             C   s   | j S )N)r   )rl   r5   r5   r6   r?   1  s    zVerbatim.pdfReprN)rr   rs   rt   ru   rm   r?   r5   r5   r5   r6   r   +  s   r      b   B   f   h   s   S   ns   BTs   ET   cs   re   l   ms   cms   Do   G   gs   RGs   rgs   CSs   css   SCNs   scn   d   j   Js   gs   q   Qs   Tds   Tfs   Tms   Tjs   TJ   w   Ws   sh)%Zclose_fill_strokefill_stroker7   	closepathZclose_strokestrokeendpath
begin_textend_textcurveto	rectanglelinetomovetoconcat_matrixuse_xobjectsetgray_strokesetgray_nonstrokesetrgb_strokesetrgb_nonstrokeZsetcolorspace_strokesetcolorspace_nonstrokeZsetcolor_strokesetcolor_nonstrokesetdashsetlinejoin
setlinecap	setgstategsavegrestoretextpos
selectfont
textmatrixshowshowkernsetlinewidthclipshadingc             C   s   i | ]\}}t ||qS r5   )r   )rF   rv   valuer5   r5   r6   
<dictcomp>B  s   r   c             C   s*   |r| rt jS t jS n| r t jS t jS dS )zReturn the PDF operator to paint a path in the following way:
    fill:   fill the path with the fill color
    stroke: stroke the outline of the path with the line colorN)Opr   r   r7   r   )r7   r   r5   r5   r6   _paint_pathF  s    r   c               @   s>   e Zd ZdZdZdddZdd Zdd	 Zd
d Zdd Z	dS )StreamzPDF stream object.

    This has no pdfRepr method. Instead, call begin(), then output the
    contents of the stream by calling write(), and finally call end().
    )rk   r.   pdfFilerq   compressobjextraposNc             C   s   || _ || _|| _|j| _d| _|dkr2t | _n
| | _|dk	rZ| j	t
d|d | j| j  td r|sttd | _| jdkrt | _n|   | j | _dS )a9  id: object id of stream; len: an unused Reference object for the
        length of the stream, or None (to use a memory buffer); file:
        a PdfFile; extra: a dictionary of extra key-value pairs to
        include in the stream header; png: if the data is already
        png compressed, the decode parametersNFlateDecode)FilterZDecodeParmszpdf.compression)rk   r.   r   fhrq   r   r_   r   copyupdaterE   
recordXrefr   zlibr   _writeHeadertellr   )rl   rk   r.   rq   r   pngr5   r5   r6   rm   _  s$    




zStream.__init__c             C   sR   | j j}|d| j  | j}| j|d< td r:td|d< |t| |d d S )Ns	   %d 0 obj
Lengthzpdf.compressionr   r   s   
stream
)rq   ro   rk   r   r.   r   rE   r?   )rl   ro   r_   r5   r5   r6   r   {  s    
zStream._writeHeaderc             C   s   |    | jdkrR| j }t|| _| jj| _|   | j| | jd n,| j | j	 }| jd | j
| j| dS )zFinalize stream.Ns   
endstream
endobj
)_flushr.   rq   getvaluer   r   r   ro   r   r   writeObject)rl   rp   r4   r5   r5   r6   end  s    



z
Stream.endc             C   s4   | j dkr| j| n| j |}| j| dS )zWrite some data on the stream.N)r   rq   ro   compress)rl   data
compressedr5   r5   r6   ro     s    
zStream.writec             C   s*   | j dk	r&| j  }| j| d| _ dS )zFlush the compression object.N)r   flushrq   ro   )rl   r   r5   r5   r6   r     s    

zStream._flush)NN)
rr   rs   rt   ru   r   rm   r   r   ro   r   r5   r5   r5   r6   r   W  s   
	r   c               @   s~  e Zd ZdZdYddZdd Zddddgfd	d
Zdd Zdd Zdd Z	dd Z
dZddZdd Zdd Zeeddd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 Zd7d8 Z d9d: Z!d[d;d<Z"d=d> Z#d?d@ Z$dAdB Z%dCdD Z&dEdF Z'e(d\dGdHZ)d]dJdKZ*d^dMdNZ+dOdP Z,dQdR Z-dSdT Z.dUdV Z/dWdX Z0dS )_PdfFilezPDF file object.Nc       
      C   sZ  d| _ dddgg| _d| _d | _d| _tj|ddd\}}|sxy| | _W n  tk
rl   t	 }|| _Y nX |}d| _t
jtd	 d
d| _|| _d | _|d |d | d| _| d| _g | _| d
| _| d| _| d| _| d| _| d| _| d| _td| jd}| | j| t
d}|r^t t!|}|j"t#d}nt$ }dt% dt% |d| _&|d k	r| j&'| dd | j&( D | _&i | _)d| _*i | _+d | _,i | _-i | _.i | _/d| _0t12 | _3d| _4g | _5t12 | _6d| _7t12 | _8i | _9g | _:g | _;dd d < D }| j| j| j| j| j|d!}	| | j|	 d S )"Nr*   r   i  zthe zero objectFwbT)Zreturn_openedZdatapathfontsZpdfcorefontss	   %PDF-1.4
s   % 
rootZpageszextended graphics statesztiling patternszGouraud triangleszexternal objects	resourcesZCatalog)TypePagesSOURCE_DATE_EPOCH)Ztzinfoz$matplotlib %s, http://matplotlib.orgzmatplotlib pdf backend %s)CreatorProducerCreationDatec             S   s   i | ]\}}|d k	r||qS )Nr5   )rF   kvr5   r5   r6   r     s    z$PdfFile.__init__.<locals>.<dictcomp>c             S   s   g | ]}t |qS r5   )rE   )rF   r   r5   r5   r6   rI     s   z$PdfFile.__init__.<locals>.<listcomp>zPDF Text ImageB ImageC ImageI)FontXObject	ExtGStatePatternZShadingZProcSet)=
nextObject	xrefTablepassed_in_file_objectoriginal_file_like	tell_baser
   Zto_filehandler   IOErrorr   ospathr0   r   _core14fontdirr   currentstreamro   reserveObject
rootObjectpagesObjectpageList
fontObjectalphaStateObjecthatchObjectgouraudObjectXObjectObjectresourceObjectrE   r   getenvr   ZutcfromtimestamprV   replacer%   Ztodayr   infoDictr   items	fontNamesnextFontdviFontInfoZ_texFontMaptype1Descriptorsused_charactersalphaStatesnextAlphaStatecollectionsOrderedDicthatchPatterns	nextHatchgouraudTriangles_images	nextImagemarkersmulti_byte_charprocspathspageAnnotationssplit)
rl   filenamemetadatar   Zopenedr   Zsource_date_epochZsource_dateZprocsetsr   r5   r5   r6   rm     s    








zPdfFile.__init__c          	   C   s   |    || | _| _| d}td| j| jddd| d| g|tdtdtdd| jd	}| d
}| || | j	
| | |j| d | tjd tj g | _d S )Nzpage contentsZPager   H   GroupZTransparency	DeviceRGB)r   SZCS)r   ZParent	ResourcesZMediaBoxContentsr  ZAnnotspagezlength of content streamround)	endStreamwidthheightr   rE   r   r   r  r   r   r/   beginStreamrk   outputGraphicsContextPdf
joinstylesr   r   )rl   r#  r$  ZcontentObjectZthePageZ
pageObjectr5   r5   r6   newPage  s&    



zPdfFile.newPageir   c             C   s<   t dt d||d}| d}| || | j| d S )NZAnnotZText)r   Subtyper  ZRectZ
annotation)rE   r   r   r  r/   )rl   textpositionRectZtheNoteZannotObjectr5   r5   r6   newTextnote,  s    
zPdfFile.newTextnotec          
   C   s$  |    |   | | jdd | j D  |   |   dd | j D }x"| j	 D ]}|d ||d < q^W x| j
 D ]\}}|||< qW x(| jD ]\	}}}}}}	}
}}|||< qW | | j| |   |   |   | | jtd| jt| jd |   |   |   dS )	z>Write out the various deferred objects and the pdf end matter.c             S   s   i | ]}|d  |d qS )r*   r   r5   )rF   rK   r5   r5   r6   r   >  s    z$PdfFile.finalize.<locals>.<dictcomp>c             S   s   i | ]\}}}||qS r5   r5   )rF   imagerv   obr5   r5   r6   r   A  s   r*   r   r   )r   ZKidsZCountN)r"  
writeFontsr   r   r
  valueswriteHatcheswriteGouraudTrianglesr  r  r  r  r  r   writeImageswriteMarkerswritePathCollectionTemplatesr   rE   r   r.   writeInfoDict	writeXrefwriteTrailer)rl   Zxobjectstuprv   r   r   transr/  r0   Zcappaddingfilledstrokedr5   r5   r6   finalize7  s6    zPdfFile.finalizec             C   sD   |    | jr| j  n&| jdk	r6| j| j  | j  dS )z)Flush all buffers and free all resources.N)r"  r   r   r   r   ro   r   close)rl   r5   r5   r6   r@  X  s    
zPdfFile.closec             C   s(   | j d kr| j| n| j | d S )N)r   r   ro   )rl   r   r5   r5   r6   ro   c  s    
zPdfFile.writec             G   s&   |  tdd |D  |  d d S )Nc             S   s   g | ]}t |qS r5   )r?   )rF   r   r5   r5   r6   rI   j  s    z"PdfFile.output.<locals>.<listcomp>r,   )ro   r7   )rl   r   r5   r5   r6   r&  i  s    zPdfFile.outputc             C   s$   | j d kstt||| ||| _ d S )N)r   r;   r   )rl   rk   r.   r   r   r5   r5   r6   r%  m  s    zPdfFile.beginStreamc             C   s   | j d k	r| j   d | _ d S )N)r   r   )rl   r5   r5   r6   r"  q  s    

zPdfFile.endStreamc             C   s   t |tr|}n:td rBt|d| jd}|dkrJtdd| jd}nt|}| j|}|dkrtd| j }|| j|< |  jd7  _t	
d|| |S )	z
        Select a font based on fontprop and return a name suitable for
        Op.selectfont. If fontprop is a string, it will be interpreted
        as the filename of the font.
        zpdf.use14corefontsafm)fontext	directoryN	HelveticazF%dr*   zAssigning font %s = %r)rO   rW   r   r   r   r  getrE   r  _logdebug)rl   Zfontpropr  Fxr5   r5   r6   fontNamev  s     

zPdfFile.fontNamez3.0c             C   s   t t dS )Nz
pdftex.map)dviread
PsfontsMapfind_tex_file)rl   r5   r5   r6   
texFontMap  s    zPdfFile.texFontMapc             C   s   | j |j}|dk	r|jS ttd}||j }|jdkrTtd	|j
|jtd| j }|  jd7  _td||j tj|||j|j
|j|jd| j |j< |S )z
        Given a dvi font object, return a name suitable for Op.selectfont.
        This registers the font information in self.dviFontInfo if not yet
        registered.
        Nz
pdftex.mapzNNo usable font file found for {} (TeX: {}); the font may lack a Type-1 versionzF%dr*   zAssigning font %s = %s (dvi))dvifontpdfnamefontfilebasefontencodingfileeffects)r  rE  texnamerO  rJ  rK  rL  r  rS   rf   ZpsnamerE   r  rF  rG  typesSimpleNamespaceencodingrS  )rl   rN  Zdvi_infoZtex_font_mapZpsfontrO  r5   r5   r6   dviFontName  s(    

zPdfFile.dviFontNamec       	      C   s   i }x:t | j D ](\}}|j}td| | |||< qW xt | jD ]}| j| }td| |drtd | 	|||< qLtd t
|\}}| j|}|d k	rLt|d rL| ||d ||< qLW | | j| d S )Nz"Embedding Type-1 font %s from dvi.zEmbedding font %s.z.afmzWriting AFM font.zWriting TrueType font.r*   )ra   r  r  rO  rF  rG  _embedTeXFontr  endswith_write_afm_fontr   r	  rE  r.   embedTTFr   r   )	rl   r   ZdvinameinforH  r  realpathstat_keycharsr5   r5   r6   r0    s"    



zPdfFile.writeFontsc          	   C   s^   t |d}t|}W d Q R X | }tdtdt|tdd}| d}| || |S )Nrbr   Type1ZWinAnsiEncoding)r   r*  BaseFontEncodingzfont dictionary)openr   Zget_fontnamerE   r   r   )rl   r  r   fontfontnamefontdictfontdictObjectr5   r5   r6   r[    s    
zPdfFile._write_afm_fontc       
      C   sp  t d|jj|j | d}| ||jj | d}tdtddt	|jjd |d}|j
d k	rt|j
}d	d
 |D }dg| }td|d|d< |jd krt d|j t|j|d< | || |S t|j}|jr||j}t|jd |d< |jdd|jddf}| j|j|f}	|	d krX| ||j}	|	| j|j|f< |	|d< | || |S )Nz#Embedding TeX font %s - fontinfo=%szfont widthszfont dictionaryr   rb  r   r*   )r   r*  	FirstCharLastCharWidthsc             S   s   g | ]}t |qS r5   )rE   )rF   Zchr5   r5   r6   rI     s    z)PdfFile._embedTeXFont.<locals>.<listcomp>rd  )r   DifferenceszBecause of TeX configuration (pdftex.map, see updmap option pdftexDownloadBase14) the font %s is not embedded. This is deprecated as of PDF 1.5 and it may cause the consumer application to show something that was not intended.rc  FontNameZslantg        r`   g      ?FontDescriptor)rF  rG  rN  rT  __dict__r   r   widthsrE   r.   rR  rJ  rd  rP  warningrQ  	type1fontZ	Type1FontrS  	transformproprE  r  createType1Descriptor)
rl   ZfontinfowidthsObjectri  rh  encdifferencesArrayt1fontrS  Zfontdescr5   r5   r6   rY    sH    





zPdfFile._embedTeXFontc       
      C   s   |  d}|  d}|jd }|jd }d}|r8|dO }|dO }|rL|dO }t|}td	t|jd
 ||j||j|jdd||jd dd}	| ||	 | |j	d t
|jd t
|jd dd | j|jd  | j|jd  |   |S )Nzfont descriptorz	font fileItalicAngleZisFixedPitchr   r*      @   ro  rn  i  i  Z
FamilyName2   )r   rn  FlagsFontBBoxr{  AscentDescent	CapHeightXHeightZFontFileZ
FontFamilyStemV)Length1ZLength2ZLength3)r   ru  r   rE   bboxascender	descenderr   r%  rk   r.   partsr   ro   r"  )
rl   rz  rP  fontdescObjectfontfileObjectZitalic_angleZfixed_pitchflagsZft2font
descriptorr5   r5   r6   rv    s@    





zPdfFile.createType1Descriptorc             C   s    dt jt j|d |f S )Nz%s-%sr   )r   r   splitextbasename)rl   r  symbol_namer5   r5   r6   _get_xobject_symbol_nameV  s    z PdfFile._get_xobject_symbol_namesO  /CIDInit /ProcSet findresource begin
12 dict begin
begincmap
/CIDSystemInfo
<< /Registry (Adobe)
   /Ordering (UCS)
   /Supplement 0
>> def
/CMapName /Adobe-Identity-UCS def
/CMapType 2 def
1 begincodespacerange
<0000> <ffff>
endcodespacerange
%d beginbfrange
%s
endbfrange
endcmap
CMapName currentdict /CMap defineresource pop
end
endc                sz  t }td }|jdfdd  fdd} fdd}|jd	d
t|dplddd}|dp~ddi}|j}	|j}
d}d}|	t	@ r|dO }|r|dO }n|dO }|
t
@ r|dO }td| fdd|jD  |jdd |jdd |d dd |d |d d dd
}trJd}tdtj |dkr`||||S |dkrv||||S d S )!z9Embed the TTF font from the named file into the document.zpdf.fonttypeTc             S   s6   | | d }|rt |S |dk r*t|S t|S dS )z1Convert font coordinates to PDF glyph coordinatesi  r   N)rQ   r!  r   r   )r4   Zupenearestr   r5   r5   r6   cvtv  s    
zPdfFile.embedTTF.<locals>.cvtc                s   d} d} d} d}g }d\}}	fddjD }
td||	|td	|d
 |
ddddddg|td|d|d}ddlm  t dr fddn fddfddfddt||	d D }t||d< g }g }t }xT|D ]L}|}	|}|
| |}|dkrD|
||f n
|| qW |  d}x<|D ]4\}}||d kr|
| |
t| |}qfW tt|}i }xt|D ]}|| }dt|i}||krtd|d< td|d < |
|d!< ||d"d# d$ } d%}|jd$| j|   ||krf|}|j|< n|||< qW || || || || |S )&z5The Type 3-specific part of embedding a Truetype fontzfont widthszfont descriptorzfont dictionaryzcharacter procs)r      c                s   g | ]} |d dqS )F)r  r5   )rF   r   )r  r5   r6   rI     s    z;PdfFile.embedTTF.<locals>.embedTTFType3.<locals>.<listcomp>r   ZType3rn  gMbP?r   rd  )r   rm  )r   rc  rj  rk  ro  r*  rE   r  Z
FontMatrixZ	CharProcsrd  rl  )cp1252decoding_mapc                s    j |  pdS )Nr   )r  )charcode)r  r5   r6   decode_char  s    z<PdfFile.embedTTF.<locals>.embedTTFType3.<locals>.decode_charc                s   t  j|  S )N)r   Zdecoding_table)r  )r  r5   r6   r    s    c                s$   | }j |ttB dj} |S )N)r  )	load_charr   r   horiAdvance)r  r3   r#  )r  r  rf  r5   r6   get_char_width  s    z?PdfFile.embedTTF.<locals>.embedTTFType3.<locals>.get_char_widthc                s   g | ]} |qS r5   r5   )rF   r  )r  r5   r6   rI     s   r*   MaxWidthr  r   r   r   Formr*  BBoxs   d1   NZcharProc)r   r  rE   Z	encodingsr  rN   rangemaxsetget_char_indexr/   get_glyph_nameaddsortr(   Zget_pdf_charprocsr   fsencodera   r.   findr%  rk   r   ro   r"  r  r  r   )rf  
charactersr  rw  r  ri  ZcharprocsObjectry  Z	firstcharZlastcharr  rh  rq  Z	glyph_idsZdifferencesZmulti_byte_charscccodegind
glyph_nameZlast_crv   ZrawcharprocsZ	charprocsZcharnamestreamZcharprocDictZcharprocObject)r  r  ps_namerl   )r  r  rf  r  r6   embedTTFType3  s    















z'PdfFile.embedTTF.<locals>.embedTTFType3c                 s   d} d} d} d} d} d} d}	tdtd	d
ddd|||d}
tdtdtd|g|	d}||d<  d}|j dd|i td8}d}x,|d}|sP |t|7 }j| qW W dQ R X 	  
|| dgd }g }d}xb|D ]Z}|}| |}| j|ttB d}|| |jf |dk rxt|||< t||}q*W |  |d|d  }d}g }d}g }xn|D ]f\}}||d kr|| ||g |||g n|d | ||d d< t||}|}qW g }x@|D ]8\}}|d||d d!d" t||d D f  q*W jt|d#|f }d$|d%}|jdd&t|i j| 	  |	jdd&|i j| 	  ||d'< 
||
 
|| 
|| 
|| |S )(z6The Type 42-specific part of embedding a Truetype fontzfont descriptorzCID font dictionaryzType 0 font dictionaryzCIDToGIDMap streamzfont file streamzType 0 widthszToUnicode mapr   ZCIDFontType2ZAdobeZIdentityr   )ZRegistryZOrderingZ
Supplement)r   r*  rc  ZCIDSystemInforo  WZCIDToGIDMapZType0z
Identity-H)r   r*  rc  rd  ZDescendantFontsZ	ToUnicodeZ	FontFile2zdecoded length of a fontzlength of font streamr  ra  i   N i   )r  r*   r  s   <%04x> <%04x> [%s]r+   c             s   s   | ]}d | V  qdS )s   <%04x>Nr5   )rF   r   r5   r5   r6   	<genexpr>K  s    z;PdfFile.embedTTF.<locals>.embedTTFType42.<locals>.<genexpr>r,    zutf-16ber   r  )r   rE   r%  rk   re  readr.   r   ro   r"  r   r  r  r   r   r/   r  chrr  r  r0   r  _identityToUnicodeCMaprX   ) rf  r  r  r  ZcidFontDictObjectZtype0FontDictObjectZcidToGidMapObjectr  ZwObjectZtoUnicodeMapObjectZcidFontDictZtype0FontDictZlength1ObjectrP  Zlength1r   Zcid_to_gid_maprq  Z	max_ccoder  r  r  glyphZ
last_ccodewZ	max_widthZunicode_groupsr#  Zunicode_bfrangestartr   Zunicode_cmap)r  r  r  rl   r5   r6   embedTTFType42  s    
















*
z(PdfFile.embedTTF.<locals>.embedTTFType42rw   r  pcltr   )	capHeightxHeightpostZitalicAngle)r   r   Fr*   r|      r}  ro  c                s   g | ]} |d dqS )F)r  r5   )rF   r   )r  r5   r6   rI     s    z$PdfFile.embedTTF.<locals>.<listcomp>)r  r  r  )
r   rn  r  r  r  r  r  r  r{  r  *   z[%r can not be subsetted into a Type 3 font. The entire font will be embedded in the output.   N)r   r   Zunits_per_EMZpostscript_namerX   rE   Zget_sfnt_tableZ
face_flagsZstyle_flagsr   r   r  r  r  r   rF  rr  r   r   r  )rl   r  r  rf  fonttyper  r  r  r  ZffZsfr  Zsymbolicr  r5   )r  r  r  rl   r6   r\  p  sL    rv
	




zPdfFile.embedTTFc             C   s`   | j |d}|dk	r|d S td| j }|  jd7  _|td|d |d df| j |< |S )z?Return name of an ExtGState that sets alpha to the given value.Nr   zA%dr*   r   )r   ZCAZca)r
  rE  rE   r  )rl   alphastaterv   r5   r5   r6   
alphaState  s    zPdfFile.alphaStatec             C   s   |d k	r<|\}}}|d k	r"t |}|d k	r2t |}|||f}| j|d }|d k	rV|S td| j }|  jd7  _|| j|< |S )NzH%dr*   )rc   r  rE  rE   r  )rl   hatch_styleZedgeZfacehatchpatternrv   r5   r5   r6   hatchPattern  s    


zPdfFile.hatchPatternc       
      C   sJ  t  }d}x*| j D ]\}}| d}|||< ddd d D i}| |jd tddddd	d	||g|||dd	d	dd	| jd
 gd	 |\}}}	| 	|d	 |d |d t
j |d k	r| 	|d	 |d |d t
jd	d	||t
jt
j
 | 	td t
j | j	| jt|	t |dd  | 	t
j |   qW | | j| d S )Ng      R@zhatch patternZProcsetsc             S   s   g | ]}t |qS r5   )rE   )rF   r   r5   r5   r6   rI     s    z(PdfFile.writeHatches.<locals>.<listcomp>zPDF Text ImageB ImageC ImageIr   r*   r   r  )	r   ZPatternTypeZ	PaintTypeZ
TilingTyper  ZXStepZYStepr  ZMatrixr  zhatch.linewidthF)simplify)r_   r  r  r   r  r%  rk   rE   r$  r&  r   r   r   r   r7   r   r   pathOperationsr$   r  r"   scaler   r"  r   r   )
rl   Z	hatchDictZsidelenr  rv   r/  ZresZ
stroke_rgbZfill_rgbr   r5   r5   r6   r2    s>    




zPdfFile.writeHatchesc             C   s(   t dt| j }| j|||f |S )NzGT%d)rE   r.   r  r/   )rl   pointscolorsrv   r5   r5   r6   addGouraudTriangles  s    zPdfFile.addGouraudTrianglesc             C   sb  t  }xF| jD ]:\}}}| d}|||< |j}||d |d  df}||d |d  df}tj|ddd }	tj|ddd }
d|
|	  }| |j	d dd	d
d
t
dd|	d |
d |	d |
d ddddddg
d tj|d |d  fdddgd}d|d< ||	 | |d< |d d d df d |d< | |  |   qW | | j| d S )NzGouraud triangler   r*   r  r|  )Zaxis   l    r     r  T)ZShadingTypeZBitsPerCoordinateBitsPerComponentZBitsPerFlag
ColorSpaceZ	AntiAliasZDecode)r  u1)r  z>u4)r  )r  r  )r  )Zdtyper  r  r  g     o@r  )r_   r  r   shapereshaperQ   minr  r%  rk   rE   emptyro   tostringr"  r   r   )rl   ZgouraudDictrv   r  r  r/  r  Zflat_pointsZflat_colorsZ
points_minZ
points_maxZfactorZ	streamarrr5   r5   r6   r3    s@    

zPdfFile.writeGouraudTrianglesc             C   sf   | j t|d}|dk	r"|d S td| j }| d| j }|  jd7  _|||f| j t|< |S )z=Return name of an image XObject representing the given image.Nr*   zI%dzimage %d)r  rE  rk   rE   r  r   )rl   r.  entryrv   r/  r5   r5   r6   imageObject  s    zPdfFile.imageObjectc             C   s   |j dd \}}|ddd }|jdkr6|||dfS |ddddddf }tj|dd}|j d dkr|dddddf d }t|d	krd}qtj|dd}nd}||||fS dS )
z
        Unpack the image object im into height, width, data, alpha,
        where data and alpha are HxWx3 (RGB) or HxWx1 (grayscale or alpha)
        arrays, except alpha is None if the image is fully opaque.
        Nr  r  r  C)orderr|  ).Nr  )r  ndimrQ   Zarrayall)rl   imhr  rgbr  r5   r5   r6   _unpack  s    
zPdfFile._unpackc             C   s   t  }t|| |d d}td}x||}|dks@ttdt	|\}}|dkrt|}||}||kszt| j
t	| ||7 }n|dkrP n||d |dd q*W dS )	zo
        Write the image *data* into the pdf file using png
        predictors with Flate compression.
        r  r   s   !L4ss   IDATs   IENDr*   r|  N)r   r'   Z	write_pngseek	bytearrayreadintor;   structZunpackr\   r   ro   )rl   r   bufferZwrittenheadernr4   rg   r5   r5   r6   	_writePng6  s&    



zPdfFile._writePngc       	      C   s   t dt d||t |rdnddd}|r2||d< td rPd	|rDd
nd|d}nd}| j|| d||d |r|| | n| j|  |   dS )a  
        Write the image *data* of size *height* x *width*, as grayscale
        if *grayscale* is true and RGB otherwise, as pdf object *id*
        and with the soft mask (alpha channel) *smask*, which should be
        either None or a *height* x *width* x 1 array.
        r   ZImageZ
DeviceGrayr  r  )r   r*  ZWidthZHeightr  r  ZSMaskzpdf.compression
   r*   r  )Z	PredictorZColorsZColumnsNzlength of image stream)r   )	rE   r   r%  r   r  r   ro   r  r"  )	rl   r   r$  r#  Z	grayscalerk   smaskrH   r   r5   r5   r6   	_writeImgQ  s.    


zPdfFile._writeImgc       	   	   C   sr   xl| j  D ]^\}}}| |\}}}}|d k	rP| d}| |||d|j nd }| |||d|j| qW d S )Nr  TF)r  r1  r  r   r  rk   )	rl   Zimgrv   r/  r$  r#  r   ZadataZsmaskObjectr5   r5   r6   r4  t  s    
zPdfFile.writeImagesc             C   s   | j ||dd}t|t|t|||f}	| j|	}
|
dkrtdt| j }| dt| j }||}||||g| j|	< n|
d |k r||
d< |
d }|S )z<Return name of a marker XObject representing the given path.F)r  NzM%dz	marker %dr  r   )	r  rc   rU   r  rE  rE   r.   r   get_extents)rl   r   r;  r7   r   lw	joinstylecapstylepathopsrG   r1   rv   r/  r  r5   r5   r6   markerObject  s    
zPdfFile.markerObjectc       
   	   C   s   x| j  D ]\\}}}}}\}}}}	||	d }| |jd tdtdt|jd | t	j
| tj | t	j| tj | j|  | t|| |   qW d S )Ng      ?r   r  )r   r*  r  )r  r  paddedr%  rk   rE   rb   extentsr&  r'  r(  r   r   	capstylesr   
paint_pathr"  )
rl   r  r7   r   r  r  rv   r/  r  r  r5   r5   r6   r5    s    $
zPdfFile.writeMarkersc       	      C   sP   t dt| j }| dt| j }| j||||| | |||f	 |S )NzP%dzpath %d)rE   r.   r  r   r/   get_joinstyleget_capstyle)	rl   gcr   r;  r<  r=  r>  rv   r/  r5   r5   r6   pathCollectionObject  s    zPdfFile.pathCollectionObjectc          
   C   s   x| j D ]\	}}}}}}}}}	| j||dd}
||}tt|jsXddddg}n||}t|j}| 	|j
d tdtd|d | tj| tj | tj| tj | j|
  | t||	 |   qW d S )NF)r  r   r   r  )r   r*  r  )r  r  r  rQ   r  rR   r  r  rb   r%  rk   rE   r&  r'  r(  r   r   r  r   r  r"  )rl   rv   r   r;  r/  r  r  r<  r=  r>  r  r  r  r5   r5   r6   r6    s$    




z$PdfFile.writePathCollectionTemplatesc             C   s8   t t| ||||dtjjtjjdtjjtjjgdgS )N       T)	r   r&   Zconvert_to_stringr   r   r   r   r   r   )r   rt  r   r  sketchr5   r5   r6   r    s
    
zPdfFile.pathOperationsFc             C   sN   |r$dd| j d | jd f}|j}nd }d}| j|||||d}| j|  d S )Ng        r  F)r  r  )r#  r$  Zshould_simplifyr  r&  )rl   r   rt  r   r  r  cmdsr5   r5   r6   	writePath  s    zPdfFile.writePathr  c             C   s.   | j }|  j d7  _ | jdd|g t|S )zReserve an ID for an indirect object.
        The name is used for debugging in case we forget to print out
        the object with writeObject.
        r*   Nr   )r   r   r/   rj   )rl   rv   rk   r5   r5   r6   r     s    zPdfFile.reserveObjectc             C   s   | j  | j | j| d< d S )Nr   )r   r   r   r   )rl   rk   r5   r5   r6   r     s    zPdfFile.recordXrefc             C   s   |  |j |||  d S )N)r   rk   ro   )rl   objectrp   r5   r5   r6   r     s    zPdfFile.writeObjectc             C   s   | j  | j | _| d| j  d}d}xh| jD ]^\}}}|dkr`td||f tj	d d}n(|dkrld	nd
}d|||f }| | |d7 }q2W |rt
ddS )zWrite out the xref table.s
   xref
0 %d
r   FNzNo offset for object %d (%s))rq   Tzthe zero objectr   r   s   %010d %05d %b 
r*   zIndirect object does not exist)r   r   r   	startxrefro   r   r   printsysstderrr;   )rl   r2   ZborkenoffsetZ
generationrv   rG   r+  r5   r5   r6   r8    s    

zPdfFile.writeXrefc          
   C   s   dd }dd }dd }|||||||||d	}xN| j D ]D}||krXtjd| d	d
 q8|| | j | s8tjd| d	d
 q8W | d| _| | j| j  dS )z8Write out the info dictionary, checking it for good formc             S   s
   t | tS )N)rO   rW   )r   r5   r5   r6   is_string_like  s    z-PdfFile.writeInfoDict.<locals>.is_string_likec             S   s
   t | tS )N)rO   r   )r   r5   r5   r6   is_date  s    z&PdfFile.writeInfoDict.<locals>.is_datec             S   s   t | to| jdkS )N)TrueFalseZUnknown)rO   rE   rv   )r   r5   r5   r6   <lambda>
  s   
z'PdfFile.writeInfoDict.<locals>.<lambda>)	ZTitleZAuthorZSubjectZKeywordsr   r   r   ZModDateZTrappedzUnknown infodict keyword: %sr  )
stacklevelz!Bad value for infodict keyword %sr]  N)r  warningswarnr   
infoObjectr   )rl   r  r  Zcheck_trappedkeywordsr   r5   r5   r6   r7    s(    
zPdfFile.writeInfoDictc             C   s:   |  d |  t| j| j| jd |  d| j  dS )zWrite out the PDF trailer.s   trailer
)ZSizeZRootZInfos   
startxref
%d
%%%%EOF
N)ro   r?   r   r   r  r  )rl   r5   r5   r6   r9  !  s    
zPdfFile.writeTrailer)N)NN)N)NNN)FN)r  )1rr   rs   rt   ru   rm   r)  r-  r?  r@  ro   r&  r%  r"  rI  propertyr
   Z
deprecatedrM  rX  r0  r[  rY  rv  r  r  r\  r  r  r2  r  r3  r  r  r  r  r4  r  r5  r   r6  r   r  r  r   r   r   r8  r7  r9  r5   r5   r5   r6   r     s\   
e!
;B  1&&
#

 r   c               @   s   e Zd ZedZdd Zdd Zd8ddZd	d
 Zdd Z	dd Z
dd Zdd Zd9ddZd:ddZdd Zd;ddZdd Zdd Zd<d d!Zd"d# Zd=d%d&Zd'd( Zd>d*d+Zd,d- Zd.d/ Zd0d1 Zd2d3 Zd4d5 Zd6d7 ZdS )?RendererPdfr~  c             C   s:   t |  || _|| _|| _|  | _td| _|| _	d S )NZPdf)
r   rm   r$  r#  rq   new_gcr  r!   mathtext_parser	image_dpi)rl   rq   r  r$  r#  r5   r5   r6   rm   0  s    


zRendererPdf.__init__c             C   s   | j j| j   d S )N)rq   r&  r  r?  )rl   r5   r5   r6   r?  9  s    zRendererPdf.finalizeNc             C   s   t |dd}||_t |dd}| d kr8|jddd |jrN|j|jf|_n:|d ksbt|dk rt|jd	 d
f|_n|jd	 |d	 f|_| j	
|}|r| jj|  ||_||_d S )N
_fillcolor)g        g        g        _effective_alphas)g      ?g      ?)r   r   r   r   T)ZisRGBAr|  r  g      ?)getattrr  Zget_rgbZset_foreground_forced_alpha_alphar  r.   _rgbr  deltarq   r&  )rl   r  	fillcolorZ	orig_fillZorig_alphasr!  r5   r5   r6   check_gc<  s    zRendererPdf.check_gcc             C   sP   t |tr|}n|j}t|\}}| jj||t f}|d t	t
| dS )zDKeeps track of which characters are required from
        each font.r*   N)rO   rW   fnamer   rq   r	  
setdefaultr  r   mapr   )rl   rf  r3   r$  r^  r_  r	  r5   r5   r6   track_charactersX  s    
zRendererPdf.track_charactersc             C   sB   x<|  D ]0\}\}}| jj||t f}|d | q
W d S )Nr*   )r  rq   r	  r%  r  r   )rl   r}   r_  r^  charsetr	  r5   r5   r6   merge_used_charactersd  s    z!RendererPdf.merge_used_charactersc             C   s
   | j d S )Ng      R@)r  )rl   r5   r5   r6   get_image_magnificationj  s    z#RendererPdf.get_image_magnificationc             C   s   dS )zA
        pdf backend support arbitrary scaling of image.
        Tr5   )rl   r5   r5   r6   option_scale_imagem  s    zRendererPdf.option_scale_imagec             C   s
   t d  S )zl
        return whether to generate a composite image from multiple images on
        a set of axes
        zimage.composite_image)r   )rl   r5   r5   r6   option_image_nocomposites  s    z$RendererPdf.option_image_nocompositec             C   s   |j d d \}}|dks"|dkr&d S |d kr8|d | | d| | j }d| | j }| j|}|d kr| jtj|dd|||tj	|tj
tj nP|  \}	}
}}}}| jtjdddd||tj	|	|
||||tj	|tj
tj d S )Nr  r   g      ?g      R@r*   )r  Z	set_alphar#  r  rq   r  r&  r   r   r   r   r   frozenZ	to_values)rl   r  r   yr  rt  r  r  ZimobZtr1Ztr2Ztr3Ztr4Ztr5Ztr6r5   r5   r6   
draw_imagez  s$    



zRendererPdf.draw_imagec             C   sH   |  || | j|||d ko(| d k|  | j| j  d S )N)r#  rq   r  Zget_hatch_pathZget_sketch_paramsr&  r  paint)rl   r  r   rt  rgbFacer5   r5   r6   	draw_path  s    
zRendererPdf.draw_pathc       $      C   s,  d}t |}t |}t|s0d}|  }n0t |d d df |d kr\|d dk}nd}t|snd}nJt t |	dkrd}n0t |d d df |d kr|d dk}nd}t|dkrt|d jnd}| |||||}|| d || k }|r|s,t| |||||||||	|
|||S t 	|	}g }xDt
| |||D ].\}\}}| j||||||}|| qNW | jj}|| j   d\}}xz| |||||||||	|
|||D ]T\}}}} }!| | |! || ||  }"}#|d	ddd	|"|#tj|tj	 || }}qW || j   d S )
NTFr  )r   r  g        r      )r   r   r*   )rQ   asarrayr.   Z	get_hatchr  verticesZ_iter_collection_uses_per_pathr   draw_path_collectionr  r-   Z_iter_collection_raw_pathsrq   r   r/   r&  r  pushZ_iter_collectionr#  r   r   r   pop)$rl   r  Zmaster_transformr  Zall_transformsZoffsetsZoffsetTransZ
facecolorsZ
edgecolorsZ
linewidthsZ
linestylesZantialiasedsZurlsZoffset_positionZcan_do_optimizationr=  r>  Zlen_pathZuses_per_pathZshould_do_optimizationr<  Z
path_codesr2   r   rt  rv   r&  lastxlastyZxoZyoZpath_idZgc0r1  dxdyr5   r5   r6   r6    s\    





z RendererPdf.draw_path_collectionc             C   st  t |}t |}|| || d k r>t| |||||| d S | || ||}	| }
| jj}| j|||	|
| j	j
| | }|tj d\}}x|j|dd| jjd | jjd fddD ]\}}t |r|dd  \}}d|  kr| jjd krn qd|  kr&| jjd ks*q q|| ||  }}|dddd||tj|tj	 || }}qW |tj d S )	Nr3  )r   r   r   r  F)r   r  r  r*   )r.   r   draw_markersr#  r7   r   rq   r&  r  r  
_linewidthr  r  r   r   Ziter_segmentsr#  r$  r   r   r   )rl   r  Zmarker_pathZmarker_transr   r;  r1  Zlen_marker_pathZusesr7   r   r&  Zmarkerr9  r:  r5  coder   r.  r;  r<  r5   r5   r6   r=    s:    


""
zRendererPdf.draw_markersc             C   s    |  ||d|d| d S )N)r*   r  r  )r*   r  r|  )draw_gouraud_trianglesr  )rl   r  r  r  r;  r5   r5   r6   draw_gouraud_triangle  s    z!RendererPdf.draw_gouraud_trianglec             C   s   t |t |kst|jdks"t|jd dks4t|jd dksFt|jdksTt|jd dksft|jd dksxt|j}||d |d  df}||}||}| j||}| | | j	|t
j d S )Nr  r*   r  r|  r   )r.   r;   r  r  r  rt  rq   r  r#  r&  r   r   )rl   r  r  r  r;  r  Ztpointsrv   r5   r5   r6   r@    s    


z"RendererPdf.draw_gouraud_trianglesr   c          	   C   s   ||  krdkr4n n| j || || tj nJ|d t }| j t|t|t| t|||tj | j ddtj d S )Nr   g     f@)rq   r&  r   r   r   r   r	   r   )rl   r   r.  angleoldxoldyZoldangler5   r5   r6   _setup_textpos  s    zRendererPdf._setup_textposc             C   sJ  | j |d|\}}}	}
}}| | td }|d t }| jtj | jt	|t
|t
| t	|||tj | ||j | jtj d}d\}}x|
D ]\}}}}}}t|rd}n|}|dks|dkr| ||d|| || }}||f|kr | j| j||tj ||f}| j| t||tj qW | jtj |d	krx|
D ]\}}}}}}t|r~d}n|}|d	kr^|dkr^| j| | jtjd
| ddd
| ||tj | j||}| jt|tj | jtj q^W x8|D ]0\}}}}| jtj||||tjtjtj qW | jtj d S )Nr  zpdf.fonttypeg     f@)NN)r   r   r  r  r   r  gMbP?)r  parser)  r   r   rq   r&  r   r   r   r	   r   r#  r   r   r   rE  rI  r   encode_stringr  r   r   r  rE   r   r   r   r7   )rl   r  r   r.  r3   ru  rB  r#  r$  Zdescentglyphsrectsr	  Zglobal_fonttypeaZ	prev_fontrC  rD  ZoxZoyrg  fontsizeZnumr  r  rv   r5   r5   r6   draw_mathtext'  sX    
$



zRendererPdf.draw_mathtextTeX!c	       $   	   C   s~  |   }	| }
|	||
}t|d}tt|}W d Q R X d g  }}xb|jD ]X\}}}}}||kr| j	|}|d||j
gg7 }|}|d||t|gg|| gg7 }qRW d\}}}
x|t|d k r|||d  \}}|d dkr|d }
n|d |d   krdkrn n|d |d kr|d |d  }t|d	k r|d
 d  |d
 d 7  < |d  |d |d  7  < n0|d
  |d |
 |d
 d g7  < |d |d< ||d = q|d7 }qW t |||}| ||j | jtj d\}}}}x|D ]}|d dkr>| j|d |d tj n|d dkr||d |d f\}}| ||||| || }}t|d
 dkr| j|d
 d tj n| j|d
 tj n
dstqW | jtj |  }|| |d t j!t j"t j"t j"t j#g} xb|j$D ]X\}}}!}"t ||g||" |g||" ||! g|||! gddgg| }#| %||#||j qW d S )Nr  rf  r+  )r   r   Nr*   r  r   r|  g?r  r  g     @@)r   r   r   r   F)&get_texmanagerget_size_in_pointsZmake_dvirJ  ZDvinextiterr+  rq   rX  sizer\   r.   absr"   Z
rotate_deg	translater#  r   r&  r   r   r   Ztransform_pointrE  r   r   r;   r   r  copy_propertiesZset_linewidthr$   ZMOVETOZLINETOZ	CLOSEPOLYZboxesr2  )$rl   r  r   r.  r3   ru  rB  ismathmtext
texmanagerrK  ZdvifileZdvir   ZoldfontseqZx1Zy1rN  r  r#  rO  r2   ZcurxZeltZnxtr  ZmytransZcuryrC  rD  Zboxgcr  r  r  r   r5   r5   r6   draw_texi  sh    
$

6$




*zRendererPdf.draw_texc             C   s    |dkr| ddS | ddS )N)r*   r  r  r  zutf-16be)rX   )rl   r3   r  r5   r5   r6   rG    s    zRendererPdf.encode_stringFc	                s    ||j |r&| S  td rX\}	}
}}dn< j	dt
d td tjrdfdd} fd	d
} fdd}|\}}|r| S ||S d S )Nzpdf.use14corefontsr*   g        )r  zpdf.fonttyper  c                s   d}g }t d s dkrt| tst| dkrt| } x^| D ]V}t|dkrRd}nd}t|r|d d |kr|d d | q<|||gf q<W t|dko|d d dk}||fS )	zDetermine if we should use the simple or woven method
            to output this text, and chunks the string into 1-byte and
            2-byte sections if necessary.Tzpdf.use14corefontsr  r   r  r*   r  r  )r   rO   r\   r.   rW   r   r/   )r3   use_simple_methodchunksr  Z	char_type)r  r5   r6   check_simple_method  s    
z2RendererPdf.draw_text.<locals>.check_simple_methodc                  sL   j tjj tj   j tjtj	 dS )z%Outputs text using the simple method.N)
rq   r&  r   r   rI  r   rE  rG  r   r   r5   )rB  rK  r  ru  r3   rl   r   r.  r5   r6   draw_text_simple  s    

z/RendererPdf.draw_text.<locals>.draw_text_simplec                s  dd | D } j tj  d t }j t|t|t| t|tj xdD ]}d }}|dkrj tjj 	tj
 xD| D ]:\}}|dkr|dkr|dd|dd j |tj |}d}x|D ]}t|}	|	}
|
dk	r|dkr|dkr|
}j tj j d	 ddd	 |dtj j j|}j t|tj j tj j|	td
}|dk	r||
t}nd}|
}||d |jd  7 }qW qW |dkr\j tj q\W j tj dS )zOutputs text using the woven method, alternating
            between chunks of 1-byte characters and 2-byte characters.
            Only used for Type 3 fonts.c             S   s   g | ]\}}|d  |fqS )r  )r0   )rF   rJ  br5   r5   r6   rI     s    zBRendererPdf.draw_text.<locals>.draw_text_woven.<locals>.<listcomp>g     f@)r*   r  r   r*   Nr  gMbP?)r  g      P@g      @)rq   r&  r   r   r   r   r	   r   r   rI  r   rE  rG  r   r   r  r  r  r$  rE   r   r   r  r   Zget_kerningr    ZlinearHoriAdvancer   )r\  rJ  modeZnewxrC  Z
chunk_typechunkZlastgindr  r  r  r  rv   r  Zkern)rB  rf  rK  r  ru  rl   r   r.  r5   r6   draw_text_woven  sX    $






z.RendererPdf.draw_text.<locals>.draw_text_woven)r#  r   rL  rO  r   _get_font_afmZget_str_bbox_get_font_ttfr'  set_textr   r   r$  )rl   r  r   r.  r3   ru  rB  rV  rW  lr_  r  r  r]  r^  rb  r[  r\  r5   )	rB  rf  rK  r  ru  r3   rl   r   r.  r6   	draw_text  s*    



@zRendererPdf.draw_textc             C   s  t d r8|  }| }|j||| d\}}}|||fS |rZ| j|d|\}}}}	}
}nt d r| |}||\}}}}}| }||d 9 }||d 9 }||d 9 }nJ| |}|j	|dt
d | \}}d}||9 }||9 }| }||9 }|||fS )	Nztext.usetex)rendererr  zpdf.use14corefontsi  g        )r  g      ?)r   rN  rO  get_text_width_height_descentr  rF  rc  Zget_str_bbox_and_descentrd  re  r   Zget_width_heightZget_descent)rl   r3   ru  rV  rX  rK  r  r  drH  rI  r	  rf  rf  r_  r  r5   r5   r6   ri  I  s0    


z)RendererPdf.get_text_width_height_descentc          	   C   s   t |}| j|}|d krt|d| jjd}|d krHtdd| jjd}| j|}|d krt|d}t|}|| j|< W d Q R X || j|< |S )NrA  )rB  rC  rD  ra  )r   afm_font_cacherE  r   rq   r   re  r   )rl   ru  rG   rf  r  r   r5   r5   r6   rc  g  s     
zRendererPdf._get_font_afmc             C   s,   t |}t|}|  || d |S )Nr  )r   r   clearZset_sizerO  )rl   ru  r  rf  r5   r5   r6   rd  y  s
    zRendererPdf._get_font_ttfc             C   s   dS )NFr5   )rl   r5   r5   r6   flipy  s    zRendererPdf.flipyc             C   s   | j jd | j jd fS )Ng      R@)rq   r#  r$  )rl   r5   r5   r6   get_canvas_width_height  s    z#RendererPdf.get_canvas_width_heightc             C   s
   t | jS )N)r'  rq   )rl   r5   r5   r6   r    s    zRendererPdf.new_gc)N)N)N)N)r   r   r   )rM  N)FN)rr   rs   rt   r   rk  rm   r?  r#  r'  r)  r*  r+  r,  r/  r2  r6  r=  rA  r@  rE  rL  rZ  rG  rg  ri  rc  rd  rm  rn  r  r5   r5   r5   r6   r  -  s6   	


G
#

B
N
 r  c            
   @   s   e Zd Zdd Zdd Zdd Zdd Zd	d
 ZddddZddddZ	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&efd'efd(e
fd)efd*efd+efd,efd-efd.eff	Zd/d0 Zd1d2 Zd3d4 Zd5S )6r'  c             C   s&   t |  d| _d| _|| _d | _d S )N)g        g        g        )g      ?g      ?)r   rm   r  r  rq   parent)rl   rq   r5   r5   r6   rm     s
    
zGraphicsContextPdf.__init__c             C   s   t | j}|d= |d= t|S )Nrq   ro  )r_   rp  repr)rl   rj  r5   r5   r6   rn     s    
zGraphicsContextPdf.__repr__c             C   s0   | j dko.| jdko.t| jdkp.| jd dkS )z
        Predicate: does the path need to be stroked (its outline drawn)?
        This tests for the various conditions that disable stroking
        the path, in which case it would presumably be filled.
        r   r  g        )r>  r  r.   r   )rl   r5   r5   r6   r     s    zGraphicsContextPdf.strokec             G   s>   t |r|d }n| j}| jp<|dk	o<t |dkp<|d dkS )z
        Predicate: does the path need to be filled?

        An optional argument can be used to specify an alternative
        _fillcolor, as needed by RendererPdf.draw_markers.
        r   Nr  g        )r.   r  _hatch)rl   argsr  r5   r5   r6   r7     s    
zGraphicsContextPdf.fillc             C   s   t |  |  S )zo
        Return the appropriate pdf operator to cause the path to be
        stroked, filled, or both.
        )r   r  r7   r   )rl   r5   r5   r6   r0    s    zGraphicsContextPdf.paintr   r*   r  )Zbuttr!  Z
projecting)Zmiterr!  Zbevelc             C   s   | j | tjgS )N)r  r   r   )rl   styler5   r5   r6   capstyle_cmd  s    zGraphicsContextPdf.capstyle_cmdc             C   s   | j | tjgS )N)r(  r   r   )rl   rs  r5   r5   r6   joinstyle_cmd  s    z GraphicsContextPdf.joinstyle_cmdc             C   s
   |t jgS )N)r   r   )rl   r#  r5   r5   r6   linewidth_cmd  s    z GraphicsContextPdf.linewidth_cmdc             C   s(   |\}}|d krg }d}t ||tjgS )Nr   )rb   r   r   )rl   Zdashesr  Zdashr5   r5   r6   dash_cmd  s
    zGraphicsContextPdf.dash_cmdc             C   s   | j |}|tjgS )N)rq   r  r   r   )rl   r  Zforcedeffective_alphasrv   r5   r5   r6   	alpha_cmd  s    zGraphicsContextPdf.alpha_cmdc             C   sZ   |s*| j d k	r| | j S tdtjgS n,|| j |f}| j|}tdtj|tjgS d S )Nr  r   )r  fillcolor_cmdrE   r   r   rq   r  r   )rl   r  Zhatch_colorr  rv   r5   r5   r6   	hatch_cmd  s    

zGraphicsContextPdf.hatch_cmdc             C   sV   t d rg S |d |d   kr,|d kr>n n|d tjgS |d d tjfS d S )Nzpdf.inheritcolorr   r*   r  r  )r   r   r   r   )rl   r  r5   r5   r6   rgb_cmd  s
    $zGraphicsContextPdf.rgb_cmdc             C   s^   |d kst d rg S |d |d   kr4|d krFn n|d tjgS |d d tjfS d S )Nzpdf.inheritcolorr   r*   r  r  )r   r   r   r   )rl   r  r5   r5   r6   rz    s
    $z GraphicsContextPdf.fillcolor_cmdc             C   s*   t | j}||  | j|_|| _tjgS )N)r'  rq   rU  ro  r   r   )rl   ro  r5   r5   r6   r7    s
    

zGraphicsContextPdf.pushc             C   s,   | j d k	st| | j  | j j | _ tjgS )N)ro  r;   rU  r   r   )rl   r5   r5   r6   r8    s    
zGraphicsContextPdf.popc             C   s   g }x0| j | jf||fkr4| jdk	r4||   qW | j | jf||fksT| jdkr||   | j |kr||tjtjtj	g | j|kr|
 \}}|tj||ddtjtj	g  |S )z5Set clip rectangle. Calls self.pop() and self.push().NF)r  )	_cliprect	_clippathro  r`   r8  r7  r   r   r   r   Zget_transformed_path_and_affiner   r  )rl   ZcliprectZclippathr  r   Zaffiner5   r5   r6   clip_cmd  s    



zGraphicsContextPdf.clip_cmd)r}  r~  )r  r  r  )Z	_capstyle)r  )Z
_joinstyle)r>  )Z_dashes)r   )rq  _hatch_colorc       
   
      s&  g }d}x| j D ]
\}}d}x|D ]}t| |}t |}	y*|dksP|	dkrZ||	k	}nt||	k}W nB tk
r   t|}t|	}	|j|	jkpt||	k}Y nX |r&P q&W |dkr|rd}|r|dkrd} fdd|D }	||| f|	  x |D ]}t	| |t | qW qW |S )zy
        Copy properties of other into self and return PDF commands
        needed to transform self into other.
        FN)rq  r  T)r  c                s   g | ]}t  |qS r5   )r  )rF   p)r}   r5   r6   rI   <	  s    z,GraphicsContextPdf.delta.<locals>.<listcomp>)
commandsr  rU   rS   rQ   r4  r  anyr`   setattr)
rl   r}   r  Zfill_performedZparamscmdZ	differentr  ZoursZtheirsr5   )r}   r6   r!  	  s8    






zGraphicsContextPdf.deltac             C   s8   t | | t|d| j}t|d| j}|| _|| _dS )z5
        Copy properties of other into self.
        r  r  N)r   rU  r  r  r  )rl   r}   r"  rx  r5   r5   r6   rU  B	  s    z"GraphicsContextPdf.copy_propertiesc             C   s&   g }x| j dk	r ||   qW |S )zB
        Make sure every pushed graphics state is popped.
        N)ro  r`   r8  )rl   r  r5   r5   r6   r?  M	  s    zGraphicsContextPdf.finalizeN)rr   rs   rt   rm   rn   r   r7   r0  r  r(  rt  ru  rv  rw  ry  r{  r|  rz  r7  r8  r  r  r!  rU  r?  r5   r5   r5   r6   r'    s<   
&r'  c               @   sd   e Zd ZdZdZdddZdd Zd	d
 Zdd Zdd Z	dddZ
dd ZddddgfddZdS )PdfPagesaa  
    A multi-page PDF file.

    Examples
    --------

    >>> import matplotlib.pyplot as plt
    >>> # Initialize:
    >>> with PdfPages('foo.pdf') as pdf:
    ...     # As many times as you like, create a figure fig and save it:
    ...     fig = plt.figure()
    ...     pdf.savefig(fig)
    ...     # When no figure is specified the current figure is saved
    ...     pdf.savefig()

    Notes
    -----

    In reality :class:`PdfPages` is a thin wrapper around :class:`PdfFile`, in
    order to avoid confusion when using :func:`~matplotlib.pyplot.savefig` and
    forgetting the format argument.
    )_file
keep_emptyTNc             C   s   t ||d| _|| _dS )a  
        Create a new PdfPages object.

        Parameters
        ----------

        filename : str
            Plots using :meth:`PdfPages.savefig` will be written to a file at
            this location. The file is opened at once and any older file with
            the same name is overwritten.
        keep_empty : bool, optional
            If set to False, then empty pdf files will be deleted automatically
            when closed.
        metadata : dictionary, optional
            Information dictionary object (see PDF reference section 10.2.1
            'Document Information Dictionary'), e.g.:
            `{'Creator': 'My software', 'Author': 'Me',
            'Title': 'Awesome fig'}`

            The standard keys are `'Title'`, `'Author'`, `'Subject'`,
            `'Keywords'`, `'Creator'`, `'Producer'`, `'CreationDate'`,
            `'ModDate'`, and `'Trapped'`. Values have been predefined
            for `'Creator'`, `'Producer'` and `'CreationDate'`. They
            can be removed by setting them to `None`.

        )r  N)r   r  r  )rl   r  r  r  r5   r5   r6   rm   w	  s    zPdfPages.__init__c             C   s   | S )Nr5   )rl   r5   r5   r6   	__enter__	  s    zPdfPages.__enter__c             C   s   |    d S )N)r@  )rl   exc_typeZexc_valZexc_tbr5   r5   r6   __exit__	  s    zPdfPages.__exit__c             C   sH   | j   | j   |  dkr>| js>| j js>t| j jj	 d| _ dS )z_
        Finalize this object, making the underlying file a complete
        PDF file.
        r   N)
r  r?  r@  get_pagecountr  r   r   remover   rv   )rl   r5   r5   r6   r@  	  s    

zPdfPages.closec             C   s   | j jS )z
        Return a modifiable information dictionary object
        (see PDF reference section 10.2.1 'Document Information
        Dictionary').
        )r  r  )rl   r5   r5   r6   infodict	  s    zPdfPages.infodictc             K   s|   t |tsD|dkrt }n
t|}|dkr<td||jj}z*|j}t	||_|j
| fddi| W d||_X dS )aQ  
        Saves a :class:`~matplotlib.figure.Figure` to this file as a new page.

        Any other keyword arguments are passed to
        :meth:`~matplotlib.figure.Figure.savefig`.

        Parameters
        ----------

        figure : :class:`~matplotlib.figure.Figure` or int, optional
            Specifies what figure is saved to file. If not specified, the
            active figure is saved. If a :class:`~matplotlib.figure.Figure`
            instance is provided, this figure is saved. If an int is specified,
            the figure instance to save is looked up by number.
        NzNo figure {}rf   pdf)rO   r   r   Z
get_activeZget_fig_managerrS   rf   ZcanvasfigureFigureCanvasPdfsavefig)rl   r  kwargsZmanagerZorig_canvasr5   r5   r6   r  	  s    



zPdfPages.savefigc             C   s   t | jjS )zP
        Returns the current number of pages in the multipage pdf file.
        )r.   r  r   )rl   r5   r5   r6   r  	  s    zPdfPages.get_pagecountir   c             C   s   | j || dS )z
        Add a new text note to the page to be saved next. The optional
        positionRect specifies the position of the new note on the
        page. It is outside the page per default to make sure it is
        invisible on printouts.
        N)r  r-  )rl   r+  r,  r5   r5   r6   attach_note	  s    zPdfPages.attach_note)TN)N)rr   rs   rt   ru   r   rm   r  r  r@  r  r  r  r  r5   r5   r5   r6   r  ^	  s   

 r  c               @   s>   e Zd ZdZdZdd ZddiZdd Zdd	d	d
ddZd	S )r  z
    The canvas the figure renders into.  Calls the draw and print fig
    methods, creates the renderers, etc...

    Attributes
    ----------
    figure : `matplotlib.figure.Figure`
        A high-level Figure instance

    r  c             C   s   d S )Nr5   )rl   r5   r5   r6   draw	  s    zFigureCanvasPdf.drawr  zPortable Document Formatc             C   s   dS )Nr  r5   )rl   r5   r5   r6   get_default_filetype	  s    z$FigureCanvasPdf.get_default_filetypeN)dpibbox_inches_restorer  c      
   
   K   s   | j d | j  \}}t|tr,|j}nt||d}zV||| t| j |||t	|||||d}	| j 
|	 |	  t|ts|  W d t|tr|  n|  X d S )Nr  )r  )r  )r  Zset_dpiZget_size_inchesrO   r  r  r   r)  r   r  r  r?  r"  r@  )
rl   r  r  r  r  r  r#  r$  rq   rh  r5   r5   r6   	print_pdf	  s$    




zFigureCanvasPdf.print_pdf)	rr   rs   rt   ru   Z	fixed_dpir  Z	filetypesr  r  r5   r5   r5   r6   r  	  s   
r  c               @   s   e Zd ZeZdS )_BackendPdfN)rr   rs   rt   r  ZFigureCanvasr5   r5   r5   r6   r  
  s   r  )r)   )fru   rZ   r  r   	functoolsr   ior   ZloggingZmathr   r   r   r   r	   r   r   r  r	  rd   rU  r  r   ZnumpyrQ   Z
matplotlibr
   r   r   Zmatplotlib._pylab_helpersr   Zmatplotlib.backend_basesr   r   r   r   r   Z!matplotlib.backends.backend_mixedr   Zmatplotlib.cbookr   r   r   Zmatplotlib.figurer   Zmatplotlib.font_managerr   r   r   Zmatplotlib.afmr   Zmatplotlib.type1fontrs  Zmatplotlib.dvireadrJ  Zmatplotlib.ft2fontr   r   r   r   r    Zmatplotlib.mathtextr!   Zmatplotlib.transformsr"   r#   Zmatplotlib.pathr$   Zmatplotlib.datesr%   r&   r'   r(   Z	getLoggerrr   rF  r7   r   r]   r>   r?   r  rj   rE   r   r   r_   Z_pdfopsrV  r  r   r   r  r   r   r  r'  r  r  ZFigureManagerPdfZexportr  r5   r5   r5   r6   <module>   s   
2

\$
Q             a U 1