writer.add_page not pure? #3703
|
add_page() looks like it transfers data but actually transfers a reference. The writer silently remains dependent on the reader's file handle, violating the user's reasonable expectation that after adding a page, the reader is no longer needed. def test_writer_does_not_hold_references_to_reader_files():
reader = PdfReader(RESOURCE_ROOT / "example.pdf")
writer = PdfWriter()
for page in reader.pages:
writer.add_page(page) # Looks like a copy, but holds references back to reader file?
reader.close() # Closes the file stream that writer's pages still point to
with NamedTemporaryFile() as output_file:
writer.write(output_file) # throws exceptionThis smells to me, users will expect that add_page creates a deep copy of what it needs not a shallow one. Actual test that fails can be found in this PR. |
Replies: 2 comments 2 replies
|
Given the traceback in your PR, this is related to keeping the links working by copying them over from the source document to the destination document. As they might be split across multiple pages which are only added to the writer later, this is done during the writing process itself. If you use def test_writer_does_not_hold_references_to_reader_files():
writer = PdfWriter(clone_from=RESOURCE_ROOT / "example.pdf")
with NamedTemporaryFile() as output_file:
writer.write(output_file) # throws exceptionthere is no such problem and might be more suitable for most use cases. |
|
Yea that seems to work. It also appears to "fix" slightly broken pdf's which was the intent of what I was doing with reader/writer add_page. Can you confirm it's intended to do this? |
Given the traceback in your PR, this is related to keeping the links working by copying them over from the source document to the destination document. As they might be split across multiple pages which are only added to the writer later, this is done during the writing process itself.
If you use
there is no such problem and might be more suitable for most use cases.