@@ -168,7 +168,7 @@ def is_encrypted(self) -> bool:
168
168
169
169
def __init__ (
170
170
self ,
171
- fileobj : StrByteType = "" ,
171
+ fileobj : Union [ None , PdfReader , StrByteType , Path ] = "" ,
172
172
clone_from : Union [None , PdfReader , StrByteType , Path ] = None ,
173
173
) -> None :
174
174
self ._header = b"%PDF-1.3"
@@ -213,12 +213,41 @@ def __init__(
213
213
)
214
214
self ._root = self ._add_object (self ._root_object )
215
215
216
+ def _get_clone_from (
217
+ fileobj : Union [None , PdfReader , str , Path , IO [Any ], BytesIO ],
218
+ clone_from : Union [None , PdfReader , str , Path , IO [Any ], BytesIO ],
219
+ ) -> Union [None , PdfReader , str , Path , IO [Any ], BytesIO ]:
220
+ if not isinstance (fileobj , (str , Path , IO , BytesIO )) or (
221
+ fileobj != "" and clone_from is None
222
+ ):
223
+ cloning = True
224
+ if not (
225
+ not isinstance (fileobj , (str , Path ))
226
+ or (
227
+ Path (str (fileobj )).exists ()
228
+ and Path (str (fileobj )).stat ().st_size > 0
229
+ )
230
+ ):
231
+ cloning = False
232
+ if isinstance (fileobj , (IO , BytesIO )):
233
+ t = fileobj .tell ()
234
+ fileobj .seek (- 1 , 2 )
235
+ if fileobj .tell () == 0 :
236
+ cloning = False
237
+ fileobj .seek (t , 0 )
238
+ if cloning :
239
+ clone_from = fileobj
240
+ return clone_from
241
+
242
+ clone_from = _get_clone_from (fileobj , clone_from )
243
+ # to prevent overwriting
244
+ self .temp_fileobj = fileobj
245
+ self .fileobj = ""
246
+ self .with_as_usage = False
216
247
if clone_from is not None :
217
248
if not isinstance (clone_from , PdfReader ):
218
249
clone_from = PdfReader (clone_from )
219
250
self .clone_document_from_reader (clone_from )
220
- self .fileobj = fileobj
221
- self .with_as_usage = False
222
251
223
252
self ._encryption : Optional [Encryption ] = None
224
253
self ._encrypt_entry : Optional [DictionaryObject ] = None
@@ -268,7 +297,10 @@ def xmp_metadata(self, value: Optional[XmpInformation]) -> None:
268
297
269
298
def __enter__ (self ) -> "PdfWriter" :
270
299
"""Store that writer is initialized by 'with'."""
300
+ t = self .temp_fileobj
301
+ self .__init__ () # type: ignore
271
302
self .with_as_usage = True
303
+ self .fileobj = t # type: ignore
272
304
return self
273
305
274
306
def __exit__ (
0 commit comments