2
2
import codecs
3
3
import datetime
4
4
import functools
5
+ from io import BytesIO
5
6
import logging
6
7
import math
7
8
import os
11
12
import subprocess
12
13
import sys
13
14
import tempfile
15
+ from tempfile import TemporaryDirectory
14
16
import weakref
15
17
16
18
from PIL import Image
@@ -866,18 +868,12 @@ def _print_pdf_to_fh(self, fh, *args, metadata=None, **kwargs):
866
868
hyperref_options = ',' .join (
867
869
_metadata_to_str (k , v ) for k , v in info_dict .items ())
868
870
869
- try :
870
- # create temporary directory for compiling the figure
871
- tmpdir = tempfile .mkdtemp (prefix = "mpl_pgf_" )
872
- fname_pgf = os .path .join (tmpdir , "figure.pgf" )
873
- fname_tex = os .path .join (tmpdir , "figure.tex" )
874
- fname_pdf = os .path .join (tmpdir , "figure.pdf" )
871
+ with TemporaryDirectory () as tmpdir :
872
+ tmppath = pathlib .Path (tmpdir )
875
873
876
874
# print figure to pgf and compile it with latex
877
- self .print_pgf (fname_pgf , * args , ** kwargs )
875
+ self .print_pgf (tmppath / "figure.pgf" , * args , ** kwargs )
878
876
879
- latex_preamble = get_preamble ()
880
- latex_fontspec = get_fontspec ()
881
877
latexcode = """
882
878
\\ PassOptionsToPackage{pdfinfo={%s}}{hyperref}
883
879
\\ RequirePackage{hyperref}
@@ -890,22 +886,16 @@ def _print_pdf_to_fh(self, fh, *args, metadata=None, **kwargs):
890
886
\\ begin{document}
891
887
\\ centering
892
888
\\ input{figure.pgf}
893
- \\ end{document}""" % (hyperref_options , w , h , latex_preamble , latex_fontspec )
894
- pathlib . Path ( fname_tex ).write_text (latexcode , encoding = "utf-8" )
889
+ \\ end{document}""" % (hyperref_options , w , h , get_preamble (), get_fontspec () )
890
+ ( tmppath / "figure.tex" ).write_text (latexcode , encoding = "utf-8" )
895
891
896
892
texcommand = mpl .rcParams ["pgf.texsystem" ]
897
893
cbook ._check_and_log_subprocess (
898
894
[texcommand , "-interaction=nonstopmode" , "-halt-on-error" ,
899
895
"figure.tex" ], _log , cwd = tmpdir )
900
896
901
- # copy file contents to target
902
- with open (fname_pdf , "rb" ) as fh_src :
903
- shutil .copyfileobj (fh_src , fh )
904
- finally :
905
- try :
906
- shutil .rmtree (tmpdir )
907
- except :
908
- TmpDirCleaner .add (tmpdir )
897
+ with (tmppath / "figure.pdf" ).open ("rb" ) as fh_src :
898
+ shutil .copyfileobj (fh_src , fh ) # copy file contents to target
909
899
910
900
def print_pdf (self , fname_or_fh , * args , ** kwargs ):
911
901
"""Use LaTeX to compile a Pgf generated figure to PDF."""
@@ -914,23 +904,14 @@ def print_pdf(self, fname_or_fh, *args, **kwargs):
914
904
915
905
def _print_png_to_fh (self , fh , * args , ** kwargs ):
916
906
converter = make_pdf_to_png_converter ()
917
-
918
- try :
919
- # create temporary directory for pdf creation and png conversion
920
- tmpdir = tempfile .mkdtemp (prefix = "mpl_pgf_" )
921
- fname_pdf = os .path .join (tmpdir , "figure.pdf" )
922
- fname_png = os .path .join (tmpdir , "figure.png" )
923
- # create pdf and try to convert it to png
924
- self .print_pdf (fname_pdf , * args , ** kwargs )
925
- converter (fname_pdf , fname_png , dpi = self .figure .dpi )
926
- # copy file contents to target
927
- with open (fname_png , "rb" ) as fh_src :
928
- shutil .copyfileobj (fh_src , fh )
929
- finally :
930
- try :
931
- shutil .rmtree (tmpdir )
932
- except :
933
- TmpDirCleaner .add (tmpdir )
907
+ with TemporaryDirectory () as tmpdir :
908
+ tmppath = pathlib .Path (tmpdir )
909
+ pdf_path = tmppath / "figure.pdf"
910
+ png_path = tmppath / "figure.png"
911
+ self .print_pdf (pdf_path , * args , ** kwargs )
912
+ converter (pdf_path , png_path , dpi = self .figure .dpi )
913
+ with png_path .open ("rb" ) as fh_src :
914
+ shutil .copyfileobj (fh_src , fh ) # copy file contents to target
934
915
935
916
def print_png (self , fname_or_fh , * args , ** kwargs ):
936
917
"""Use LaTeX to compile a pgf figure to pdf and convert it to png."""
@@ -973,12 +954,8 @@ class PdfPages:
973
954
... pdf.savefig()
974
955
"""
975
956
__slots__ = (
976
- '_outputfile ' ,
957
+ '_output_name ' ,
977
958
'keep_empty' ,
978
- '_tmpdir' ,
979
- '_basename' ,
980
- '_fname_tex' ,
981
- '_fname_pdf' ,
982
959
'_n_figures' ,
983
960
'_file' ,
984
961
'_info_dict' ,
@@ -1009,7 +986,7 @@ def __init__(self, filename, *, keep_empty=True, metadata=None):
1009
986
'Trapped'. Values have been predefined for 'Creator', 'Producer'
1010
987
and 'CreationDate'. They can be removed by setting them to `None`.
1011
988
"""
1012
- self ._outputfile = filename
989
+ self ._output_name = filename
1013
990
self ._n_figures = 0
1014
991
self .keep_empty = keep_empty
1015
992
self ._metadata = (metadata or {}).copy ()
@@ -1027,13 +1004,7 @@ def __init__(self, filename, *, keep_empty=True, metadata=None):
1027
1004
f'set { canonical } instead of { key } .' )
1028
1005
self ._metadata [canonical ] = self ._metadata .pop (key )
1029
1006
self ._info_dict = _create_pdf_info_dict ('pgf' , self ._metadata )
1030
-
1031
- # create temporary directory for compiling the figure
1032
- self ._tmpdir = tempfile .mkdtemp (prefix = "mpl_pgf_pdfpages_" )
1033
- self ._basename = 'pdf_pages'
1034
- self ._fname_tex = os .path .join (self ._tmpdir , self ._basename + ".tex" )
1035
- self ._fname_pdf = os .path .join (self ._tmpdir , self ._basename + ".pdf" )
1036
- self ._file = open (self ._fname_tex , 'wb' )
1007
+ self ._file = BytesIO ()
1037
1008
1038
1009
@cbook .deprecated ('3.3' )
1039
1010
@property
@@ -1085,27 +1056,22 @@ def close(self):
1085
1056
and moving the final pdf file to *filename*.
1086
1057
"""
1087
1058
self ._file .write (rb'\end{document}\n' )
1088
- self ._file .close ()
1089
-
1090
1059
if self ._n_figures > 0 :
1091
- try :
1092
- self ._run_latex ()
1093
- finally :
1094
- try :
1095
- shutil .rmtree (self ._tmpdir )
1096
- except :
1097
- TmpDirCleaner .add (self ._tmpdir )
1060
+ self ._run_latex ()
1098
1061
elif self .keep_empty :
1099
- open (self ._outputfile , 'wb' ).close ()
1062
+ open (self ._output_name , 'wb' ).close ()
1063
+ self ._file .close ()
1100
1064
1101
1065
def _run_latex (self ):
1102
1066
texcommand = mpl .rcParams ["pgf.texsystem" ]
1103
- cbook ._check_and_log_subprocess (
1104
- [texcommand , "-interaction=nonstopmode" , "-halt-on-error" ,
1105
- os .path .basename (self ._fname_tex )],
1106
- _log , cwd = self ._tmpdir )
1107
- # copy file contents to target
1108
- shutil .copyfile (self ._fname_pdf , self ._outputfile )
1067
+ with TemporaryDirectory () as tmpdir :
1068
+ tex_source = pathlib .Path (tmpdir , "pdf_pages.tex" )
1069
+ tex_source .write_bytes (self ._file .getvalue ())
1070
+ cbook ._check_and_log_subprocess (
1071
+ [texcommand , "-interaction=nonstopmode" , "-halt-on-error" ,
1072
+ tex_source ],
1073
+ _log , cwd = tmpdir )
1074
+ shutil .move (tex_source .with_suffix (".pdf" ), self ._output_name )
1109
1075
1110
1076
def savefig (self , figure = None , ** kwargs ):
1111
1077
"""
0 commit comments