6363 StreamType ,
6464 _get_max_pdf_version_header ,
6565 deprecate ,
66+ deprecate_no_replacement ,
6667 deprecation_with_replacement ,
6768 logger_warning ,
6869)
@@ -236,10 +237,9 @@ def _get_clone_from(
236237 or Path (str (fileobj )).stat ().st_size == 0
237238 ):
238239 cloning = False
239- if isinstance (fileobj , (IO , BytesIO )):
240+ if isinstance (fileobj , (IOBase , BytesIO )):
240241 t = fileobj .tell ()
241- fileobj .seek (- 1 , 2 )
242- if fileobj .tell () == 0 :
242+ if fileobj .seek (0 , 2 ) == 0 :
243243 cloning = False
244244 fileobj .seek (t , 0 )
245245 if cloning :
@@ -250,7 +250,8 @@ def _get_clone_from(
250250 # to prevent overwriting
251251 self .temp_fileobj = fileobj
252252 self .fileobj = ""
253- self .with_as_usage = False
253+ self ._with_as_usage = False
254+ self ._cloned = False
254255 # The root of our page tree node.
255256 pages = DictionaryObject ()
256257 pages .update (
@@ -268,6 +269,7 @@ def _get_clone_from(
268269 if not isinstance (clone_from , PdfReader ):
269270 clone_from = PdfReader (clone_from )
270271 self .clone_document_from_reader (clone_from )
272+ self ._cloned = True
271273 else :
272274 self ._pages = self ._add_object (pages )
273275 # root object
@@ -355,11 +357,23 @@ def xmp_metadata(self, value: Optional[XmpInformation]) -> None:
355357
356358 return self .root_object .xmp_metadata # type: ignore
357359
360+ @property
361+ def with_as_usage (self ) -> bool :
362+ deprecate_no_replacement ("with_as_usage" , "6.0" )
363+ return self ._with_as_usage
364+
365+ @with_as_usage .setter
366+ def with_as_usage (self , value : bool ) -> None :
367+ deprecate_no_replacement ("with_as_usage" , "6.0" )
368+ self ._with_as_usage = value
369+
358370 def __enter__ (self ) -> "PdfWriter" :
359- """Store that writer is initialized by 'with'."""
371+ """Store how writer is initialized by 'with'."""
372+ c : bool = self ._cloned
360373 t = self .temp_fileobj
361374 self .__init__ () # type: ignore
362- self .with_as_usage = True
375+ self ._cloned = c
376+ self ._with_as_usage = True
363377 self .fileobj = t # type: ignore
364378 return self
365379
@@ -370,7 +384,7 @@ def __exit__(
370384 traceback : Optional [TracebackType ],
371385 ) -> None :
372386 """Write data to the fileobj."""
373- if self .fileobj :
387+ if self .fileobj and not self . _cloned :
374388 self .write (self .fileobj )
375389
376390 def _repr_mimebundle_ (
@@ -1406,13 +1420,14 @@ def write(self, stream: Union[Path, StrByteType]) -> Tuple[bool, IO[Any]]:
14061420
14071421 if isinstance (stream , (str , Path )):
14081422 stream = FileIO (stream , "wb" )
1409- self .with_as_usage = True
14101423 my_file = True
14111424
14121425 self .write_stream (stream )
14131426
1414- if self . with_as_usage :
1427+ if my_file :
14151428 stream .close ()
1429+ else :
1430+ stream .flush ()
14161431
14171432 return my_file , stream
14181433
0 commit comments