File tree Expand file tree Collapse file tree 1 file changed +18
-0
lines changed Expand file tree Collapse file tree 1 file changed +18
-0
lines changed Original file line number Diff line number Diff line change 3535from datetime import datetime
3636from io import BytesIO , FileIO , UnsupportedOperation
3737from pathlib import Path
38+ from types import TracebackType
3839from typing import (
3940 Any ,
4041 Callable ,
4546 Mapping ,
4647 Optional ,
4748 Tuple ,
49+ Type ,
4850 Union ,
4951 cast ,
5052)
@@ -312,8 +314,10 @@ def __init__(
312314 __name__ ,
313315 )
314316
317+ self ._we_opened = False
315318 if isinstance (stream , (str , Path )):
316319 stream = FileIO (stream , "rb" )
320+ self ._we_opened = True
317321 weakref .finalize (self , stream .close )
318322
319323 self .read (stream )
@@ -349,6 +353,20 @@ def close(self) -> None:
349353 """Close the underlying file handle"""
350354 self .stream .close ()
351355
356+ def __enter__ (self ) -> "PdfReader" :
357+ """Use PdfReader as context manager"""
358+ return self
359+
360+ def __exit__ (
361+ self ,
362+ exc_type : Optional [Type [BaseException ]],
363+ exc : Optional [BaseException ],
364+ traceback : Optional [TracebackType ],
365+ ) -> None :
366+ """Write data to the fileobj."""
367+ if self ._we_opened :
368+ self .close ()
369+
352370 @property
353371 def root_object (self ) -> DictionaryObject :
354372 """Provide access to "/Root". standardized with PdfWriter."""
You can’t perform that action at this time.
0 commit comments