verifica se o seguinte código está completo e funcional: import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from PyPDF2 import PdfReader, PdfWriter, PdfMerger
from pdf2docx import Converter
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
import os
from PIL import Image, ImageTk
import shutil
import time
from pptx import Presentation
from tkinterdnd2 import *
import io
import tempfile
from pdf2image import convert_from_path

class BPFomentoPDFEditor:
    def __init__(self, root):
        self.root = root
        self.root.title("BPFomento PDF Editor")
        self.root.geometry("900x600")
        self.root.configure(bg="#f0f2f5")
        self.undo_stack = []  # Para suporte a undo
        self.current_file = None  # Arquivo atual para pré-visualização

        # Estilo moderno
        style = ttk.Style()
        style.configure("Custom.Horizontal.TProgressbar", troughcolor="#d9e1e8", background="#4CAF50")
        style.configure("Treeview", font=("Helvetica", 10), rowheight=40)
        style.configure("Treeview.Heading", font=("Helvetica", 12, "bold"))

        self.show_splash_screen()
        self.create_layout()

        self.root.drop_target_register(DND_FILES)
        self.root.dnd_bind('<<Drop>>', self.handle_drop)

    def show_splash_screen(self):
        splash = tk.Toplevel(self.root)
        splash.geometry("300x100")
        splash.overrideredirect(True)
        splash.attributes("-topmost", True)
        splash.configure(bg="#ffffff")
        splash.update_idletasks()
        width, height = splash.winfo_screenwidth(), splash.winfo_screenheight()
        x, y = (width // 2 - 150), (height // 2 - 50)
        splash.geometry(f"300x100+{x}+{y}")

        tk.Label(splash, text="BPFomento PDF Editor", font=("Helvetica", 20, "bold"), bg="#ffffff", fg="#333333").pack(expand=True)
        self.root.update()
        time.sleep(2)
        splash.destroy()

    def create_layout(self):
        # Barra superior (toolbar)
        toolbar = tk.Frame(self.root, bg="#ffffff", height=50, bd=1, relief="sunken")
        toolbar.pack(side="top", fill="x")

        # Botões da toolbar
        tk.Button(toolbar, text="Light Theme", command=lambda: self.switch_theme("light"), bg="#ffffff", fg="#333333", font=("Helvetica", 10), bd=0).pack(side="left", padx=5)
        tk.Button(toolbar, text="Dark Theme", command=lambda: self.switch_theme("dark"), bg="#ffffff", fg="#333333", font=("Helvetica", 10), bd=0).pack(side="left", padx=5)
        tk.Button(toolbar, text="Undo", command=self.undo_action, bg="#ffffff", fg="#333333", font=("Helvetica", 10), bd=0).pack(side="left", padx=5)

        # Frame principal
        main_frame = tk.Frame(self.root, bg="#f0f2f5")
        main_frame.pack(fill="both", expand=True)

        # Barra lateral
        sidebar = tk.Frame(main_frame, width=200, bg="#ffffff", bd=1, relief="sunken")
        sidebar.pack(side="left", fill="y")

        # Árvore de navegação na sidebar
        tree = ttk.Treeview(sidebar, show="tree", style="Treeview")
        tree.pack(fill="y", expand=True)

        # Categorias na sidebar
        categories = {
            "Split Tools": ["Extract", "Split", "Split by bookmarks", "Split by size"],
            "Merge Tools": ["Alternate Mix", "Insert pages multiple times", "Merge"],
            "Edit Tools": ["Edit Text", "Extract Text", "Organize pages", "Delete pages", "Crop", "Rotate"],
            "Security Tools": ["Encrypt/Decrypt", "Add Watermark", "Add Background", "Attach Files", "Extract Attachments"],
            "Other Tools": ["Fill Forms", "Convert", "Create from Images"]
        }

        for category, tools in categories.items():
            parent = tree.insert("", "end", text=category, open=True)
            for tool in tools:
                tree.insert(parent, "end", text=tool, values=(tool,))

        tree.bind("<<TreeviewSelect>>", self.on_tree_select)

        # Área principal
        self.content_frame = tk.Frame(main_frame, bg="#f0f2f5")
        self.content_frame.pack(side="right", fill="both", expand=True, padx=20, pady=20)

        self.show_home_page()

    def switch_theme(self, theme):
        if theme == "light":
            self.root.configure(bg="#f0f2f5")
            self.content_frame.configure(bg="#f0f2f5")
        elif theme == "dark":
            self.root.configure(bg="#2d2d2d")
            self.content_frame.configure(bg="#2d2d2d")

    def show_home_page(self):
        for widget in self.content_frame.winfo_children():
            widget.destroy()

        tk.Label(self.content_frame, text="BPFomento PDF Editor", font=("Helvetica", 20, "bold"), bg="#f0f2f5", fg="#333333").pack(pady=10)

        # Categorias e blocos
        categories = {
            "Split Tools": [
                ("Extract", "Extract pages from PDF documents.", self.extract_pages, "#ff6f61"),
                ("Split", "Split a PDF document at the given page numbers.", self.split_pdf, "#ff6f61"),
                ("Split by bookmarks", "Split a PDF document at bookmarked pages.", self.split_by_bookmarks, "#ff6f61"),
                ("Split by size", "Split a PDF document into files of the given size.", self.split_by_size, "#ff6f61"),
            ],
            "Merge Tools": [
                ("Alternate Mix", "Merge two PDFs, taking pages alternately.", self.alternate_mix, "#ab47bc"),
                ("Insert pages multiple times", "Insert pages of a PDF into another, repeating.", self.insert_pages, "#ab47bc"),
                ("Merge", "Merge multiple PDF documents.", self.merge_pdfs, "#ab47bc"),
            ],
            "Edit Tools": [
                ("Edit Text", "Edit text directly in the PDF.", self.edit_pdf, "#42a5f5"),
                ("Extract Text", "Extract text from the PDF.", self.extract_text, "#42a5f5"),
                ("Organize pages", "Rearrange, add, or delete pages.", self.organize_pages, "#42a5f5"),
                ("Delete pages", "Delete specific pages from a PDF.", self.delete_pages, "#42a5f5"),
                ("Crop", "Crop pages with specific values.", self.crop_pages, "#42a5f5"),
                ("Rotate", "Rotate pages of PDF documents.", self.rotate_pages, "#42a5f5"),
            ],
            "Security Tools": [
                ("Encrypt/Decrypt", "Add or remove passwords and permissions.", self.encrypt_decrypt, "#ffca28"),
                ("Add Watermark", "Add a watermark to the PDF.", self.add_watermark, "#ffca28"),
                ("Add Background", "Apply a background to PDF pages.", self.add_background, "#ffca28"),
                ("Attach Files", "Attach files to the PDF.", self.attach_files, "#ffca28"),
                ("Extract Attachments", "Extract attachments from the PDF.", self.extract_attachments, "#ffca28"),
            ],
            "Other Tools": [
                ("Fill Forms", "Fill PDF forms.", self.fill_forms, "#66bb6a"),
                ("Convert", "Convert PDFs to other formats.", self.convert_to_ppt, "#66bb6a"),
                ("Create from Images", "Create PDFs from images.", self.create_pdf_from_images, "#66bb6a"),
            ]
        }

        for category, tools in categories.items():
            tk.Label(self.content_frame, text=category, font=("Helvetica", 16, "bold"), bg="#f0f2f5", fg="#333333").pack(anchor="w", pady=10)
            frame = tk.Frame(self.content_frame, bg="#f0f2f5")
            frame.pack(fill="x", pady=5)
            for name, desc, command, color in tools:
                btn_frame = tk.Frame(frame, bg="#ffffff", bd=1, relief="flat", width=200, height=100)
                btn_frame.pack(side="left", padx=10, pady=5)
                btn_frame.pack_propagate(False)
                tk.Label(btn_frame, text="🔧", font=("Helvetica", 20), bg="#ffffff").pack(pady=5)  # Ícone placeholder
                tk.Label(btn_frame, text=name, font=("Helvetica", 12, "bold"), bg="#ffffff", fg="#333333").pack()
                tk.Label(btn_frame, text=desc, font=("Helvetica", 8), bg="#ffffff", fg="#666666", wraplength=180).pack()
                btn_frame.bind("<Button-1>", lambda e, cmd=command: cmd())
                btn_frame.bind("<Enter>", lambda e, bf=btn_frame: bf.configure(bg="#e0e0e0"))
                btn_frame.bind("<Leave>", lambda e, bf=btn_frame: bf.configure(bg="#ffffff"))

    def on_tree_select(self, event):
        tree = event.widget
        selection = tree.selection()
        if not selection:
            return
        item = tree.item(selection[0])
        value = item.get("values")
        if value:
            tool = value[0]
            self.show_home_page()

    def center_window(self, window, width, height):
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        x = (screen_width // 2) - (width // 2)
        y = (screen_height // 2) - (height // 2)
        window.geometry(f"{width}x{height}+{x}+{y}")
        window.attributes("-alpha", 0)
        self.fade_in(window)

    def fade_in(self, window, alpha=0):
        alpha += 0.1
        if alpha >= 1:
            window.attributes("-alpha", 1)
            return
        window.attributes("-alpha", alpha)
        window.after(50, lambda: self.fade_in(window, alpha))

    def fade_out(self, window, alpha=1):
        alpha -= 0.1
        if alpha <= 0:
            window.destroy()
            return
        window.attributes("-alpha", alpha)
        window.after(50, lambda: self.fade_out(window, alpha))

    def get_file(self, title="Select PDF", multiple=False, filetypes=[("PDF files", "*.pdf")]):
        if multiple:
            return filedialog.askopenfilenames(title=title, filetypes=filetypes)
        return filedialog.askopenfilename(title=title, filetypes=filetypes)

    def save_file(self, title="Save PDF", defaultextension=".pdf", filetypes=[("PDF files", "*.pdf")]):
        return filedialog.asksaveasfilename(defaultextension=defaultextension, filetypes=filetypes)

    def show_progress(self, total_steps):
        progress_window = tk.Toplevel(self.root)
        self.center_window(progress_window, 300, 100)
        progress_window.title("Processing...")
        progress_window.configure(bg="#ffffff")
        tk.Label(progress_window, text="Processing...", font=("Helvetica", 12), bg="#ffffff", fg="#333333").pack(pady=10)
        progress_bar = ttk.Progressbar(progress_window, length=250, mode='determinate', style="Custom.Horizontal.TProgressbar")
        progress_bar.pack(pady=10)
        progress_bar['maximum'] = total_steps
        progress_bar['value'] = 0
        self.root.update()
        return progress_window, progress_bar

    def update_progress(self, progress_bar, step):
        progress_bar['value'] += step
        self.root.update()

    def hide_progress(self, progress_window):
        self.fade_out(progress_window)

    def save_for_undo(self, file_path):
        if file_path:
            temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf").name
            shutil.copy(file_path, temp_file)
            self.undo_stack.append(temp_file)

    def undo_action(self):
        if not self.undo_stack:
            messagebox.showinfo("Info", "Nothing to undo.")
            return
        last_file = self.undo_stack.pop()
        if self.current_file:
            shutil.copy(last_file, self.current_file)
            os.remove(last_file)
            messagebox.showinfo("Success", "Action undone successfully!")

    def show_preview(self, file_path, preview_label):
        if not file_path:
            return
        try:
            images = convert_from_path(file_path, first_page=1, last_page=1)
            if images:
                img = images[0]
                img = img.resize((100, 100), Image.Resampling.LANCZOS)
                photo = ImageTk.PhotoImage(img)
                preview_label.configure(image=photo)
                preview_label.image = photo
        except Exception as e:
            messagebox.showwarning("Warning", f"Could not load preview: {str(e)}")
            img = Image.new('RGB', (100, 100), color='white')
            img = img.resize((100, 100))
            photo = ImageTk.PhotoImage(img)
            preview_label.configure(image=photo)
            preview_label.image = photo

    def parse_pages(self, pages_str, total_pages):
        if not pages_str:
            return []
        pages = []
        parts = pages_str.replace(" ", "").split(",")
        for part in parts:
            if "-" in part:
                start, end = map(int, part.split("-"))
                if start < 1 or end > total_pages or start > end:
                    return []
                pages.extend(range(start, end + 1))
            else:
                page = int(part)
                if page < 1 or page > total_pages:
                    return []
                pages.append(page)
        return pages

    def handle_drop(self, event):
        files = self.root.tk.splitlist(event.data)
        if files:
            messagebox.showinfo("Dropped Files", f"Files dropped: {files}")

    def extract_pages(self):
        file = self.get_file()
        if not file:
            return
        self.current_file = file
        self.save_for_undo(file)
        reader = PdfReader(file)
        window = tk.Toplevel(self.root)
        window.title("Extract Pages")
        window.configure(bg="#ffffff")
        self.center_window(window, 400, 350)

        tk.Label(window, text="Extract Pages", font=("Helvetica", 14, "bold"), bg="#ffffff", fg="#333333").pack(pady=10)
        tk.Label(window, text=f"Total Pages: {len(reader.pages)}", font=("Helvetica", 10), bg="#ffffff", fg="#666666").pack(pady=5)
        tk.Label(window, text="Enter pages (e.g., 1-3, 5):", font=("Helvetica", 10), bg="#ffffff", fg="#333333").pack(pady=5)
        entry = tk.Entry(window, width=30, font=("Helvetica", 10), bd=1, relief="solid")
        entry.pack(pady=5)

        # Validação em tempo real
        error_label = tk.Label(window, text="", font=("Helvetica", 8), bg="#ffffff", fg="red")
        error_label.pack(pady=5)
        def validate_pages(*args):
            pages = entry.get()
            if not pages:
                error_label.config(text="")
                return
            try:
                page_list = self.parse_pages(pages, len(reader.pages))
                if not page_list:
                    error_label.config(text="Invalid page range.")
                else:
                    error_label.config(text="")
            except:
                error_label.config(text="Invalid format.")
        entry.bind("<KeyRelease>", validate_pages)

        # Pré-visualização
        preview_label = tk.Label(window, bg="#ffffff")
        preview_label.pack(pady=5)
        self.show_preview(file, preview_label)

        def process():
            pages = entry.get()
            if not pages:
                messagebox.showwarning("Warning", "Please enter page numbers.")
                return
            page_list = self.parse_pages(pages, len(reader.pages))
            if not page_list:
                messagebox.showwarning("Warning", "Invalid page range.")
                return
            progress_window, progress_bar = self.show_progress(len(page_list))
            writer = PdfWriter()
            for i, page in enumerate(page_list, 1):
                writer.add_page(reader.pages[page-1])
                self.update_progress(progress_bar, 1)
            output = self.save_file()
            if output:
                with open(output, 'wb') as f:
                    writer.write(f)
                self.hide_progress(progress_window)
                window.destroy()
                messagebox.showinfo("Success", "Pages extracted successfully!")

        tk.Button(window, text="Extract", command=process, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"), 
                  bd=0, relief="flat", activebackground="#45a049", cursor="hand2").pack(pady=20)
        tk.Button(window, text="?", command=lambda: messagebox.showinfo("Help", "Enter page numbers to extract (e.g., 1-3, 5). Use commas to separate ranges."), 
                  bg="#d9e1e8", fg="#333333", font=("Helvetica", 8), bd=0).pack(side="bottom", pady=5)
        window.transient(self.root)
        window.grab_set()

    def split_pdf(self):
        file = self.get_file()
        if not file:
            return
        self.current_file = file
        self.save_for_undo(file)
        reader = PdfReader(file)
        window = tk.Toplevel(self.root)
        window.title("Split PDF")
        window.configure(bg="#ffffff")
        self.center_window(window, 400, 350)

        tk.Label(window, text="Split PDF", font=("Helvetica", 14, "bold"), bg="#ffffff", fg="#333333").pack(pady=10)
        tk.Label(window, text=f"Total Pages: {len(reader.pages)}", font=("Helvetica", 10), bg="#ffffff", fg="#666666").pack(pady=5)
        tk.Label(window, text="Split at page numbers (e.g., 1, 3, 5):", font=("Helvetica", 10), bg="#ffffff", fg="#333333").pack(pady=5)
        entry = tk.Entry(window, width=30, font=("Helvetica", 10), bd=1, relief="solid")
        entry.pack(pady=5)

        # Validação em tempo real
        error_label = tk.Label(window, text="", font=("Helvetica", 8), bg="#ffffff", fg="red")
        error_label.pack(pady=5)
        def validate_pages(*args):
            pages = entry.get()
            if not pages:
                error_label.config(text="")
                return
            try:
                page_list = self.parse_pages(pages, len(reader.pages))
                if not page_list:
                    error_label.config(text="Invalid page range.")
                else:
                    error_label.config(text="")
            except:
                error_label.config(text="Invalid format.")
        entry.bind("<KeyRelease>", validate_pages)

        def process():
            pages = entry.get()
            if not pages:
                output_dir = filedialog.askdirectory(title="Select Output Directory")
                if not output_dir:
                    return
                progress_window, progress_bar = self.show_progress(len(reader.pages))
                for i, page in enumerate(reader.pages, 1):
                    writer = PdfWriter()
                    writer.add_page(page)
                    with open(f"{output_dir}/page_{i}.pdf", 'wb') as f:
                        writer.write(f)
                    self.update_progress(progress_bar, 1)
                self.hide_progress(progress_window)
                window.destroy()
                messagebox.showinfo("Success", "PDF split successfully!")
                return
            page_list = sorted(set(self.parse_pages(pages, len(reader.pages))))
            if not page_list:
                messagebox.showwarning("Warning", "Invalid page range.")
                return
            output_dir = filedialog.askdirectory(title="Select Output Directory")
            if not output_dir:
                return
            progress_window, progress_bar = self.show_progress(len(page_list) + 1)
            start = 1
            for i, split_page in enumerate(page_list, 1):
                writer = PdfWriter()
                for page_num in range(start, split_page + 1):
                    writer.add_page(reader.pages[page_num - 1])
                with open(f"{output_dir}/part_{i}.pdf", 'wb') as f:
                    writer.write(f)
                start = split_page + 1
                self.update_progress(progress_bar, 1)
            if start <= len(reader.pages):
                writer = PdfWriter()
                for page_num in range(start, len(reader.pages) + 1):
                    writer.add_page(reader.pages[page_num - 1])
                with open(f"{output_dir}/part_{len(page_list) + 1}.pdf", 'wb') as f:
                    writer.write(f)
                self.update_progress(progress_bar, 1)
            self.hide_progress(progress_window)
            window.destroy()
            messagebox.showinfo("Success", "PDF split successfully!")

        tk.Button(window, text="Split", command=process, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"), 
                  bd=0, relief="flat", activebackground="#45a049", cursor="hand2").pack(pady=20)
        tk.Button(window, text="?", command=lambda: messagebox.showinfo("Help", "Enter page numbers to split at (e.g., 1, 3, 5). Leave empty to split into individual pages."), 
                  bg="#d9e1e8", fg="#333333", font=("Helvetica", 8), bd=0).pack(side="bottom", pady=5)
        window.transient(self.root)
        window.grab_set()

    def split_by_bookmarks(self):
        file = self.get_file()
        if not file:
            return
        self.current_file = file
        self.save_for_undo(file)
        reader = PdfReader(file)
        window = tk.Toplevel(self.root)
        window.title("Split by Bookmarks")
        window.configure(bg="#ffffff")
        self.center_window(window, 400, 300)

        tk.Label(window, text="Split by Bookmarks", font=("Helvetica", 14, "bold"), bg="#ffffff", fg="#333333").pack(pady=10)
        tk.Label(window, text=f"Total Pages: {len(reader.pages)}", font=("Helvetica", 10), bg="#ffffff", fg="#666666").pack(pady=5)
        tk.Label(window, text="Bookmark Level:", font=("Helvetica", 10), bg="#ffffff", fg="#333333").pack(pady=5)
        level_entry = tk.Entry(window, width=10, font=("Helvetica", 10), bd=1, relief="solid")
        level_entry.pack(pady=5)
        level_entry.insert(0, "1")

        def process():
            try:
                level = int(level_entry.get())
                if level < 1:
                    messagebox.showwarning("Warning", "Bookmark level must be at least 1.")
                    return
            except ValueError:
                messagebox.showwarning("Warning", "Please enter a valid number.")
                return
            outlines = reader.outline
            if not outlines:
                messagebox.showwarning("Warning", "No bookmarks found in the PDF.")
                return
            bookmark_pages = []
            def parse_outlines(outlines, current_level=1):
                for outline in outlines:
                    if isinstance(outline, list):
                        parse_outlines(outline, current_level + 1)
                    else:
                        if current_level == level:
                            page_num = reader.get_page_number(reader.get_destination_page(outline))
                            bookmark_pages.append((outline['/Title'], page_num))
            parse_outlines(outlines)
            if not bookmark_pages:
                messagebox.showwarning("Warning", f"No bookmarks found at level {level}.")
                return
            bookmark_pages.sort(key=lambda x: x[1])
            output_dir = filedialog.askdirectory(title="Select Output Directory")
            if not output_dir:
                return
            progress_window, progress_bar = self.show_progress(len(bookmark_pages) + 1)
            start = 0
            for i, (title, page_num) in enumerate(bookmark_pages, 1):
                writer = PdfWriter()
                for p in range(start, page_num + 1):
                    writer.add_page(reader.pages[p])
                output_file = f"{output_dir}/{title.replace('/', '_')}.pdf"
                with open(output_file, 'wb') as f:
                    writer.write(f)
                start = page_num + 1
                self.update_progress(progress_bar, 1)
            if start < len(reader.pages):
                writer = PdfWriter()
                for p in range(start, len(reader.pages)):
                    writer.add_page(reader.pages[p])
                with open(f"{output_dir}/remaining_pages.pdf", 'wb') as f:
                    writer.write(f)
                self.update_progress(progress_bar, 1)
            self.hide_progress(progress_window)
            window.destroy()
            messagebox.showinfo("Success", "PDF split by bookmarks successfully!")

        tk.Button(window, text="Split", command=process, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"), 
                  bd=0, relief="flat", activebackground="#45a049", cursor="hand2").pack(pady=20)
        tk.Button(window, text="?", command=lambda: messagebox.showinfo("Help", "Enter the bookmark level to split at (e.g., 1 for top-level bookmarks)."), 
                  bg="#d9e1e8", fg="#333333", font=("Helvetica", 8), bd=0).pack(side="bottom", pady=5)
        window.transient(self.root)
        window.grab_set()

    def split_by_size(self):
        file = self.get_file()
        if not file:
            return
        self.current_file = file
        self.save_for_undo(file)
        window = tk.Toplevel(self.root)
        window.title("Split by Size")
        window.configure(bg="#ffffff")
        self.center_window(window, 350, 200)
        tk.Label(window, text="Split by Size", font=("Helvetica", 14, "bold"), bg="#ffffff", fg="#333333").pack(pady=10)
        tk.Label(window, text="Enter max size per file (MB):", font=("Helvetica", 10), bg="#ffffff", fg="#333333").pack(pady=5)
        entry = tk.Entry(window, width=10, font=("Helvetica", 10), bd=1, relief="solid")
        entry.pack(pady=5)
        entry.insert(0, "10")

        def process():
            try:
                max_size_mb = float(entry.get())
                if max_size_mb <= 0:
                    messagebox.showwarning("Warning", "Size must be greater than 0.")
                    return
            except ValueError:
                messagebox.showwarning("Warning", "Please enter a valid number.")
                return
            max_size = max_size_mb * 1024 * 1024
            reader = PdfReader(file)
            output_dir = filedialog.askdirectory(title="Select Output Directory")
            if not output_dir:
                return
            current_writer = PdfWriter()
            part_num = 1
            progress_window, progress_bar = self.show_progress(len(reader.pages))
            for i, page in enumerate(reader.pages, 1):
                current_writer.add_page(page)
                temp_file = f"{output_dir}/temp_part_{part_num}.pdf"
                with open(temp_file, 'wb') as f:
                    current_writer.write(f)
                if os.path.getsize(temp_file) > max_size:
                    os.remove(temp_file)
                    current_writer = PdfWriter()
                    current_writer.add_page(page)
                    part_num += 1
                    with open(f"{output_dir}/part_{part_num}.pdf", 'wb') as f:
                        current_writer.write(f)
                else:
                    os.rename(temp_file, f"{output_dir}/part_{part_num}.pdf")
                self.update_progress(progress_bar, 1)
            self.hide_progress(progress_window)
            window.destroy()
            messagebox.showinfo("Success", "PDF split by size successfully!")

        tk.Button(window, text="Split", command=process, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"), 
                  bd=0, relief="flat", activebackground="#45a049", cursor="hand2").pack(pady=20)
        tk.Button(window, text="?", command=lambda: messagebox.showinfo("Help", "Enter the maximum size (in MB) for each split file."), 
                  bg="#d9e1e8", fg="#333333", font=("Helvetica", 8), bd=0).pack(side="bottom", pady=5)
        window.transient(self.root)
        window.grab_set()

    def merge_pdfs(self):
        files = self.get_file(title="Select PDFs to Merge", multiple=True)
        if not files:
            return
        window = tk.Toplevel(self.root)
        window.title("Merge PDFs")
        window.configure(bg="#ffffff")
        self.center_window(window, 400, 200)
        tk.Label(window, text="Merge PDFs", font=("Helvetica", 14, "bold"), bg="#ffffff", fg="#333333").pack(pady=10)
        tk.Label(window, text=f"Selected Files: {len(files)}", font=("Helvetica", 10), bg="#ffffff", fg="#666666").pack(pady=5)

        def process():
            merger = PdfMerger()
            progress_window, progress_bar = self.show_progress(len(files))
            for i, file in enumerate(files, 1):
                merger.append(file)
                self.update_progress(progress_bar, 1)
            output = self.save_file()
            if output:
                self.save_for_undo(output)
                merger.write(output)
                merger.close()
                self.hide_progress(progress_window)
                window.destroy()
                messagebox.showinfo("Success", "PDFs merged successfully!")

        tk.Button(window, text="Merge", command=process, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"), 
                  bd=0, relief="flat", activebackground="#45a049", cursor="hand2").pack(pady=20)
        tk.Button(window, text="?", command=lambda: messagebox.showinfo("Help", "Select multiple PDF files to merge into a single PDF."), 
                  bg="#d9e1e8", fg="#333333", font=("Helvetica", 8), bd=0).pack(side="bottom", pady=5)
        window.transient(self.root)
        window.grab_set()

    def alternate_mix(self):
        files = self.get_file(title="Select Two PDFs to Mix", multiple=True)
        if len(files) != 2:
            messagebox.showwarning("Warning", "Please select exactly 2 PDFs.")
            return
        window = tk.Toplevel(self.root)
        window.title("Alternate Mix")
        window.configure(bg="#ffffff")
        self.center_window(window, 400, 300)
        tk.Label(window, text="Alternate Mix", font=("Helvetica", 14, "bold"), bg="#ffffff", fg="#333333").pack(pady=10)
        tk.Label(window, text="Selected Files: 2", font=("Helvetica", 10), bg="#ffffff", fg="#666666").pack(pady=5)
        tk.Label(window, text="Order:", font=("Helvetica", 10), bg="#ffffff", fg="#333333").pack(pady=5)
        order_var = tk.StringVar(value="natural")
        tk.Radiobutton(window, text="Natural Order", variable=order_var, value="natural", bg="#ffffff", fg="#333333", 
                       font=("Helvetica", 10), activebackground="#ffffff", selectcolor="#e0e0e0").pack()
        tk.Radiobutton(window, text="Reverse Order", variable=order_var, value="reverse", bg="#ffffff", fg="#333333", 
                       font=("Helvetica", 10), activebackground="#ffffff", selectcolor="#e0e0e0").pack()

        def process():
            reader1, reader2 = PdfReader(files[0]), PdfReader(files[1])
            writer = PdfWriter()
            max_pages = max(len(reader1.pages), len(reader2.pages))
            progress_window, progress_bar = self.show_progress(max_pages)
            if order_var.get() == "natural":
                for i in range(max_pages):
                    if i < len(reader1.pages):
                        writer.add_page(reader1.pages[i])
                    if i < len(reader2.pages):
                        writer.add_page(reader2.pages[i])
                    self.update_progress(progress_bar, 1)
            else:
                for i in range(max_pages):
                    if i < len(reader2.pages):
                        writer.add_page(reader2.pages[i])
                    if i < len(reader1.pages):
                        writer.add_page(reader1.pages[i])
                    self.update_progress(progress_bar, 1)
            output = self.save_file()
            if output:
                self.save_for_undo(output)
                with open(output, 'wb') as f:
                    writer.write(f)
                self.hide_progress(progress_window)
                window.destroy()
                messagebox.showinfo("Success", "PDFs mixed alternately successfully!")

        tk.Button(window, text="Mix", command=process, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"), 
                  bd=0, relief="flat", activebackground="#45a049", cursor="hand2").pack(pady=20)
        tk.Button(window, text="?", command=lambda: messagebox.showinfo("Help", "Select two PDFs to mix alternately. Choose the order of pages."), 
                  bg="#d9e1e8", fg="#333333", font=("Helvetica", 8), bd=0).pack(side="bottom", pady=5)
        window.transient(self.root)
        window.grab_set()

    def insert_pages(self):
        base_file = self.get_file(title="Select Base PDF")
        if not base_file:
            return
        self.current_file = base_file
        self.save_for_undo(base_file)
        insert_file = self.get_file(title="Select PDF to Insert")
        if not insert_file:
            return
        base_reader = PdfReader(base_file)
        window = tk.Toplevel(self.root)
        window.title("Insert Pages Multiple Times")
        window.configure(bg="#ffffff")
        self.center_window(window, 400, 350)
        tk.Label(window, text="Insert Pages Multiple Times", font=("Helvetica", 14, "bold"), bg="#ffffff", fg="#333333").pack(pady=10)
        tk.Label(window, text=f"Total Pages in Base PDF: {len(base_reader.pages)}", font=("Helvetica", 10), bg="#ffffff", fg="#666666").pack(pady=5)
        tk.Label(window, text="Insert at page (1-based):", font=("Helvetica", 10), bg="#ffffff", fg="#333333").pack(pady=5)
        position_entry = tk.Entry(window, width=10, font=("Helvetica", 10), bd=1, relief="solid")
        position_entry.pack(pady=5)
        tk.Label(window, text="Repeat every (pages):", font=("Helvetica", 10), bg="#ffffff", fg="#333333").pack(pady=5)
        repeat_entry = tk.Entry(window, width=10, font=("Helvetica", 10), bd=1, relief="solid")
        repeat_entry.pack(pady=5)
        repeat_entry.insert(0, "1")

        def process():
            try:
                position = int(position_entry.get())
                repeat = int(repeat_entry.get())
                if position < 1 or position > len(base_reader.pages) + 1:
                    messagebox.showwarning("Warning", "Invalid position.")
                    return
                if repeat < 1:
                    messagebox.showwarning("Warning", "Repeat value must be at least 1.")
                    return
            except ValueError:
                messagebox.showwarning("Warning", "Please enter valid numbers.")
                return
            insert_reader = PdfReader(insert_file)
            writer = PdfWriter()
            total_steps = len(base_reader.pages) + (len(base_reader.pages) // repeat + 1) * len(insert_reader.pages)
            progress_window, progress_bar = self.show_progress(total_steps)
            for i in range(len(base_reader.pages)):
                if i % repeat == 0 and i >= position - 1:
                    for page in insert_reader.pages:
                        writer.add_page(page)
                        self.update_progress(progress_bar, 1)
                writer.add_page(base_reader.pages[i])
                self.update_progress(progress_bar, 1)
            output = self.save_file()
            if output:
                self.save_for_undo(output)
                with open(output, 'wb') as f:
                    writer.write(f)
                self.hide_progress(progress_window)
                window.destroy()
                messagebox.showinfo("Success", "Pages inserted successfully!")

        tk.Button(window, text="Insert", command=process, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"), 
                  bd=0, relief="flat", activebackground="#45a049", cursor="hand2").pack(pady=20)
        tk.Button(window, text="?", command=lambda: messagebox.showinfo("Help", "Insert pages from the second PDF into the first PDF at the specified position, repeating every N pages."), 
                  bg="#d9e1e8", fg="#333333", font=("Helvetica", 8), bd=0).pack(side="bottom", pady=5)
        window.transient(self.root)
        window.grab_set()

    def rotate_pages(self):
        file = self.get_file()
        if not file:
            return
        self.current_file = file
        self.save_for_undo(file)
        reader = PdfReader(file)
        window = tk.Toplevel(self.root)
        window.title("Rotate Pages")
        window.configure(bg="#ffffff")
        self.center_window(window, 400, 350)
        tk.Label(window, text="Rotate Pages", font=("Helvetica", 14, "bold"), bg="#ffffff", fg="#333333").pack(pady=10)
        tk.Label(window, text=f"Total Pages: {len(reader.pages)}", font=("Helvetica", 10), bg="#ffffff", fg="#666666").pack(pady=5)
        tk.Label(window, text="Select rotation angle:", font=("Helvetica", 10), bg="#ffffff", fg="#333333").pack(pady=5)
        angle_var = tk.StringVar(value="90")
        angles = [("90°", "90"), ("180°", "180"), ("270°", "270")]
        for text, value in angles:
            tk.Radiobutton(window, text=text, variable=angle_var, value=value, bg="#ffffff", fg="#333333", 
                           font=("Helvetica", 10), activebackground="#ffffff", selectcolor="#e0e0e0").pack()

        # Pré-visualização
        preview_label = tk.Label(window, bg="#ffffff")
        preview_label.pack(pady=5)
        self.show_preview(file, preview_label)

        def process():
            angle = int(angle_var.get())
            writer = PdfWriter()
            progress_window, progress_bar = self.show_progress(len(reader.pages))
            for page in reader.pages:
                page.rotate(angle)
                writer.add_page(page)
                self.update_progress(progress_bar, 1)
            output = self.save_file()
            if output:
                self.save_for_undo(output)
                with open(output, 'wb') as f:
                    writer.write(f)
                self.hide_progress(progress_window)
                window.destroy()
                messagebox.showinfo("Success", "Pages rotated successfully!")

        tk.Button(window, text="Rotate", command=process, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"), 
                  bd=0, relief="flat", activebackground="#45a049", cursor="hand2").pack(pady=20)
        tk.Button(window, text="?", command=lambda: messagebox.showinfo("Help", "Select the angle to rotate all pages."), 
                  bg="#d9e1e8", fg="#333333", font=("Helvetica", 8), bd=0).pack(side="bottom", pady=5)
        window.transient(self.root)
        window.grab_set()

    def organize_pages(self):
        file = self.get_file()
        if not file:
            return
        self.current_file = file
        self.save_for_undo(file)
        reader = PdfReader(file)
        window = tk.Toplevel(self.root)
        window.title("Organize Pages")
        window.configure(bg="#ffffff")
        self.center_window(window, 400, 350)
        tk.Label(window, text="Organize Pages", font=("Helvetica", 14, "bold"), bg="#ffffff", fg="#333333").pack(pady=10)
        tk.Label(window, text=f"Total Pages: {len(reader.pages)}", font=("Helvetica", 10), bg="#ffffff", fg="#666666").pack(pady=5)
        tk.Label(window, text="Enter new page order (e.g., 3, 1, 2):", font=("Helvetica", 10), bg="#ffffff", fg="#333333").pack(pady=5)
        entry = tk.Entry(window, width=40, font=("Helvetica", 10), bd=1, relief="solid")
        entry.pack(pady=5)
        tk.Label(window, text="Use commas to separate page numbers", font=("Helvetica", 8), bg="#ffffff", fg="#999999").pack(pady=5)

        # Validação em tempo real
        error_label = tk.Label(window, text="", font=("Helvetica", 8), bg="#ffffff", fg="red")
        error_label.pack(pady=5)
        def validate_order(*args):
            order = entry.get()
            if not order:
                error_label.config(text="")
                return
            try:
                page_list = self.parse_pages(order, len(reader.pages))
                if not page_list or len(page_list) != len(set(page_list)):
                    error_label.config(text="Invalid or duplicate page order.")
                else:
                    error_label.config(text="")
            except:
                error_label.config(text="Invalid format.")
        entry.bind("<KeyRelease>", validate_order)

        def process():
            order = entry.get()
            if not order:
                messagebox.showwarning("Warning", "Please enter a page order.")
                return
            page_list = self.parse_pages(order, len(reader.pages))
            if not page_list or len(page_list) != len(set(page_list)):
                messagebox.showwarning("Warning", "Invalid or duplicate page order.")
                return
            writer = PdfWriter()
            progress_window, progress_bar = self.show_progress(len(page_list))
            for page in page_list:
                writer.add_page(reader.pages[page-1])
                self.update_progress(progress_bar, 1)
            output = self.save_file()
            if output:
                self.save_for_undo(output)
                with open(output, 'wb') as f:
                    writer.write(f)
                self.hide_progress(progress_window)
                window.destroy()
                messagebox.showinfo("Success", "Pages organized successfully!")

        tk.Button(window, text="Organize", command=process, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"), 
                  bd=0, relief="flat", activebackground="#45a049", cursor="hand2").pack(pady=20)
        tk.Button(window, text="?", command=lambda: messagebox.showinfo("Help", "Enter the new order of pages (e.g., 3, 1, 2)."), 
                  bg="#d9e1e8", fg="#333333", font=("Helvetica", 8), bd=0).pack(side="bottom", pady=5)
        window.transient(self.root)
        window.grab_set()

    def delete_pages(self):
        file = self.get_file()
        if not file:
            return
        self.current_file = file
        self.save_for_undo(file)
        reader = PdfReader(file)
        window = tk.Toplevel(self.root)
        window.title("Delete Pages")
        window.configure(bg="#ffffff")
        self.center_window(window, 400, 350)
        tk.Label(window, text="Delete Pages", font=("Helvetica", 14, "bold"), bg="#ffffff", fg="#333333").pack(pady=10)
        tk.Label(window, text=f"Total Pages: {len(reader.pages)}", font=("Helvetica", 10), bg="#ffffff", fg="#666666").pack(pady=5)
        tk.Label(window, text="Enter pages to delete (e.g., 1-3, 5):", font=("Helvetica", 10), bg="#ffffff", fg="#333333").pack(pady=5)
        entry = tk.Entry(window, width=30, font=("Helvetica", 10), bd=1, relief="solid")
        entry.pack(pady=5)

        # Validação em tempo real
        error_label = tk.Label(window, text="", font=("Helvetica", 8), bg="#ffffff", fg="red")
        error_label.pack(pady=5)
        def validate_pages(*args):
            pages = entry.get()
            if not pages:
                error_label.config(text="")
                return
            try:
                page_list = self.parse_pages(pages, len(reader.pages))
                if not page_list:
                    error_label.config(text="Invalid page range.")
                else:
                    error_label.config(text="")
            except:
                error_label.config(text="Invalid format.")
        entry.bind("<KeyRelease>", validate_pages)

        # Pré-visualização
        preview_label = tk.Label(window, bg="#ffffff")
        preview_label.pack(pady=5)
        self.show_preview(file, preview_label)

        def process():
            pages = entry.get()
            if not pages:
                messagebox.showwarning("Warning", "Please enter pages to delete.")
                return
            delete_list = set(self.parse_pages(pages, len(reader.pages)))
            if not delete_list:
                messagebox.showwarning("Warning", "Invalid page range.")
                return
            writer = PdfWriter()
            progress_window, progress_bar = self.show_progress(len(reader.pages))
            for i in range(len(reader.pages)):
                if (i + 1) not in delete_list:
                    writer.add_page(reader.pages[i])
                self.update_progress(progress_bar, 1)
            output = self.save_file()
            if output:
                self.save_for_undo(output)
                with open(output, 'wb') as f:
                    writer.write(f)
                self.hide_progress(progress_window)
                window.destroy()
                messagebox.showinfo("Success", "Pages deleted successfully!")

        tk.Button(window, text="Delete", command=process, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"), 
                  bd=0, relief="flat", activebackground="#45a049", cursor="hand2").pack(pady=20)
        tk.Button(window, text="?", command=lambda: messagebox.showinfo("Help", "Enter the pages to delete (e.g., 1-3, 5)."), 
                  bg="#d9e1e8", fg="#333333", font=("Helvetica", 8), bd=0).pack(side="bottom", pady=5)
        window.transient(self.root)
        window.grab_set()

    def crop_pages(self):
        file = self.get_file()
        if not file:
            return
        self.current_file = file
        self.save_for_undo(file)
        reader = PdfReader(file)
        window = tk.Toplevel(self.root)
        window.title("Crop Pages")
        window.configure(bg="#ffffff")
        self.center_window(window, 400, 400)
        tk.Label(window, text="Crop Pages", font=("Helvetica", 14, "bold"), bg="#ffffff", fg="#333333").pack(pady=10)
        tk.Label(window, text=f"Total Pages: {len(reader.pages)}", font=("Helvetica", 10), bg="#ffffff", fg="#666666").pack(pady=5)
        tk.Label(window, text="Enter crop values (in points, 72 pt = 1 inch):", font=("Helvetica", 10), bg="#ffffff", fg="#333333").pack(pady=5)

        frame = tk.Frame(window, bg="#ffffff")
        frame.pack(pady=10)
        tk.Label(frame, text="Left:", font=("Helvetica", 10), bg="#ffffff", fg="#333333").grid(row=0, column=0, padx=10, pady=5)
        left_entry = tk.Entry(frame, width=10, font=("Helvetica", 10), bd=1, relief="solid")
        left_entry.grid(row=0, column=1)
        left_entry.insert(0, "0")
        tk.Label(frame, text="Top:", font=("Helvetica", 10), bg="#ffffff", fg="#333333").grid(row=0, column=2, padx=10, pady=5)
        top_entry = tk.Entry(frame, width=10, font=("Helvetica", 10), bd=1, relief="solid")
        top_entry.grid(row=0, column=3)
        top_entry.insert(0, "0")
        tk.Label(frame, text="Right:", font=("Helvetica", 10), bg="#ffffff", fg="#333333").grid(row=1, column=0, padx=10, pady=5)
        right_entry = tk.Entry(frame, width=10, font=("Helvetica", 10), bd=1, relief="solid")
        right_entry.grid(row=1, column=1)
        right_entry.insert(0, "0")
        tk.Label(frame, text="Bottom:", font=("Helvetica", 10), bg="#ffffff", fg="#333333").grid(row=1, column=2, padx=10, pady=5)
        bottom_entry = tk.Entry(frame, width=10, font=("Helvetica", 10), bd=1, relief="solid")
        bottom_entry.grid(row=1, column=3)
        bottom_entry.insert(0, "0")

        # Pré-visualização
        preview_label = tk.Label(window, bg="#ffffff")
        preview_label.pack(pady=5)
        self.show_preview(file, preview_label)

        def process():
            try:
                left = float(left_entry.get() or 0)
                top = float(top_entry.get() or 0)
                right = float(right_entry.get() or 0)
                bottom = float(bottom_entry.get() or 0)
            except ValueError:
                messagebox.showwarning("Warning", "Please enter valid numbers.")
                return
            writer = PdfWriter()
            progress_window, progress_bar = self.show_progress(len(reader.pages))
            for page in reader.pages:
                page.mediabox.lower_left = (page.mediabox.left + left, page.mediabox.bottom + bottom)
                page.mediabox.upper_right = (page.mediabox.right - right, page.mediabox.top - top)
                writer.add_page(page)
                self.update_progress(progress_bar, 1)
            output = self.save_file()
            if output:
                self.save_for_undo(output)
                with open(output, 'wb') as f:
                    writer.write(f)
                self.hide_progress(progress_window)
                window.destroy()
                messagebox.showinfo("Success", "Pages cropped successfully!")

        tk.Button(window, text="Crop", command=process, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"), 
                  bd=0, relief="flat", activebackground="#45a049", cursor="hand2").pack(pady=20)
        tk.Button(window, text="?", command=lambda: messagebox.showinfo("Help", "Enter crop values in points (72 points = 1 inch)."), 
                  bg="#d9e1e8", fg="#333333", font=("Helvetica", 8), bd=0).pack(side="bottom", pady=5)
        window.transient(self.root)
        window.grab_set()

    def edit_pdf(self):
        file = self.get_file()
        if not file:
            return
        self.current_file = file
        self.save_for_undo(file)
        window = tk.Toplevel(self.root)
        window.title("Edit PDF")
        window.configure(bg="#ffffff")
        self.center_window(window, 400, 350)
        tk.Label(window, text="Edit PDF", font=("Helvetica", 14, "bold"), bg="#ffffff", fg="#333333").pack(pady=10)
        tk.Label(window, text="Enter text to add:", font=("Helvetica", 10), bg="#ffffff", fg="#333333").pack(pady=5)
        text_entry = tk.Entry(window, width=30, font=("Helvetica", 10), bd=1, relief="solid")
        text_entry.pack(pady=5)
        tk.Label(window, text="X Position:", font=("Helvetica", 10), bg="#ffffff", fg="#333333").pack(pady=5)
        x_entry = tk.Entry(window, width=10, font=("Helvetica", 10), bd=1, relief="solid")
        x_entry.pack(pady=5)
        x_entry.insert(0, "100")
        tk.Label(window, text="Y Position:", font=("Helvetica", 10), bg="#ffffff", fg="#333333").pack(pady=5)
        y_entry = tk.Entry(window, width=10, font=("Helvetica", 10), bd=1, relief="solid")
        y_entry.pack(pady=5)
        y_entry.insert(0, "100")

        def process():
            text = text_entry.get()
            if not text:
                messagebox.showwarning("Warning", "Please enter text.")
                return
            try:
                x = float(x_entry.get())
                y = float(y_entry.get())
            except ValueError:
                messagebox.showwarning("Warning", "Please enter valid coordinates.")
                return
            reader = PdfReader(file)
            writer = PdfWriter()
            progress_window, progress_bar = self.show_progress(len(reader.pages))
            for page in reader.pages:
                writer.add_page(page)
                self.update_progress(progress_bar, 1)
            output = self.save_file()
            if output:
                self.save_for_undo(output)
                with open(output, 'wb') as f:
                    writer.write(f)
                temp_pdf = "temp_text.pdf"
                c = canvas.Canvas(temp_pdf, pagesize=letter)
                for page in reader.pages:
                    c.setPageSize((page.mediabox.width, page.mediabox.height))
                    c.drawString(x, y, text)
                    c.showPage()
                c.save()
                merger = PdfMerger()
                merger.append(output)
                merger.append(temp_pdf)
                merger.write(output + "_temp.pdf")
                merger.close()
                os.replace(output + "_temp.pdf", output)
                os.remove(temp_pdf)
                self.hide_progress(progress_window)
                window.destroy()
                messagebox.showinfo("Success", "Text added to PDF successfully!")

        tk.Button(window, text="Edit", command=process, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"), 
                  bd=0, relief="flat", activebackground="#45a049", cursor="hand2").pack(pady=20)
        tk.Button(window, text="?", command=lambda: messagebox.showinfo("Help", "Enter text and its position (X, Y) to add to the PDF."), 
                  bg="#d9e1e8", fg="#333333", font=("Helvetica", 8), bd=0).pack(side="bottom", pady=5)
        window.transient(self.root)
        window.grab_set()

    def extract_text(self):
        file = self.get_file()
        if not file:
            return
        reader = PdfReader(file)
        window = tk.Toplevel(self.root)
        window.title("Extract Text")
        window.configure(bg="#ffffff")
        self.center_window(window, 400, 300)
        tk.Label(window, text="Extract Text", font=("Helvetica", 14, "bold"), bg="#ffffff", fg="#333333").pack(pady=10)
        tk.Label(window, text=f"Total Pages: {len(reader.pages)}", font=("Helvetica", 10), bg="#ffffff", fg="#666666").pack(pady=5)

        def process():
            progress_window, progress_bar = self.show_progress(len(reader.pages))
            text = ""
            for page in reader.pages:
                extracted = page.extract_text()
                if extracted:
                    text += extracted + "\n"
                self.update_progress(progress_bar, 1)
            if not text:
                self.hide_progress(progress_window)
                messagebox.showwarning("Warning", "No text could be extracted from the PDF.")
                return
            output = self.save_file(title="Save Text", defaultextension=".txt", filetypes=[("Text files", "*.txt")])
            if output:
                with open(output, 'w', encoding='utf-8') as f:
                    f.write(text)
                self.hide_progress(progress_window)
                window.destroy()
                messagebox.showinfo("Success", "Text extracted successfully!")

        tk.Button(window, text="Extract", command=process, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"), 
                  bd=0, relief="flat", activebackground="#45a049", cursor="hand2").pack(pady=20)
        tk.Button(window, text="?", command=lambda: messagebox.showinfo("Help", "Extracts all text from the PDF and saves it as a .txt file."), 
                  bg="#d9e1e8", fg="#333333", font=("Helvetica", 8), bd=0).pack(side="bottom", pady=5)
        window.transient(self.root)
        window.grab_set()

    def encrypt_decrypt(self):
        file = self.get_file()
        if not file:
            return
        self.current_file = file
        self.save_for_undo(file)
        reader = PdfReader(file)
        window = tk.Toplevel(self.root)
        window.title("Encrypt/Decrypt PDF")
        window.configure(bg="#ffffff")
        self.center_window(window, 400, 350)
        tk.Label(window, text="Encrypt/Decrypt PDF", font=("Helvetica", 14, "bold"), bg="#ffffff", fg="#333333").pack(pady=10)
        tk.Label(window, text="Owner Password (for encryption):", font=("Helvetica", 10), bg="#ffffff", fg="#333333").pack(pady=5)
        owner_entry = tk.Entry(window, width=20, font=("Helvetica", 10), bd=1, relief="solid", show="*")
        owner_entry.pack(pady=5)
        tk.Label(window, text="User Password (for decryption):", font=("Helvetica", 10), bg="#ffffff", fg="#333333").pack(pady=5)
        user_entry = tk.Entry(window, width=20, font=("Helvetica", 10), bd=1, relief="solid", show="*")
        user_entry.pack(pady=5)

        def process():
            owner_password = owner_entry.get()
            user_password = user_entry.get()
            writer = PdfWriter()
            progress_window, progress_bar = self.show_progress(len(reader.pages))
            if reader.is_encrypted:
                if not user_password:
                    messagebox.showwarning("Warning", "Please enter the user password to decrypt.")
                    return
                try:
                    reader.decrypt(user_password)
                except Exception as e:
                    self.hide_progress(progress_window)
                    messagebox.showerror("Error", f"Failed to decrypt: {str(e)}")
                    return
                for page in reader.pages:
                    writer.add_page(page)
                    self.update_progress(progress_bar, 1)
            else:
                if owner_password:
                    writer.encrypt(owner_password)
                for page in reader.pages:
                    writer.add_page(page)
                    self.update_progress(progress_bar, 1)
            output = self.save_file()
            if output:
                self.save_for_undo(output)
                with open(output, 'wb') as f:
                    writer.write(f)
                self.hide_progress(progress_window)
                window.destroy()
                messagebox.showinfo("Success", "PDF encrypted/decrypted successfully!")

        tk.Button(window, text="Process", command=process, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"), 
                  bd=0, relief="flat", activebackground="#45a049", cursor="hand2").pack(pady=20)
        tk.Button(window, text="?", command=lambda: messagebox.showinfo("Help", "Enter an owner password to encrypt, or a user password to decrypt."), 
                  bg="#d9e1e8", fg="#333333", font=("Helvetica", 8), bd=0).pack(side="bottom", pady=5)
        window.transient(self.root)
        window.grab_set()

    def add_watermark(self):
        file = self.get_file()
        if not file:
            return
        self.current_file = file
        self.save_for_undo(file)
        watermark_file = self.get_file(title="Select Watermark PDF")
        if not watermark_file:
            return
        reader = PdfReader(file)
        watermark_reader = PdfReader(watermark_file)
        window = tk.Toplevel(self.root)
        window.title("Add Watermark")
        window.configure(bg="#ffffff")
        self.center_window(window, 400, 200)
        tk.Label(window, text="Add Watermark", font=("Helvetica", 14, "bold"), bg="#ffffff", fg="#333333").pack(pady=10)

        def process():
            writer = PdfWriter()
            watermark_page = watermark_reader.pages[0]
            progress_window, progress_bar = self.show_progress(len(reader.pages))
            for page in reader.pages:
                page.merge_page(watermark_page)
                writer.add_page(page)
                self.update_progress(progress_bar, 1)
            output = self.save_file()
            if output:
                self.save_for_undo(output)
                with open(output, 'wb') as f:
                    writer.write(f)
                self.hide_progress(progress_window)
                window.destroy()
                messagebox.showinfo("Success", "Watermark added successfully!")

        tk.Button(window, text="Add Watermark", command=process, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"), 
                  bd=0, relief="flat", activebackground="#45a049", cursor="hand2").pack(pady=20)
        tk.Button(window, text="?", command=lambda: messagebox.showinfo("Help", "Select a PDF with a watermark to apply to all pages."), 
                  bg="#d9e1e8", fg="#333333", font=("Helvetica", 8), bd=0).pack(side="bottom", pady=5)
        window.transient(self.root)
        window.grab_set()

    def add_background(self):
        file = self.get_file()
        if not file:
            return
        self.current_file = file
        self.save_for_undo(file)
        background_file = self.get_file(title="Select Background PDF")
        if not background_file:
            return
        reader = PdfReader(file)
        background_reader = PdfReader(background_file)
        window = tk.Toplevel(self.root)
        window.title("Add Background")
        window.configure(bg="#ffffff")
        self.center_window(window, 400, 200)
        tk.Label(window, text="Add Background", font=("Helvetica", 14, "bold"), bg="#ffffff", fg="#333333").pack(pady=10)

        def process():
            writer = PdfWriter()
            background_page = background_reader.pages[0]
            progress_window, progress_bar = self.show_progress(len(reader.pages))
            for page in reader.pages:
                background_page_copy = background_page
                background_page_copy.merge_page(page)
                writer.add_page(background_page_copy)
                self.update_progress(progress_bar, 1)
            output = self.save_file()
            if output:
                self.save_for_undo(output)
                with open(output, 'wb') as f:
                    writer.write(f)
                self.hide_progress(progress_window)
                window.destroy()
                messagebox.showinfo("Success", "Background added successfully!")

        tk.Button(window, text="Add Background", command=process, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"), 
                  bd=0, relief="flat", activebackground="#45a049", cursor="hand2").pack(pady=20)
        tk.Button(window, text="?", command=lambda: messagebox.showinfo("Help", "Select a PDF with a background to apply to all pages."), 
                  bg="#d9e1e8", fg="#333333", font=("Helvetica", 8), bd=0).pack(side="bottom", pady=5)
        window.transient(self.root)
        window.grab_set()

    def attach_files(self):
        file = self.get_file()
        if not file:
            return
        self.current_file = file
        self.save_for_undo(file)
        attachments = self.get_file(title="Select Files to Attach", multiple=True, filetypes=[("All files", "*.*")])
        if not attachments:
            return
        reader = PdfReader(file)
        window = tk.Toplevel(self.root)
        window.title("Attach Files")
        window.configure(bg="#ffffff")
        self.center_window(window, 400, 200)
        tk.Label(window, text="Attach Files", font=("Helvetica", 14, "bold"), bg="#ffffff", fg="#333333").pack(pady=10)
        tk.Label(window, text=f"Selected Files: {len(attachments)}", font=("Helvetica", 10), bg="#ffffff", fg="#666666").pack(pady=5)

        def process():
            writer = PdfWriter()
            progress_window, progress_bar = self.show_progress(len(reader.pages))
            for page in reader.pages:
                writer.add_page(page)
                self.update_progress(progress_bar, 1)
            for attachment in attachments:
                writer.add_attachment(os.path.basename(attachment), open(attachment, 'rb').read())
            output = self.save_file()
            if output:
                self.save_for_undo(output)
                with open(output, 'wb') as f:
                    writer.write(f)
                self.hide_progress(progress_window)
                window.destroy()
                messagebox.showinfo("Success", "Files attached successfully!")

        tk.Button(window, text="Attach", command=process, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"), 
                  bd=0, relief="flat", activebackground="#45a049", cursor="hand2").pack(pady=20)
        tk.Button(window, text="?", command=lambda: messagebox.showinfo("Help", "Select files to attach to the PDF."), 
                  bg="#d9e1e8", fg="#333333", font=("Helvetica", 8), bd=0).pack(side="bottom", pady=5)
        window.transient(self.root)
        window.grab_set()

    def extract_attachments(self):
        file = self.get_file()
        if not file:
            return
        reader = PdfReader(file)
        window = tk.Toplevel(self.root)
        window.title("Extract Attachments")
        window.configure(bg="#ffffff")
        self.center_window(window, 400, 200)
        tk.Label(window, text="Extract Attachments", font=("Helvetica", 14, "bold"), bg="#ffffff", fg="#333333").pack(pady=10)

        def process():
            output_dir = filedialog.askdirectory(title="Select Output Directory")
            if not output_dir:
                return
            attachments = reader.attachments
            if not attachments:
                messagebox.showwarning("Warning", "No attachments found in the PDF.")
                return
            progress_window, progress_bar = self.show_progress(len(attachments))
            for name, data in attachments.items():
                with open(f"{output_dir}/{name}", 'wb') as f:
                    f.write(data)
                self.update_progress(progress_bar, 1)
            self.hide_progress(progress_window)
            window.destroy()
            messagebox.showinfo("Success", "Attachments extracted successfully!")

        tk.Button(window, text="Extract", command=process, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"), 
                  bd=0, relief="flat", activebackground="#45a049", cursor="hand2").pack(pady=20)
        tk.Button(window, text="?", command=lambda: messagebox.showinfo("Help", "Extracts all attachments from the PDF to the selected directory."), 
                  bg="#d9e1e8", fg="#333333", font=("Helvetica", 8), bd=0).pack(side="bottom", pady=5)
        window.transient(self.root)
        window.grab_set()

    def fill_forms(self):
        file = self.get_file()
        if not file:
            return
        self.current_file = file
        self.save_for_undo(file)
        reader = PdfReader(file)
        window = tk.Toplevel(self.root)
        window.title("Fill Forms")
        window.configure(bg="#ffffff")
        self.center_window(window, 500, 500)
        tk.Label(window, text="Fill Forms", font=("Helvetica", 14, "bold"), bg="#ffffff", fg="#333333").pack(pady=10)

        # Verificar se o PDF tem formulários
        fields = reader.get_fields()
        if not fields:
            messagebox.showwarning("Warning", "This PDF does not contain any fillable forms.")
            window.destroy()
            return

        # Frame para os campos do formulário
        canvas = tk.Canvas(window, bg="#ffffff")
        scrollbar = tk.Scrollbar(window, orient="vertical", command=canvas.yview)
        scrollable_frame = tk.Frame(canvas, bg="#ffffff")

        scrollable_frame.bind(
            "<Configure>",
            lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
        )

        canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
        canvas.configure(yscrollcommand=scrollbar.set)

        canvas.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")

        # Dicionário para armazenar os campos e suas entradas
        field_entries = {}

        # Listar todos os campos do formulário
        for field_name, field in fields.items():
            frame = tk.Frame(scrollable_frame, bg="#ffffff")
            frame.pack(fill="x", pady=5)
            tk.Label(frame, text=f"{field_name}:", font=("Helvetica", 10), bg="#ffffff", fg="#333333", width=20, anchor="w").pack(side="left")
            entry = tk.Entry(frame, width=40, font=("Helvetica", 10), bd=1, relief="solid")
            entry.pack(side="left", padx=5)
            field_entries[field_name] = entry

        def process():
            writer = PdfWriter()
            progress_window, progress_bar = self.show_progress(len(reader.pages))
            for page in reader.pages:
                writer.add_page(page)
                self.update_progress(progress_bar, 1)

            # Preencher os campos do formulário
            form_data = {}
            for field_name, entry in field_entries.items():
                value = entry.get()
                if value:
                    form_data[field_name] = value

            # Atualizar os campos do formulário no PDF
            writer.update_page_form_field_values(writer.pages, form_data)

            output = self.save_file()
            if output:
                self.save_for_undo(output)
                with open(output, 'wb') as f:
                    writer.write(f)
                self.hide_progress(progress_window)
                window.destroy()
                messagebox.showinfo("Success", "Form filled successfully!")

        tk.Button(window, text="Fill", command=process, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"), 
                  bd=0, relief="flat", activebackground="#45a049", cursor="hand2").pack(pady=20)
        tk.Button(window, text="?", command=lambda: messagebox.showinfo("Help", "Fill in the form fields and click 'Fill' to save the changes."), 
                  bg="#d9e1e8", fg="#333333", font=("Helvetica", 8), bd=0).pack(side="bottom", pady=5)
        window.transient(self.root)
        window.grab_set()

    def convert_to_ppt(self):
        file = self.get_file()
        if not file:
            return
        window = tk.Toplevel(self.root)
        window.title("Convert PDF")
        window.configure(bg="#ffffff")
        self.center_window(window, 400, 300)
        tk.Label(window, text="Convert PDF", font=("Helvetica", 14, "bold"), bg="#ffffff", fg="#333333").pack(pady=10)
        tk.Label(window, text="Select output format:", font=("Helvetica", 10), bg="#ffffff", fg="#333333").pack(pady=5)
        format_var = tk.StringVar(value="PowerPoint")
        formats = [("PowerPoint (.pptx)", "PowerPoint"), ("Word (.docx)", "Word")]
        for text, value in formats:
            tk.Radiobutton(window, text=text, variable=format_var, value=value, bg="#ffffff", fg="#333333", 
                           font=("Helvetica", 10), activebackground="#ffffff", selectcolor="#e0e0e0").pack()

        def process():
            reader = PdfReader(file)
            if format_var.get() == "PowerPoint":
                output = self.save_file(title="Save PowerPoint", defaultextension=".pptx", filetypes=[("PowerPoint files", "*.pptx")])
                if not output:
                    return
                prs = Presentation()
                progress_window, progress_bar = self.show_progress(len(reader.pages))
                for page in reader.pages:
                    slide = prs.slides.add_slide(prs.slide_layouts[5])
                    temp_pdf = "temp_page.pdf"
                    writer = PdfWriter()
                    writer.add_page(page)
                    with open(temp_pdf, 'wb') as f:
                        writer.write(f)
                    images = convert_from_path(temp_pdf)
                    if images:
                        temp_image = "temp_image.png"
                        images[0].save(temp_image)
                        slide.shapes.add_picture(temp_image, 0, 0, width=prs.slide_width)
                        os.remove(temp_image)
                    os.remove(temp_pdf)
                    self.update_progress(progress_bar, 1)
                prs.save(output)
                self.hide_progress(progress_window)
                window.destroy()
                messagebox.showinfo("Success", "Converted to PowerPoint successfully!")
            else:
                output = self.save_file(title="Save Word", defaultextension=".docx", filetypes=[("Word files", "*.docx")])
                if not output:
                    return
                cv = Converter(file)
                cv.convert(output)
                cv.close()
                window.destroy()
                messagebox.showinfo("Success", "Converted to Word successfully!")

        tk.Button(window, text="Convert", command=process, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"), 
                  bd=0, relief="flat", activebackground="#45a049", cursor="hand2").pack(pady=20)
        tk.Button(window, text="?", command=lambda: messagebox.showinfo("Help", "Select the output