@@ -64,9 +64,11 @@ def __init__(
6464 debug = False ,
6565 ):
6666 self .debug = debug
67+ self .is_temp_file = is_url (filepath )
6768 if is_url (filepath ):
68- filepath = download_url (str (filepath ))
69- self .filepath : StrByteType | Path | str = filepath
69+ self .filepath = download_url (str (filepath ))
70+ else :
71+ self .filepath : StrByteType | Path | str = filepath
7072
7173 if isinstance (filepath , str ) and not filepath .lower ().endswith (".pdf" ):
7274 raise NotImplementedError ("File format not supported" )
@@ -77,6 +79,41 @@ def __init__(
7779 self .password = password
7880 self .pages = self ._get_pages (pages )
7981
82+ def __enter__ (self ):
83+ """Enter the context manager.
84+
85+ Returns
86+ -------
87+ PDFHandler
88+ The instance itself.
89+ """
90+ return self
91+
92+ def __exit__ (self , exc_type , exc_val , exc_tb ):
93+ """Exit the context manager and clean up temporary files.
94+
95+ Deletes the temporary file if it was created from a URL.
96+
97+ Parameters
98+ ----------
99+ exc_type : type or None
100+ Type of the exception raised in the context, if any.
101+ exc_val : Exception or None
102+ The exception instance raised, if any.
103+ exc_tb : traceback or None
104+ The traceback of the exception, if any.
105+ """
106+ if self .is_temp_file and os .path .exists (self .filepath ): # type: ignore
107+ os .remove (self .filepath ) # type: ignore
108+
109+ def close (self ):
110+ """Close the handler and clean up temporary files.
111+
112+ Deletes the temporary file if it was created from a URL.
113+ """
114+ if self .is_temp_file and os .path .exists (self .filepath ): # type: ignore
115+ os .remove (self .filepath ) # type: ignore
116+
80117 def _get_pages (self , pages ):
81118 """Convert pages string to list of integers.
82119
0 commit comments