py-pdf/fpdf2

`set_page_background()` doesn't apply background colour to first page of table of contents when using `insert_toc_placeholder`

nocalla opened this issue · 2 comments

When using set_page_background to change the colour of the page background, if insert_toc_placeholder is used, the first table of contents page is not affected by the new background colour but subsequent TOC pages are. This applies even on setting the background within the render_toc_function directly.

Error details
N/A

Minimal code

from fpdf import FPDF

PLACEHOLDER_PAGES = 2


def render_toc(pdf: FPDF, outline: list) -> None:
    # pdf.set_page_background((217, 186, 156)) # test of setting directly within render_toc_function
    pdf.set_font(size=20)
    pdf.ln()
    pdf.cell(text="Test TOC page 1", align="C")
    pdf.ln()
    pdf.add_page()
    pdf.cell(text="Test TOC page 2", align="C")


PDF = FPDF()
PDF.set_font(family="helvetica", style="", size=30)
PDF.add_page()
PDF.set_page_background((217, 186, 156))
PDF.insert_toc_placeholder(
    render_toc_function=render_toc, pages=PLACEHOLDER_PAGES
)
PDF.cell(text="Test normal page.")

PDF.output("Test.pdf")

Environment
Please provide the following information:

  • Operating System: Windows 11
  • Python version: 3.12.1
  • fpdf2 version used: 2.7.8

Hi @nocalla.
Thank you for this report.

This is simply because the page background color must be set BEFORE the call to .add_page().
If you simply switch 2 lines of code, you should get what you want:

PDF = FPDF()
PDF.set_font(family="helvetica", style="", size=30)
PDF.set_page_background((217, 186, 156))
PDF.add_page()

My apologies, I misunderstood the underlying logic of the function! This tweak fixed the issue.