Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 433b899

Browse files
committed
Separate pdf finalization from closing
If an error is raised and the object state is inconsistent, we shouldn't try to finalize the file, just close all resources. The idea is to support the following idiom: try: figure.draw(file) # write pdf file, can raise file.finalize() # do this if everything went well finally: file.close() # do this in any case
1 parent 77ad3ef commit 433b899

1 file changed

Lines changed: 12 additions & 5 deletions

File tree

lib/matplotlib/backends/backend_pdf.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -552,9 +552,10 @@ def newTextnote(self, text, positionRect=[-100, -100, 0, 0]):
552552
self.writeObject(annotObject, theNote)
553553
self.pageAnnotations.append(annotObject)
554554

555-
def close(self):
555+
def finalize(self):
556+
"Write out the various deferred objects and the pdf end matter."
557+
556558
self.endStream()
557-
# Write out the various deferred objects
558559
self.writeFonts()
559560
self.writeObject(self.alphaStateObject,
560561
dict([(val[0], val[1])
@@ -582,12 +583,16 @@ def close(self):
582583
# Finalize the file
583584
self.writeXref()
584585
self.writeTrailer()
586+
587+
def close(self):
588+
"Flush all buffers and free all resources."
589+
590+
self.endStream()
585591
if self.passed_in_file_object:
586592
self.fh.flush()
587-
elif self.original_file_like is not None:
588-
self.original_file_like.write(self.fh.getvalue())
589-
self.fh.close()
590593
else:
594+
if self.original_file_like is not None:
595+
self.original_file_like.write(self.fh.getvalue())
591596
self.fh.close()
592597

593598
def write(self, data):
@@ -2438,6 +2443,7 @@ def close(self):
24382443
Finalize this object, making the underlying file a complete
24392444
PDF file.
24402445
"""
2446+
self._file.finalize()
24412447
self._file.close()
24422448
if (self.get_pagecount() == 0 and not self.keep_empty and
24432449
not self._file.passed_in_file_object):
@@ -2534,6 +2540,7 @@ def print_pdf(self, filename, **kwargs):
25342540
bbox_inches_restore=_bbox_inches_restore)
25352541
self.figure.draw(renderer)
25362542
renderer.finalize()
2543+
file.finalize()
25372544
finally:
25382545
if isinstance(filename, PdfPages): # finish off this page
25392546
file.endStream()

0 commit comments

Comments
 (0)