@@ -565,9 +565,8 @@ def writeFonts(self):
565565 self .writeObject (self .fontObject , fonts )
566566
567567 def _write_afm_font (self , filename ):
568- fh = open (filename , 'rb' )
569- font = AFM (fh )
570- fh .close ()
568+ with open (filename , 'rb' ) as fh :
569+ font = AFM (fh )
571570 fontname = font .get_fontname ()
572571 fontdict = { 'Type' : Name ('Font' ),
573572 'Subtype' : Name ('Type1' ),
@@ -877,14 +876,13 @@ def embedTTFType42(font, characters, descriptor):
877876 fontfileObject .id ,
878877 self .reserveObject ('length of font stream' ),
879878 {'Length1' : length1Object })
880- fontfile = open (filename , 'rb' )
881- length1 = 0
882- while True :
883- data = fontfile .read (4096 )
884- if not data : break
885- length1 += len (data )
886- self .currentstream .write (data )
887- fontfile .close ()
879+ with open (filename , 'rb' ) as fontfile :
880+ length1 = 0
881+ while True :
882+ data = fontfile .read (4096 )
883+ if not data : break
884+ length1 += len (data )
885+ self .currentstream .write (data )
888886 self .endStream ()
889887 self .writeObject (length1Object , length1 )
890888
@@ -1827,10 +1825,9 @@ def _get_font_afm(self, prop):
18271825 directory = self .file ._core14fontdir )
18281826 font = self .afm_font_cache .get (filename )
18291827 if font is None :
1830- fh = open (filename , 'rb' )
1831- font = AFM (fh )
1832- self .afm_font_cache [filename ] = font
1833- fh .close ()
1828+ with open (filename , 'rb' ) as fh :
1829+ font = AFM (fh )
1830+ self .afm_font_cache [filename ] = font
18341831 self .afm_font_cache [key ] = font
18351832 return font
18361833
@@ -2175,17 +2172,19 @@ def print_pdf(self, filename, **kwargs):
21752172 file = filename ._file
21762173 else :
21772174 file = PdfFile (filename )
2178- file .newPage (width , height )
2179- _bbox_inches_restore = kwargs .pop ("bbox_inches_restore" , None )
2180- renderer = MixedModeRenderer (self .figure ,
2181- width , height , image_dpi , RendererPdf (file , image_dpi ),
2182- bbox_inches_restore = _bbox_inches_restore )
2183- self .figure .draw (renderer )
2184- renderer .finalize ()
2185- if isinstance (filename , PdfPages ): # finish off this page
2186- file .endStream ()
2187- else : # we opened the file above; now finish it off
2188- file .close ()
2175+ try :
2176+ file .newPage (width , height )
2177+ _bbox_inches_restore = kwargs .pop ("bbox_inches_restore" , None )
2178+ renderer = MixedModeRenderer (self .figure ,
2179+ width , height , image_dpi , RendererPdf (file , image_dpi ),
2180+ bbox_inches_restore = _bbox_inches_restore )
2181+ self .figure .draw (renderer )
2182+ renderer .finalize ()
2183+ finally :
2184+ if isinstance (filename , PdfPages ): # finish off this page
2185+ file .endStream ()
2186+ else : # we opened the file above; now finish it off
2187+ file .close ()
21892188
21902189class FigureManagerPdf (FigureManagerBase ):
21912190 pass
0 commit comments