63
63
StreamType ,
64
64
_get_max_pdf_version_header ,
65
65
deprecate ,
66
+ deprecate_no_replacement ,
66
67
deprecation_with_replacement ,
67
68
logger_warning ,
68
69
)
@@ -236,10 +237,9 @@ def _get_clone_from(
236
237
or Path (str (fileobj )).stat ().st_size == 0
237
238
):
238
239
cloning = False
239
- if isinstance (fileobj , (IO , BytesIO )):
240
+ if isinstance (fileobj , (IOBase , BytesIO )):
240
241
t = fileobj .tell ()
241
- fileobj .seek (- 1 , 2 )
242
- if fileobj .tell () == 0 :
242
+ if fileobj .seek (0 , 2 ) == 0 :
243
243
cloning = False
244
244
fileobj .seek (t , 0 )
245
245
if cloning :
@@ -250,7 +250,8 @@ def _get_clone_from(
250
250
# to prevent overwriting
251
251
self .temp_fileobj = fileobj
252
252
self .fileobj = ""
253
- self .with_as_usage = False
253
+ self ._with_as_usage = False
254
+ self ._cloned = False
254
255
# The root of our page tree node.
255
256
pages = DictionaryObject ()
256
257
pages .update (
@@ -268,6 +269,7 @@ def _get_clone_from(
268
269
if not isinstance (clone_from , PdfReader ):
269
270
clone_from = PdfReader (clone_from )
270
271
self .clone_document_from_reader (clone_from )
272
+ self ._cloned = True
271
273
else :
272
274
self ._pages = self ._add_object (pages )
273
275
# root object
@@ -355,11 +357,23 @@ def xmp_metadata(self, value: Optional[XmpInformation]) -> None:
355
357
356
358
return self .root_object .xmp_metadata # type: ignore
357
359
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
+
358
370
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
360
373
t = self .temp_fileobj
361
374
self .__init__ () # type: ignore
362
- self .with_as_usage = True
375
+ self ._cloned = c
376
+ self ._with_as_usage = True
363
377
self .fileobj = t # type: ignore
364
378
return self
365
379
@@ -370,7 +384,7 @@ def __exit__(
370
384
traceback : Optional [TracebackType ],
371
385
) -> None :
372
386
"""Write data to the fileobj."""
373
- if self .fileobj :
387
+ if self .fileobj and not self . _cloned :
374
388
self .write (self .fileobj )
375
389
376
390
def _repr_mimebundle_ (
@@ -1406,13 +1420,14 @@ def write(self, stream: Union[Path, StrByteType]) -> Tuple[bool, IO[Any]]:
1406
1420
1407
1421
if isinstance (stream , (str , Path )):
1408
1422
stream = FileIO (stream , "wb" )
1409
- self .with_as_usage = True
1410
1423
my_file = True
1411
1424
1412
1425
self .write_stream (stream )
1413
1426
1414
- if self . with_as_usage :
1427
+ if my_file :
1415
1428
stream .close ()
1429
+ else :
1430
+ stream .flush ()
1416
1431
1417
1432
return my_file , stream
1418
1433
0 commit comments