import tkinter as tk
from tkinter.scrolledtext import ScrolledText
import fitz


class PDFViewer(ScrolledText):
    """
    Tkinter widget for displaying PDF files as rendered page images.

    Inherits from ScrolledText and renders each PDF page as a PhotoImage.
    """

    images = None

    def show(self, pdf_file):
        """
        Render and display all pages of a PDF file.

        Args:
            pdf_file: Path to the PDF file to display.
        """
        self.delete("1.0", "end")  # clear current content
        pdf = fitz.open(pdf_file)  # open the PDF file
        self.images = []  # for storing the page images
        for page in pdf:
            pix = page.get_pixmap()
            pix1 = fitz.Pixmap(pix, 0) if pix.alpha else pix
            photo = tk.PhotoImage(data=pix1.tobytes("ppm"))
            # insert into the text box
            self.image_create("end", image=photo)
            self.insert("end", "\n")
            # save the image to avoid garbage collected
            self.images.append(photo)
