From 29d8c531215b45b7ea0e009366f9959889a3c376 Mon Sep 17 00:00:00 2001 From: Robert Kearns Date: Thu, 29 Jun 2023 13:19:34 -0600 Subject: [PATCH 1/2] Bug: add_named_destination() maintains named destination list sort order Fixes #1927 --- pypdf/_writer.py | 4 ++-- tests/test_writer.py | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/pypdf/_writer.py b/pypdf/_writer.py index 598ba4305..c3b5ef0a1 100644 --- a/pypdf/_writer.py +++ b/pypdf/_writer.py @@ -1985,10 +1985,10 @@ def add_named_destination( ) dest_ref = self._add_object(dest) - nd = self.get_named_dest_root() if not isinstance(title, TextStringObject): title = TextStringObject(str(title)) - nd.extend([title, dest_ref]) + + self.add_named_destination_array(title, dest_ref) return dest_ref def addNamedDestination( diff --git a/tests/test_writer.py b/tests/test_writer.py index c5b71ebc8..709578da5 100644 --- a/tests/test_writer.py +++ b/tests/test_writer.py @@ -607,6 +607,32 @@ def test_add_named_destination(pdf_file_path): writer.write(output_stream) +def test_add_named_destination_sort_order(pdf_file_path): + """ + This test is regression test for issue #1927 + + add_named_destination() maintains the named destination list sort order + """ + writer = PdfWriter() + + assert writer.get_named_dest_root() == [] + + writer.add_blank_page(200, 200) + writer.add_named_destination("b", 0) + # "a" should be moved before "b" on insert + writer.add_named_destination("a", 0) + + root = writer.get_named_dest_root() + + assert len(root) == 4 + assert root[0] == "a", '"a" was not inserted before "b" in the named destination root' + assert root[2] == "b" + + # write "output" to pypdf-output.pdf + with open(pdf_file_path, "wb") as output_stream: + writer.write(output_stream) + + def test_add_uri(pdf_file_path): reader = PdfReader(RESOURCE_ROOT / "pdflatex-outline.pdf") writer = PdfWriter() From 2158ae0855452ccf8ddbc46c431d48335ef426af Mon Sep 17 00:00:00 2001 From: Martin Thoma Date: Fri, 30 Jun 2023 19:48:36 +0200 Subject: [PATCH 2/2] Update tests/test_writer.py --- tests/test_writer.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_writer.py b/tests/test_writer.py index 709578da5..a8925fb79 100644 --- a/tests/test_writer.py +++ b/tests/test_writer.py @@ -609,7 +609,7 @@ def test_add_named_destination(pdf_file_path): def test_add_named_destination_sort_order(pdf_file_path): """ - This test is regression test for issue #1927 + Issue #1927 does not appear. add_named_destination() maintains the named destination list sort order """