def check_add_page()

in gemini/sample-apps/accelerating_product_innovation/app/pages_utils/pdf_generation.py [0:0]


def check_add_page(pdf: pdf_generator, text: str) -> list[str]:
    """Checks if the text overflows onto a new page and adds a new page if
      necessary.

    The text is split into lines based on the available page width.
    If the text overflows onto a new page, a new page is added and the text
    is continued on the new page.

    Args:
        pdf: The PDF document to which the text is added.
        text: The text to be added to the PDF document.

    Returns:
        A list of strings, where each page is a string containing the text
        that fits on that page.
    """

    pages: list[str] = []  # Store the text content for each page
    page_content = ""  # Text for the current page being built

    pdf.set_font("Arial", "", 11)

    # Split the text into lines based on the available page width
    lines = []
    y = pdf.y

    for line in text.split("\n"):
        words = line.split(" ")
        current_line = ""  # Represents a single line within the page

        for word in words:
            # Check if adding the word would exceed the line limit
            if len(current_line + word) > pdf.w - pdf.l_margin - pdf.r_margin:
                lines.append(current_line)
                page_content += current_line + "\n"
                current_line = ""  # Reset for the next line
            current_line += word + " "

        if current_line:
            lines.append(current_line)
            # Check if adding the line would overflow the page
            if y + 10 > pdf.h - (80 if len(pages) == 0 else 0):
                pages.append(page_content)  # Add the new page to the PDF
                page_content = current_line + "\n"  # Start a new page
                y = 10
            else:
                # Add the completed line to the current page
                page_content += current_line + "\n"
            y += 10

    # Add any remaining text to the final page
    pages.append(page_content)
    return pages