diff --git a/CHANGELOG.md b/CHANGELOG.md index 945b4bdf0..e2117b4a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ This can also be enabled programmatically with `warnings.simplefilter('default', ## [2.8.3] - Not released yet ### Fixed * [`FPDF.write_html()`](https://py-pdf.github.io/fpdf2/fpdf/fpdf.html#fpdf.fpdf.FPDF.write_html): Fixed rendering of content following `` tags; now correctly resets emphasis style post `` tag: hyperlink styling contained within the tag authority. - [Issue #1311](https://github.com/py-pdf/fpdf2/issues/1311) +* [`FPDF.add_link()`](https://py-pdf.github.io/fpdf2/fpdf/fpdf.html#fpdf.fpdf.FPDF.add_link): It is now safe to create links before adding pages with `FPDF.add_page()`. ## [2.8.2] - 2024-12-16 ### Added diff --git a/fpdf/fpdf.py b/fpdf/fpdf.py index 046b0abb0..7a0db815e 100644 --- a/fpdf/fpdf.py +++ b/fpdf/fpdf.py @@ -2219,12 +2219,15 @@ def add_link(self, y=0, x=0, page=-1, zoom="null"): x (float): optional abscissa of target position. The default value is 0 (top of page). page (int): optional number of target page. - -1 indicates the current page, which is the default value. + -1 indicates the current page (or the first page if there are no pages yet), + which is the default value. zoom (float): optional new zoom level after following the link. Currently ignored by Sumatra PDF Reader, but observed by Adobe Acrobat reader. """ + if page < 0: + page = self.page if self.page != 0 else 1 link = DestinationXYZ( - self.page if page == -1 else page, + page, top=self.h_pt - y * self.k, left=x * self.k, zoom=zoom, diff --git a/test/test_links.py b/test/test_links.py index ed24a37ef..36182a9e0 100644 --- a/test/test_links.py +++ b/test/test_links.py @@ -151,14 +151,20 @@ def test_inserting_link_to_non_exising_page(): pdf.output() -def test_inserting_link_with_no_page_number(): +def test_inserting_link_with_no_page_number(tmp_path): pdf = FPDF() - link = pdf.add_link() - pdf.add_page() - pdf.set_font("helvetica", size=12) - with pytest.raises(ValueError): - pdf.cell(text="Page 1", link=link) + pdf.set_font("helvetica") + + link_to_section1 = pdf.add_link() + + pdf.add_page() # page 1 + pdf.cell(text="Section 1", link=link_to_section1) + pdf.add_page() # page 2 + pdf.set_link(link_to_section1, page=pdf.page) + pdf.cell(text="Section 1: Bla bla bla") + + assert_pdf_equal(pdf, HERE / "later_call_to_set_link.pdf", tmp_path) def test_later_call_to_set_link(tmp_path): # v2.6.1 bug spotted in discussion 729 pdf = FPDF()