Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

import tkinter as tk from tkinter import filedialog, messagebox import fitz # PyMuPDF…

  1. User

    import tkinter as tk from tkinter import filedialog, messagebox import fitz # PyMuPDF import pandas as pd from PIL import Image, ImageTk import os import tempfile from reportlab.pdfgen import canvas as reportlab_canvas from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase import pdfmetrics import matplotlib.font_manager as fm from fontTools.ttLib import TTFont as FontToolsTTFont import sys import cairosvg # Để chuyển đổi SVG sang PDF import comtypes.client import win32com.client as win32 from docx2pdf import convert as docx2pdf_convert import uuid

    class PDFEditorApp: def init(self, root): self.root = root self.root.title("Phần mềm tạo dữ liệu biến đổi - Bản quyền thuộc về NhanNguyen") self.root.configure(bg='#2c2f33') self.root.bind("", self.delete_text) self.root.bind("", self.undo) self.root.bind("", self.redo)

        self.file_path = None  # Đổi tên biến để phản ánh việc hỗ trợ nhiều định dạng tệp
        self.excel_path = None
        self.pdf_image = None
        self.coords = {}  # Lưu tọa độ cho mỗi trang
        self.df = None
        self.fields = []
        self.font_var = tk.StringVar(value="Arial")
        self.font_size_var = tk.IntVar(value=12)
        self.cmyk_vars = {
            "C": tk.DoubleVar(value=0.0),
            "M": tk.DoubleVar(value=0.0),
            "Y": tk.DoubleVar(value=0.0),
            "K": tk.DoubleVar(value=0.0)
        }
    
        self.original_width = 0
        self.original_height = 0
        self.current_page_index = 0  # Chỉ số trang hiện tại
        self.pdf_doc = None  # Tài liệu PDF đã tải
        self.font_file_dict = {}
        self.undo_stack = []  # Ngăn xếp undo
        self.redo_stack = []  # Ngăn xếp redo
    
        self.field_type = tk.StringVar(value="Text")  # Biến để chọn loại trường
        self.image_width_var = tk.DoubleVar(value=100.0)  # Sử dụng DoubleVar cho đơn vị mm
        self.image_height_var = tk.DoubleVar(value=100.0)
    
        self.selected_field = tk.StringVar(value="Ho Ten")
        self.selected_items = set()
        self.zoom_level = 1.0
    
        self.preview_pdf_path = None
        self.preview_doc = None
        self.preview_page_index = 0
    
        self.is_previewing = False  # Trạng thái xem trước
    
        self.excel_row_index = 0  # Thêm biến để theo dõi chỉ số hàng hiện tại trong Excel
        
         # Existing variable for crop mark offset
        self.cropmark_offset_var = tk.DoubleVar(value=3.0)
    
        # New variable for crop mark length
        self.cropmark_length_var = tk.DoubleVar(value=5.0)  # Default length: 5 mm
    
        self.setup_ui()
    
    def get_installed_fonts(self):
        """Lấy danh sách các font TrueType đã cài đặt."""
        font_list = fm.findSystemFonts(fontpaths=None, fontext='ttf')
        for font_path in font_list:
            font_name = self.get_font_full_name(font_path)
            if font_name:
                self.font_file_dict[font_name] = font_path
        return list(self.font_file_dict.keys())
    
    def get_font_full_name(self, font_path):
        """Lấy tên đầy đủ của font sử dụng fontTools."""
        try:
            font = FontToolsTTFont(font_path)
            name = ""
            for record in font['name'].names:
                if record.nameID == 4 and record.platformID == 3:
                    name = record.string.decode('utf-16-be')
                    break
                elif record.nameID == 4 and record.platformID == 1:
                    name = record.string.decode('utf-8')
                    break
            font.close()
            return name
        except Exception:
            return None
    
    def check_font_availability(self, font_path):
        """Kiểm tra xem tệp font có khả dụng và hợp lệ không."""
        try:
            font = FontToolsTTFont(font_path)
            font.close()
            return True
        except Exception:
            return False
    
    def setup_ui(self):
        """Thiết lập các thành phần giao diện người dùng."""
        # Hàng đầu tiên của các nút
        button_frame = tk.Frame(self.root, bg='#2c2f33')
        button_frame.pack(pady=5, fill=tk.X)
    
        select_pdf_button = tk.Button(button_frame, text="Chọn tệp", command=self.load_file, bg='#7289da', fg='white')
        select_pdf_button.pack(side=tk.LEFT, padx=2)
    
        select_excel_button = tk.Button(button_frame, text="Chọn Excel", command=self.load_excel, bg='#7289da', fg='white')
        select_excel_button.pack(side=tk.LEFT, padx=2)
    
        save_button = tk.Button(button_frame, text="Xuất PDF", command=self.export_pdfs, bg='#7289da', fg='white')
        save_button.pack(side=tk.LEFT, padx=2)
    
        prev_button = tk.Button(button_frame, text="Trang trước", command=self.prev_page, bg='#7289da', fg='white')
        prev_button.pack(side=tk.LEFT, padx=2)
    
        next_button = tk.Button(button_frame, text="Trang tiếp", command=self.next_page, bg='#7289da', fg='white')
        next_button.pack(side=tk.LEFT, padx=2)
    
        font_label = tk.Label(button_frame, text="Chọn font:", bg='#2c2f33', fg='white')
        font_label.pack(side=tk.LEFT, padx=2)
    
        self.font_files = self.get_installed_fonts()
        self.font_menu = tk.OptionMenu(button_frame, self.font_var, *self.font_files, command=self.update_canvas_font)
        self.font_menu.pack(side=tk.LEFT, padx=2)
    
        size_label = tk.Label(button_frame, text="Kích cỡ chữ:", bg='#2c2f33', fg='white')
        size_label.pack(side=tk.LEFT, padx=2)
    
        size_entry = tk.Entry(button_frame, textvariable=self.font_size_var, width=5)
        size_entry.pack(side=tk.LEFT, padx=2)
        size_entry.bind("<KeyRelease>", self.update_canvas_font)
    
        # Nhập màu CMYK
        for color in ["C", "M", "Y", "K"]:
            color_label = tk.Label(button_frame, text=f"{color}:", bg='#2c2f33', fg='white')
            color_label.pack(side=tk.LEFT, padx=2)
            color_entry = tk.Entry(button_frame, textvariable=self.cmyk_vars[color], width=5)
            color_entry.pack(side=tk.LEFT, padx=2)
            color_entry.bind("<KeyRelease>", self.update_canvas_font)
    
        # Chọn loại trường
        tk.Radiobutton(button_frame, text="Văn bản", variable=self.field_type, value="Text", bg='#2c2f33', fg='white', selectcolor='#7289da').pack(side=tk.LEFT, padx=2)
        tk.Radiobutton(button_frame, text="Hình ảnh", variable=self.field_type, value="Image", bg='#2c2f33', fg='white', selectcolor='#7289da').pack(side=tk.LEFT, padx=2)
    
        # Nhập kích thước hình ảnh
        tk.Label(button_frame, text="Chiều rộng (mm):", bg='#2c2f33', fg='white').pack(side=tk.LEFT, padx=2)
        tk.Entry(button_frame, textvariable=self.image_width_var, width=5).pack(side=tk.LEFT, padx=2)
    
        tk.Label(button_frame, text="Chiều cao (mm):", bg='#2c2f33', fg='white').pack(side=tk.LEFT, padx=2)
        tk.Entry(button_frame, textvariable=self.image_height_var, width=5).pack(side=tk.LEFT, padx=2)
    
        # Hàng thứ hai của các nút
        button_frame2 = tk.Frame(self.root, bg='#2c2f33')
        button_frame2.pack(pady=5, fill=tk.X)
    
        align_left_button = tk.Button(button_frame2, text="Canh trái", command=self.align_left, bg='#7289da', fg='white')
        align_left_button.pack(side=tk.LEFT, padx=2)
    
        align_right_button = tk.Button(button_frame2, text="Canh phải", command=self.align_right, bg='#7289da', fg='white')
        align_right_button.pack(side=tk.LEFT, padx=2)
    
        align_center_button = tk.Button(button_frame2, text="Canh giữa", command=self.align_center, bg='#7289da', fg='white')
        align_center_button.pack(side=tk.LEFT, padx=2)
    
        align_top_button = tk.Button(button_frame2, text="Canh trên", command=self.align_top, bg='#7289da', fg='white')
        align_top_button.pack(side=tk.LEFT, padx=2)
    
        align_bottom_button = tk.Button(button_frame2, text="Canh dưới", command=self.align_bottom, bg='#7289da', fg='white')
        align_bottom_button.pack(side=tk.LEFT, padx=2)
    
        zoom_in_button = tk.Button(button_frame2, text="Zoom +", command=self.zoom_in, bg='#7289da', fg='white')
        zoom_in_button.pack(side=tk.LEFT, padx=2)
    
        zoom_out_button = tk.Button(button_frame2, text="Zoom -", command=self.zoom_out, bg='#7289da', fg='white')
        zoom_out_button.pack(side=tk.LEFT, padx=2)
    
        preview_button = tk.Button(button_frame2, text="Xem trước", command=self.preview_pdf, bg='#7289da', fg='white')
        preview_button.pack(side=tk.LEFT, padx=2)
    
        # Hàng thứ ba của các nút (thông số Imposition)
        imposition_frame = tk.Frame(self.root, bg='#2c2f33')
        imposition_frame.pack(pady=5, fill=tk.X)
    
        tk.Label(imposition_frame, text="Khổ giấy (mm):", bg='#2c2f33', fg='white').pack(side=tk.LEFT, padx=2)
    
        tk.Label(imposition_frame, text="Chiều rộng:", bg='#2c2f33', fg='white').pack(side=tk.LEFT, padx=2)
        self.new_page_width_var = tk.DoubleVar(value=210.0)
        tk.Entry(imposition_frame, textvariable=self.new_page_width_var, width=5).pack(side=tk.LEFT, padx=2)
    
        tk.Label(imposition_frame, text="Chiều cao:", bg='#2c2f33', fg='white').pack(side=tk.LEFT, padx=2)
        self.new_page_height_var = tk.DoubleVar(value=297.0)
        tk.Entry(imposition_frame, textvariable=self.new_page_height_var, width=5).pack(side=tk.LEFT, padx=2)
    
        tk.Label(imposition_frame, text="Lề (mm):", bg='#2c2f33', fg='white').pack(side=tk.LEFT, padx=2)
    
        tk.Label(imposition_frame, text="Trên:", bg='#2c2f33', fg='white').pack(side=tk.LEFT, padx=2)
        self.margin_top_var = tk.DoubleVar(value=10.0)
        tk.Entry(imposition_frame, textvariable=self.margin_top_var, width=5).pack(side=tk.LEFT, padx=2)
    
        tk.Label(imposition_frame, text="Dưới:", bg='#2c2f33', fg='white').pack(side=tk.LEFT, padx=2)
        self.margin_bottom_var = tk.DoubleVar(value=10.0)
        tk.Entry(imposition_frame, textvariable=self.margin_bottom_var, width=5).pack(side=tk.LEFT, padx=2)
    
        tk.Label(imposition_frame, text="Trái:", bg='#2c2f33', fg='white').pack(side=tk.LEFT, padx=2)
        self.margin_left_var = tk.DoubleVar(value=10.0)
        tk.Entry(imposition_frame, textvariable=self.margin_left_var, width=5).pack(side=tk.LEFT, padx=2)
    
        tk.Label(imposition_frame, text="Phải:", bg='#2c2f33', fg='white').pack(side=tk.LEFT, padx=2)
        self.margin_right_var = tk.DoubleVar(value=10.0)
        tk.Entry(imposition_frame, textvariable=self.margin_right_var, width=5).pack(side=tk.LEFT, padx=2)
    
        # Khoảng cách crop marks
        tk.Label(imposition_frame, text="Khoảng cách crop marks (mm):", bg='#2c2f33', fg='white').pack(side=tk.LEFT, padx=2)
        self.cropmark_offset_var = tk.DoubleVar(value=3.0)
        tk.Entry(imposition_frame, textvariable=self.cropmark_offset_var, width=5).pack(side=tk.LEFT, padx=2)
    
        # Độ dài crop marks
        tk.Label(imposition_frame, text="Độ dài crop marks (mm):", bg='#2c2f33', fg='white').pack(side=tk.LEFT, padx=2)
        self.cropmark_length_var = tk.DoubleVar(value=5.0)  # Added
        tk.Entry(imposition_frame, textvariable=self.cropmark_length_var, width=5).pack(side=tk.LEFT, padx=2)
    
        # Điều chỉnh khung để hiển thị cả hai canvas
        content_frame = tk.Frame(self.root, bg='#2c2f33')
        content_frame.pack(pady=5, fill=tk.BOTH, expand=True)
    
        # Khung canvas chính
        main_canvas_frame = tk.Frame(content_frame, bg='#2c2f33')
        main_canvas_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
    
        self.canvas = tk.Canvas(main_canvas_frame, bg="gray")
        self.canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
    
        # Thêm thanh cuộn cho canvas
        hbar = tk.Scrollbar(main_canvas_frame, orient=tk.HORIZONTAL)
        hbar.pack(side=tk.BOTTOM, fill=tk.X)
        hbar.config(command=self.canvas.xview)
        vbar = tk.Scrollbar(main_canvas_frame, orient=tk.VERTICAL)
        vbar.pack(side=tk.RIGHT, fill=tk.Y)
        vbar.config(command=self.canvas.yview)
        self.canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set)
    
        # Khung canvas xem trước
        self.preview_canvas_frame = tk.Frame(content_frame, bg='#2c2f33')
        self.preview_canvas_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
    
        self.preview_canvas = tk.Canvas(self.preview_canvas_frame, bg="gray")
        self.preview_canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
    
        # Thêm thanh cuộn cho canvas xem trước
        preview_hbar = tk.Scrollbar(self.preview_canvas_frame, orient=tk.HORIZONTAL)
        preview_hbar.pack(side=tk.BOTTOM, fill=tk.X)
        preview_hbar.config(command=self.preview_canvas.xview)
        preview_vbar = tk.Scrollbar(self.preview_canvas_frame, orient=tk.VERTICAL)
        preview_vbar.pack(side=tk.RIGHT, fill=tk.Y)
        preview_vbar.config(command=self.preview_canvas.yview)
        self.preview_canvas.config(xscrollcommand=preview_hbar.set, yscrollcommand=preview_vbar.set)
    
        # Khung xem trước
        self.preview_frame = tk.Frame(self.root, bg='#2c2f33')
        self.preview_frame.pack(fill=tk.BOTH, expand=True)
    
        # Khu vực văn bản
        self.text_area = tk.Text(self.preview_frame, height=10, width=100, bg='#23272a', fg='white')
        self.text_area.pack(side=tk.LEFT, padx=5, fill=tk.BOTH, expand=True)
    
        self.canvas.bind("<Button-1>", self.canvas_click)
        self.canvas.bind("<B1-Motion>", self.move_text)
        self.canvas.bind("<MouseWheel>", self.zoom_with_mouse_wheel)
        self.canvas.bind("<Button-4>", self.zoom_with_mouse_wheel)  # Cho Linux
        self.canvas.bind("<Button-5>", self.zoom_with_mouse_wheel)
    
        self.preview_canvas.bind("<MouseWheel>", self.zoom_with_mouse_wheel)
        self.preview_canvas.bind("<Button-4>", self.zoom_with_mouse_wheel)  # Cho Linux
        self.preview_canvas.bind("<Button-5>", self.zoom_with_mouse_wheel)
    
        # Khung chọn trường
        self.excel_button_frame = tk.Frame(self.root, bg='#2c2f33')
        self.excel_button_frame.pack(fill=tk.X, padx=5, pady=5)
    
        # Thêm nút "Trước" và "Tiếp" cho xem trước
        preview_nav_frame = tk.Frame(self.preview_frame, bg='#2c2f33')
        preview_nav_frame.pack(fill=tk.X)
    
        prev_preview_button = tk.Button(preview_nav_frame, text="<< Trước", command=self.prev_preview, bg='#7289da', fg='white')
        prev_preview_button.pack(side=tk.LEFT, padx=2)
    
        next_preview_button = tk.Button(preview_nav_frame, text="Tiếp >>", command=self.next_preview, bg='#7289da', fg='white')
        next_preview_button.pack(side=tk.LEFT, padx=2)
    
    def load_file(self):
        """Tải tệp đã chọn và hiển thị trang đầu tiên."""
        filetypes = [
            ("Supported files", "*.pdf *.ai *.eps *.svg *.tiff *.tif *.jpg *.jpeg *.png *.pptx"),
            ("PDF files", "*.pdf"),
            ("Image files", "*.tiff *.tif *.jpg *.jpeg *.png"),
            ("Vector files", "*.ai *.eps *.svg"),
            ("PowerPoint files", "*.pptx"),
            ("All files", "*.*")
        ]
        self.file_path = filedialog.askopenfilename(filetypes=filetypes)
        if self.file_path:
            try:
                # Đóng tài liệu hiện tại nếu đang mở
                if self.pdf_doc:
                    self.pdf_doc.close()
                self.convert_file_to_pdf()
                self.pdf_doc = fitz.open(self.temp_pdf_path)
                self.current_page_index = 0  # Đặt lại chỉ số trang
                self.display_pdf_page()
                self.reset_preview()
            except Exception as e:
                messagebox.showerror("Lỗi", f"Không thể mở tệp: {e}")
                self.file_path = None
                self.pdf_doc = None
    
    def convert_file_to_pdf(self):
        """Chuyển đổi tệp đầu vào sang PDF nếu cần thiết."""
        ext = os.path.splitext(self.file_path)[1].lower()
        temp_dir = tempfile.gettempdir()
        unique_id = str(uuid.uuid4())
        self.temp_pdf_path = os.path.join(temp_dir, f"temp_input_{unique_id}.pdf")
    
        if ext == ".pdf":
            self.temp_pdf_path = self.file_path  # Không cần chuyển đổi
    
        elif ext in [".doc", ".docx"]:
            try:
                docx2pdf_convert(self.file_path, self.temp_pdf_path)
            except Exception as e:
                raise Exception(f"Không thể chuyển đổi tệp Word sang PDF: {e}")
    
        elif ext in [".xls", ".xlsx"]:
            try:
                excel = win32.Dispatch("Excel.Application")
                excel.Visible = False
                wb = excel.Workbooks.Open(self.file_path)
                wb.ExportAsFixedFormat(0, self.temp_pdf_path)
                wb.Close(False)
                excel.Quit()
            except Exception as e:
                raise Exception(f"Không thể chuyển đổi tệp Excel sang PDF: {e}")
    
        elif ext == ".ai":
            try:
                app = comtypes.client.CreateObject("Illustrator.Application")
                doc = app.Open(self.file_path)
                options = comtypes.client.CreateObject("Illustrator.PDFSaveOptions")
                doc.SaveAs(self.temp_pdf_path, options)
                doc.Close()
                app.Quit()    # Đóng ứng dụng Illustrator
            except Exception as e:
                raise Exception(f"Không thể chuyển đổi tệp AI sang PDF: {e}")
    
        elif ext == ".cdr":
            try:
                app = comtypes.client.CreateObject("CorelDRAW.Application")
                doc = app.OpenDocument(self.file_path)
                doc.PublishToPDF(self.temp_pdf_path)
                doc.Close()
                app.Quit()
            except Exception as e:
                raise Exception(f"Không thể chuyển đổi tệp CDR sang PDF: {e}")
    
        elif ext == ".psd":
            try:
                app = comtypes.client.CreateObject("Photoshop.Application")
                doc = app.Open(self.file_path)
                options = comtypes.client.CreateObject("Photoshop.PDFSaveOptions")
                doc.SaveAs(self.temp_pdf_path, options)
                doc.Close()
                app.Quit()
            except Exception as e:
                raise Exception(f"Không thể chuyển đổi tệp PSD sang PDF: {e}")
    
        elif ext == ".indd":
            try:
                app = comtypes.client.CreateObject("InDesign.Application")
                doc = app.Open(self.file_path)
                pdf_preset = app.PDFExportPresets.Item("High Quality Print")
                doc.Export(1242363897, self.temp_pdf_path, False, pdf_preset)
                doc.Close()
                app.Quit()
            except Exception as e:
                raise Exception(f"Không thể chuyển đổi tệp InDesign sang PDF: {e}")
    
        elif ext in [".jpg", ".jpeg", ".png", ".tif", ".tiff", ".webp"]:
            # Chuyển đổi hình ảnh sang PDF với kích thước trang chính xác
            image = Image.open(self.file_path)
            width_px, height_px = image.size
            dpi = image.info.get('dpi', (72, 72))[0]  # Lấy DPI từ hình ảnh, mặc định là 72
            width_inch = width_px / dpi
            height_inch = height_px / dpi
            page_width = width_inch * 72  # 1 inch = 72 points
            page_height = height_inch * 72
    
            c = reportlab_canvas.Canvas(self.temp_pdf_path, pagesize=(page_width, page_height))
            c.drawImage(self.file_path, 0, 0, width=page_width, height=page_height)
            c.showPage()
            c.save()
    
            # Thiết lập các hộp PDF
            doc = fitz.open(self.temp_pdf_path)
            for page in doc:
                rect = fitz.Rect(0, 0, page_width, page_height)
                page.set_cropbox(rect)
                page.set_trimbox(rect)
                page.set_artbox(rect)
            doc.saveIncr()
            doc.close()
    
        elif ext == ".svg":
            # Chuyển đổi SVG sang PDF
            cairosvg.svg2pdf(url=self.file_path, write_to=self.temp_pdf_path)
        elif ext == ".eps":
            # Chuyển đổi EPS sang PDF bằng Ghostscript
            try:
                import subprocess
                subprocess.call(['gs', '-dNOPAUSE', '-dBATCH', '-sDEVICE=pdfwrite',
                                '-sOutputFile=' + self.temp_pdf_path, self.file_path])
            except Exception as e:
                raise Exception(f"Không thể chuyển đổi tệp EPS sang PDF: {e}")
        elif ext == ".ps":
            # Chuyển đổi PostScript sang PDF bằng Ghostscript
            try:
                import subprocess
                subprocess.call(['gs', '-dNOPAUSE', '-dBATCH', '-sDEVICE=pdfwrite',
                                '-sOutputFile=' + self.temp_pdf_path, self.file_path])
            except Exception as e:
                raise Exception(f"Không thể chuyển đổi tệp PS sang PDF: {e}")
        elif ext == ".pptx":
            # Chuyển đổi PowerPoint sang PDF
            try:
                powerpoint = comtypes.client.CreateObject("Powerpoint.Application")
                powerpoint.Visible = 1
                deck = powerpoint.Presentations.Open(self.file_path)
                deck.SaveAs(self.temp_pdf_path, 32)  # 32 cho định dạng PDF
                deck.Close()
                powerpoint.Quit()
            except Exception as e:
                raise Exception(f"Không thể chuyển đổi tệp PPTX sang PDF: {e}")
        else:
            raise Exception("Định dạng tệp không được hỗ trợ.")
    
    def display_pdf_page(self):
        """Hiển thị trang hiện tại của PDF."""
        if self.pdf_doc:
            try:
                page = self.pdf_doc.load_page(self.current_page_index)
                self.original_width, self.original_height = page.rect.width, page.rect.height
                # Điều chỉnh ma trận cho zoom
                zoom_matrix = fitz.Matrix(self.zoom_level, self.zoom_level)
                pix = page.get_pixmap(matrix=zoom_matrix)
                img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
                self.pdf_image = ImageTk.PhotoImage(img)
                self.canvas.delete("all")
                self.canvas.create_image(0, 0, anchor="nw", image=self.pdf_image)
                # Cập nhật kích thước canvas
                self.canvas.config(width=pix.width, height=pix.height)
                self.canvas.config(scrollregion=self.canvas.bbox(tk.ALL))
                self.render_text_on_page()
            except Exception as e:
                messagebox.showerror("Lỗi", f"Không thể hiển thị trang: {e}")
    
    def prev_page(self):
        """Chuyển đến trang trước của PDF hoặc xem trước."""
        if self.preview_doc and self.preview_page_index > 0:
            self.preview_page_index -= 1
            self.display_preview_page()
        elif self.pdf_doc:
            if self.current_page_index > 0:
                self.current_page_index -= 1
                self.display_pdf_page()
    
    def next_page(self):
        """Chuyển đến trang tiếp theo của PDF hoặc xem trước."""
        if self.preview_doc and self.preview_page_index < len(self.preview_doc) - 1:
            self.preview_page_index += 1
            self.display_preview_page()
        elif self.pdf_doc:
            if self.current_page_index < len(self.pdf_doc) - 1:
                self.current_page_index += 1
                self.display_pdf_page()
    
    def render_text_on_page(self):
        """Hiển thị các trường văn bản và hình ảnh trên trang."""
        self.current_selected_text = None  # Đặt lại lựa chọn hiện tại
        page_items = self.coords.get(self.current_page_index, [])
        for item in page_items:
            x = item["x"] * self.zoom_level
            y = item["y"] * self.zoom_level
            if item.get('type', 'Text') == 'Text':
                text_id = self.canvas.create_text(x, y, text=f"<{item['field']}>", anchor="center", fill="red")
                self.canvas.itemconfig(text_id, font=(item["font"], int(item["size"] * self.zoom_level)))
                c = item['color_cmyk']['C'] / 100
                m = item['color_cmyk']['M'] / 100
                y_col = item['color_cmyk']['Y'] / 100
                k = item['color_cmyk']['K'] / 100
                r, g, b = self.cmyk_to_rgb(c, m, y_col, k)
                color = f'#{int(r):02x}{int(g):02x}{int(b):02x}'
                self.canvas.itemconfig(text_id, fill=color)
                item["id"] = text_id  # Cập nhật ID trong coords
            elif item.get('type') == 'Image':
                width = item["width_points"] * self.zoom_level
                height = item["height_points"] * self.zoom_level
                rect_id = self.canvas.create_rectangle(
                    x - width/2,
                    y - height/2,
                    x + width/2,
                    y + height/2,
                    outline='blue', dash=(2,2)
                )
                label_id = self.canvas.create_text(x, y, text=f"<{item['field']}>", anchor="center", fill="blue")
                item["id"] = rect_id
                item["label_id"] = label_id
    
    def canvas_click(self, event):
        """Xử lý sự kiện click chuột trên canvas."""
        clicked_items = self.canvas.find_withtag(tk.CURRENT)
        if clicked_items:
            clicked_item = clicked_items[0]
            item_type = self.canvas.type(clicked_item)
            if item_type == "text" or item_type == "rectangle":
                if event.state & 0x0001 or event.state & 0x0004:  # Shift hoặc Control được nhấn
                    if clicked_item in self.selected_items:
                        self.selected_items.remove(clicked_item)
                        # Bỏ chọn
                        self.deselect_item(clicked_item)
                    else:
                        self.selected_items.add(clicked_item)
                        # Chọn
                        self.select_item(clicked_item)
                else:
                    # Xóa lựa chọn trước đó
                    for item in self.selected_items:
                        self.deselect_item(item)
                    self.selected_items = set([clicked_item])
                    self.select_item(clicked_item)
            else:
                self.add_text(event.x, event.y)
        else:
            self.add_text(event.x, event.y)
        self.update_preview()
    
    def select_item(self, item_id):
        """Hiển thị mục được chọn."""
        item_type = self.canvas.type(item_id)
        if item_type == "rectangle":
            self.canvas.itemconfig(item_id, outline='yellow', width=2)
        elif item_type == "text":
            self.canvas.itemconfig(item_id, fill='yellow')
    
        field = self.get_field_by_text_id(item_id)
        if field and field.get('label_id'):
            self.canvas.itemconfig(field['label_id'], fill='yellow')
    
    def deselect_item(self, item_id):
        """Bỏ chọn mục."""
        item_type = self.canvas.type(item_id)
        if item_type == "rectangle":
            self.canvas.itemconfig(item_id, outline='blue', width=1)
        elif item_type == "text":
            self.canvas.itemconfig(item_id, fill='red')
    
        field = self.get_field_by_text_id(item_id)
        if field and field.get('label_id'):
            self.canvas.itemconfig(field['label_id'], fill='blue')
    
    def get_field_by_text_id(self, text_id):
        """Lấy thuộc tính của trường dựa trên ID."""
        page_items = self.coords.get(self.current_page_index, [])
        for item in page_items:
            if item["id"] == text_id or item.get("label_id") == text_id:
                return item
        return None
    
    def add_text(self, x, y):
        """Thêm trường văn bản hoặc hình ảnh mới vào canvas và coords."""
        field = self.selected_field.get()
        field_type = self.field_type.get()
    
        x /= self.zoom_level
        y /= self.zoom_level
    
        if field_type == "Text":
            display_x = x * self.zoom_level
            display_y = y * self.zoom_level
            text_id = self.canvas.create_text(display_x, display_y, text=f"<{field}>", anchor="center", fill="red")
            if self.current_page_index not in self.coords:
                self.coords[self.current_page_index] = []
            new_item = {
                "id": text_id,
                "field": field,
                "x": x,
                "y": y,
                "type": "Text",
                "font": self.font_var.get(),
                "size": self.font_size_var.get(),
                "color_cmyk": {
                    "C": self.cmyk_vars["C"].get(),
                    "M": self.cmyk_vars["M"].get(),
                    "Y": self.cmyk_vars["Y"].get(),
                    "K": self.cmyk_vars["K"].get(),
                }
            }
            self.coords[self.current_page_index].append(new_item)
            self.selected_items = set([text_id])
            self.update_canvas_font()
            self.undo_stack.append(('add', new_item))
            self.redo_stack.clear()  # Xóa ngăn xếp redo
        elif field_type == "Image":
            width_in_points = self.mm_to_points(self.image_width_var.get())
            height_in_points = self.mm_to_points(self.image_height_var.get())
            display_x = x * self.zoom_level
            display_y = y * self.zoom_level
            display_width = width_in_points * self.zoom_level
            display_height = height_in_points * self.zoom_level
            rect_id = self.canvas.create_rectangle(
                display_x - display_width/2,
                display_y - display_height/2,
                display_x + display_width/2,
                display_y + display_height/2,
                outline='blue', dash=(2,2)
            )
            label_id = self.canvas.create_text(display_x, display_y, text=f"<{field}>", anchor="center", fill="blue")
            if self.current_page_index not in self.coords:
                self.coords[self.current_page_index] = []
            new_item = {
                "id": rect_id,
                "label_id": label_id,
                "field": field,
                "x": x,
                "y": y,
                "type": "Image",
                "width_mm": self.image_width_var.get(),
                "height_mm": self.image_height_var.get(),
                "width_points": width_in_points,
                "height_points": height_in_points,
            }
            self.coords[self.current_page_index].append(new_item)
            self.selected_items = set([rect_id])
            self.undo_stack.append(('add', new_item))
            self.redo_stack.clear()
        self.update_preview()
    
    def move_text(self, event):
        """Xử lý di chuyển trường văn bản hoặc hình ảnh trên canvas."""
        if self.selected_items:
            for item_id in self.selected_items:
                prev_coords = self.canvas.coords(item_id)
                if len(prev_coords) == 2:
                    x0, y0 = prev_coords[0], prev_coords[1]
                else:
                    x0 = (prev_coords[0] + prev_coords[2]) / 2
                    y0 = (prev_coords[1] + prev_coords[3]) / 2
                dx = event.x - x0
                dy = event.y - y0
                self.canvas.move(item_id, dx, dy)
                field = self.get_field_by_text_id(item_id)
                if field:
                    self.canvas.move(field.get("label_id", ""), dx, dy)
                    field["x"] += dx / self.zoom_level
                    field["y"] += dy / self.zoom_level
            self.undo_stack.append(('move', list(self.selected_items), dx / self.zoom_level, dy / self.zoom_level))
            self.redo_stack.clear()
            self.update_preview()
    
    def update_canvas_font(self, event=None):
        """Cập nhật thuộc tính font của văn bản được chọn."""
        if self.selected_items:
            for item_id in self.selected_items:
                field = self.get_field_by_text_id(item_id)
                if field and field.get('type', 'Text') == 'Text':
                    # Kiểm tra kích thước font
                    try:
                        size = int(self.font_size_var.get())
                        if size <= 0:
                            raise ValueError
                    except ValueError:
                        messagebox.showerror("Lỗi nhập liệu", "Kích thước font phải là số nguyên dương.")
                        self.font_size_var.set(12)
                        return
    
                    self.canvas.itemconfig(item_id, font=(self.font_var.get(), int(self.font_size_var.get() * self.zoom_level)))
                    c = self.cmyk_vars['C'].get() / 100
                    m = self.cmyk_vars['M'].get() / 100
                    y = self.cmyk_vars['Y'].get() / 100
                    k = self.cmyk_vars['K'].get() / 100
                    r, g, b = self.cmyk_to_rgb(c, m, y, k)
                    color = f'#{int(r):02x}{int(g):02x}{int(b):02x}'
                    self.canvas.itemconfig(item_id, fill=color)
                    field["font"] = self.font_var.get()
                    field["size"] = self.font_size_var.get()
                    field["color_cmyk"] = {
                        "C": self.cmyk_vars["C"].get(),
                        "M": self.cmyk_vars["M"].get(),
                        "Y": self.cmyk_vars["Y"].get(),
                        "K": self.cmyk_vars["K"].get(),
                    }
            self.update_preview()
    
    def delete_text(self, event=None):
        """Xóa văn bản hoặc hình ảnh được chọn trên canvas."""
        if self.selected_items:
            for item_id in list(self.selected_items):
                field = self.get_field_by_text_id(item_id)
                if field:
                    # Xóa các mục liên quan
                    items_to_delete = [field["id"]]
                    if field.get('type', 'Text'):
                        pass
                    elif field.get('type', 'Image'):
                        items_to_delete.append(field.get("label_id", ""))
                    for item_id_del in items_to_delete:
                        self.canvas.delete(item_id_del)
                    self.coords[self.current_page_index].remove(field)
                    self.undo_stack.append(('delete', field))
                    self.redo_stack.clear()  # Xóa ngăn xếp redo
            self.selected_items.clear()
            self.update_preview()
    
    def undo(self, event=None):
        """Undo hành động cuối cùng."""
        if self.undo_stack:
            action = self.undo_stack.pop()
            if action[0] == 'add':
                # Xóa mục đã thêm
                item = action[1]
                self.canvas.delete(item["id"])
                if item.get("label_id"):
                    self.canvas.delete(item["label_id"])
                self.coords[self.current_page_index].remove(item)
                self.redo_stack.append(('add', item))
            elif action[0] == 'move':
                # Di chuyển trở lại vị trí trước đó
                item_ids, dx, dy = action[1:]
                for item_id in item_ids:
                    self.canvas.move(item_id, -dx * self.zoom_level, -dy * self.zoom_level)
                    field = self.get_field_by_text_id(item_id)
                    if field:
                        self.canvas.move(field.get("label_id", ""), -dx * self.zoom_level, -dy * self.zoom_level)
                        field["x"] -= dx
                        field["y"] -= dy
                self.redo_stack.append(('move', item_ids, dx, dy))
            elif action[0] == 'delete':
                # Thêm lại mục đã xóa
                item = action[1]
                if item.get('type', 'Text') == 'Text':
                    x = item["x"] * self.zoom_level
                    y = item["y"] * self.zoom_level
                    text_id = self.canvas.create_text(x, y, text=f"<{item['field']}>", anchor="center", fill="red")
                    self.canvas.itemconfig(text_id, font=(item["font"], int(item["size"] * self.zoom_level)))
                    c = item['color_cmyk']['C'] / 100
                    m = item['color_cmyk']['M'] / 100
                    y_col = item['color_cmyk']['Y'] / 100
                    k = item['color_cmyk']['K'] / 100
                    r, g, b = self.cmyk_to_rgb(c, m, y_col, k)
                    color = f'#{int(r):02x}{int(g):02x}{int(b):02x}'
                    self.canvas.itemconfig(text_id, fill=color)
                    item["id"] = text_id
                elif item.get('type') == 'Image':
                    x = item["x"] * self.zoom_level
                    y = item["y"] * self.zoom_level
                    width = item["width_points"] * self.zoom_level
                    height = item["height_points"] * self.zoom_level
                    rect_id = self.canvas.create_rectangle(
                        x - width/2,
                        y - height/2,
                        x + width/2,
                        y + height/2,
                        outline='blue', dash=(2,2)
                    )
                    label_id = self.canvas.create_text(x, y, text=f"<{item['field']}>", anchor="center", fill="blue")
                    item["id"] = rect_id
                    item["label_id"] = label_id
                self.coords[self.current_page_index].append(item)
                self.redo_stack.append(('delete', item))
            self.update_preview()
    
    def redo(self, event=None):
        """Redo hành động đã undo."""
        if self.redo_stack:
            action = self.redo_stack.pop()
            if action[0] == 'add':
                # Thêm lại mục
                item = action[1]
                if item.get('type', 'Text') == 'Text':
                    x = item["x"] * self.zoom_level
                    y = item["y"] * self.zoom_level
                    text_id = self.canvas.create_text(x, y, text=f"<{item['field']}>", anchor="center", fill="red")
                    self.canvas.itemconfig(text_id, font=(item["font"], int(item["size"] * self.zoom_level)))
                    c = item['color_cmyk']['C'] / 100
                    m = item['color_cmyk']['M'] / 100
                    y_col = item['color_cmyk']['Y'] / 100
                    k = item['color_cmyk']['K'] / 100
                    r, g, b = self.cmyk_to_rgb(c, m, y_col, k)
                    color = f'#{int(r):02x}{int(g):02x}{int(b):02x}'
                    self.canvas.itemconfig(text_id, fill=color)
                    item["id"] = text_id
                elif item.get('type') == 'Image':
                    x = item["x"] * self.zoom_level
                    y = item["y"] * self.zoom_level
                    width = item["width_points"] * self.zoom_level
                    height = item["height_points"] * self.zoom_level
                    rect_id = self.canvas.create_rectangle(
                        x - width/2,
                        y - height/2,
                        x + width/2,
                        y + height/2,
                        outline='blue', dash=(2,2)
                    )
                    label_id = self.canvas.create_text(x, y, text=f"<{item['field']}>", anchor="center", fill="blue")
                    item["id"] = rect_id
                    item["label_id"] = label_id
                self.coords[self.current_page_index].append(item)
                self.undo_stack.append(('add', item))
            elif action[0] == 'move':
                # Di chuyển đến vị trí mới
                item_ids, dx, dy = action[1:]
                for item_id in item_ids:
                    self.canvas.move(item_id, dx * self.zoom_level, dy * self.zoom_level)
                    field = self.get_field_by_text_id(item_id)
                    if field:
                        self.canvas.move(field.get("label_id", ""), dx * self.zoom_level, dy * self.zoom_level)
                        field["x"] += dx
                        field["y"] += dy
                self.undo_stack.append(('move', item_ids, dx, dy))
            elif action[0] == 'delete':
                # Xóa mục
                item = action[1]
                self.canvas.delete(item["id"])
                if item.get("label_id"):
                    self.canvas.delete(item["label_id"])
                self.coords[self.current_page_index].remove(item)
                self.undo_stack.append(('delete', item))
            self.update_preview()
    
    def load_excel(self):
        """Tải tệp Excel và hiển thị dữ liệu."""
        self.excel_path = filedialog.askopenfilename(filetypes=[("Excel files", "*.xlsx"), ("Excel files", "*.xls")])
        if self.excel_path:
            try:
                self.df = pd.read_excel(self.excel_path)
                self.fields = self.df.columns.tolist()
                self.text_area.delete(1.0, tk.END)
                self.text_area.insert(tk.END, self.df.to_string())
                self.create_field_radiobuttons()
                self.reset_preview()
            except Exception as e:
                messagebox.showerror("Lỗi", f"Không thể đọc tệp Excel: {e}")
                self.excel_path = None
                self.df = None
    
    def create_field_radiobuttons(self):
        """Tạo các nút radio cho các trường dữ liệu Excel."""
        # Xóa khung nút hiện có và tạo mới
        for widget in self.excel_button_frame.winfo_children():
            widget.destroy()
    
        # Tạo canvas để chứa các nút với thanh cuộn
        canvas = tk.Canvas(self.excel_button_frame, bg='#2c2f33', highlightthickness=0)
        scrollbar = tk.Scrollbar(self.excel_button_frame, orient=tk.HORIZONTAL, command=canvas.xview)
        canvas.configure(xscrollcommand=scrollbar.set)
    
        inner_frame = tk.Frame(canvas, bg='#2c2f33')
    
        # Thêm inner_frame vào canvas
        canvas.create_window((0, 0), window=inner_frame, anchor='nw')
    
        canvas.pack(side=tk.TOP, fill=tk.X, expand=True)
        scrollbar.pack(side=tk.BOTTOM, fill=tk.X)
    
        # Cập nhật scrollregion sau khi thêm widget
        def configure_canvas(event):
            canvas.configure(scrollregion=canvas.bbox("all"))
        inner_frame.bind("<Configure>", configure_canvas)
    
        # Đặt tất cả các nút trong inner_frame
        for field in self.fields:
            rb = tk.Radiobutton(inner_frame, text=field, variable=self.selected_field, value=field,
                                bg='#2c2f33', fg='white', selectcolor='#7289da')
            rb.pack(side=tk.LEFT, padx=5, pady=5)
        canvas.config(scrollregion=canvas.bbox("all"))
    
    def cmyk_to_rgb(self, c, m, y, k):
        """Chuyển đổi giá trị CMYK sang RGB."""
        r = min(max(0, 255 * (1 - c) * (1 - k)), 255)
        g = min(max(0, 255 * (1 - m) * (1 - k)), 255)
        b = min(max(0, 255 * (1 - y) * (1 - k)), 255)
        return int(r), int(g), int(b)
    
    def mm_to_points(self, mm):
        """Chuyển đổi millimeters sang points."""
        return mm * 72 / 25.4
    
    def points_to_mm(self, points):
        """Chuyển đổi points sang millimeters."""
        return points * 25.4 / 72
    
    def create_text_pdf(self, output_pdf_path, row, selected_font_path):
        """Tạo tệp PDF tùy chỉnh với các trường văn bản và hình ảnh."""
        c = reportlab_canvas.Canvas(output_pdf_path, pagesize=(self.original_width, self.original_height))
        total_pages = len(self.pdf_doc)
    
        for page_index in range(total_pages):
            c.setPageSize((self.original_width, self.original_height))  # Thiết lập kích thước trang cho mỗi trang
            if page_index in self.coords:
                fields = self.coords[page_index]
                for item in fields:
                    field_name = item["field"]
                    if field_name not in row:
                        print(f"Trường '{field_name}' không có trong dữ liệu. Bỏ qua...")
                        continue
                    x = item["x"]
                    y = item["y"]
                    if item.get('type', 'Text') == 'Text':
                        font_name = item["font"]
                        size = item["size"]
                        color_cmyk = item["color_cmyk"]
    
                        # Lấy đường dẫn font
                        font_path = self.font_file_dict.get(font_name, selected_font_path)
                        if not self.check_font_availability(font_path):
                            font_path = selected_font_path
    
                        # Đăng ký và đặt font
                        if font_name not in pdfmetrics.getRegisteredFontNames():
                            pdfmetrics.registerFont(TTFont(font_name, font_path))
                        c.setFont(font_name, size)
    
                        # Đặt màu
                        c.setFillColorCMYK(
                            color_cmyk["C"] / 100,
                            color_cmyk["M"] / 100,
                            color_cmyk["Y"] / 100,
                            color_cmyk["K"] / 100
                        )
    
                        value = str(row[field_name])
                        adjusted_y = self.original_height - y
                        text_width = c.stringWidth(value, font_name, size)
                        adjusted_x = x - text_width / 2
    
                        c.drawString(adjusted_x, adjusted_y, value)
                    elif item.get('type') == 'Image':
                        image_path = str(row[field_name])
                        if not os.path.isabs(image_path):
                            image_path = os.path.join(os.path.dirname(self.excel_path), image_path)
                        if not os.path.exists(image_path):
                            print(f"Hình ảnh '{image_path}' không tồn tại. Bỏ qua...")
                            continue
                        # Sử dụng chiều rộng và chiều cao đã lưu
                        width_in_points = item["width_points"]
                        height_in_points = item["height_points"]
                        adjusted_y = self.original_height - y - height_in_points / 2
                        adjusted_x = x - width_in_points / 2
                        try:
                            c.drawImage(image_path, adjusted_x, adjusted_y,
                                        width=width_in_points,
                                        height=height_in_points)
                        except Exception as e:
                            print(f"Lỗi khi chèn hình ảnh: {e}")
    
            # Kết thúc trang hiện tại
            c.showPage()
    
        c.save()
    
    def export_pdfs(self):
        """Xuất các tệp PDF với dữ liệu từ Excel và merge chúng."""
        if not self.file_path or not self.excel_path:
            messagebox.showerror("Lỗi", "Hãy chọn tệp và Excel trước khi xuất.")
            return
        if not self.coords:
            messagebox.showerror("Lỗi", "Chưa đặt trường nào trên tệp.")
            return
    
        output_folder = filedialog.askdirectory()
        if not output_folder:
            return
    
        selected_font_name = self.font_var.get()
        selected_font_path = self.font_file_dict.get(selected_font_name, None)
        if not selected_font_path or not self.check_font_availability(selected_font_path):
            messagebox.showerror("Lỗi", f"Không thể mở tệp font {selected_font_name}, sử dụng font mặc định.")
            if sys.platform == "win32":
                selected_font_path = "C:/Windows/Fonts/Arial.ttf"
            else:
                selected_font_path = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
    
        # Danh sách lưu các tệp PDF cá nhân
        individual_pdfs = []
    
        for index, row in self.df.iterrows():
            doc = fitz.open(self.temp_pdf_path)
    
            # Tạo tên tệp duy nhất
            fields_in_name = '_'.join([str(row[field]) for field in self.fields[:3]])  # Tùy chỉnh nếu cần
            output_pdf_path = os.path.join(output_folder, f"{fields_in_name}_custom.pdf")
    
            # Tạo PDF tùy chỉnh
            self.create_text_pdf(output_pdf_path, row, selected_font_path)
    
            # Mở PDF tùy chỉnh
            new_doc = fitz.open(output_pdf_path)
    
            # Đảm bảo new_doc có cùng số trang
            if new_doc.page_count != len(doc):
                messagebox.showerror("Lỗi", "Số trang trong tệp gốc và tệp mới không khớp.")
                new_doc.close()
                doc.close()
                continue
    
            # Overlay các trang tùy chỉnh lên tệp gốc
            for page_num in range(len(doc)):
                page = doc.load_page(page_num)
                rect = fitz.Rect(0, 0, self.original_width, self.original_height)
                page.show_pdf_page(rect, new_doc, page_num)
    
            new_doc.close()
    
            # Lưu PDF cuối cùng
            final_output_path = os.path.join(output_folder, f"{fields_in_name}_final.pdf")
            doc.save(final_output_path)
            individual_pdfs.append(final_output_path)
    
            doc.close()
    
        # Xóa tệp PDF tùy chỉnh tạm thời
        try:
            os.remove(output_pdf_path)
        except Exception as e:
            print(f"Lỗi khi xóa tệp tạm: {e}")
    
        # Merge các tệp PDF
        if individual_pdfs:
            merged_pdf_path = os.path.join(output_folder, "merged_final_output.pdf")
            self.merge_pdfs(individual_pdfs, merged_pdf_path)
            messagebox.showinfo("Thành công", "File PDF đã được xuất thành công với dữ liệu từ Excel.")
    
            # Hỏi người dùng có muốn áp dụng imposition không
            if messagebox.askyesno("Imposition", "Bạn có muốn áp dụng imposition cho file PDF đã xuất không?"):
                # Lấy các thông số từ giao diện
                new_page_width = self.new_page_width_var.get()
                new_page_height = self.new_page_height_var.get()
                margin_top = self.margin_top_var.get()
                margin_bottom = self.margin_bottom_var.get()
                margin_left = self.margin_left_var.get()
                margin_right = self.margin_right_var.get()
                cropmark_offset = self.cropmark_offset_var.get()
    
                # Chuyển đổi các đơn vị từ mm sang points
                new_page_width_pt = self.mm_to_points(new_page_width)
                new_page_height_pt = self.mm_to_points(new_page_height)
                margin_top_pt = self.mm_to_points(margin_top)
                margin_bottom_pt = self.mm_to_points(margin_bottom)
                margin_left_pt = self.mm_to_points(margin_left)
                margin_right_pt = self.mm_to_points(margin_right)
                cropmark_offset_pt = self.mm_to_points(cropmark_offset)
    
                # Áp dụng imposition
                imposed_pdf_path = os.path.join(output_folder, "imposed_output.pdf")
                self.apply_imposition(merged_pdf_path, imposed_pdf_path)
    
                messagebox.showinfo("Thành công", f"Imposition đã được áp dụng. File PDF đã được lưu tại {imposed_pdf_path}")
            else:
                messagebox.showinfo("Thành công", f"File PDF đã được lưu tại {merged_pdf_path}")
        else:
            messagebox.showerror("Lỗi", "Không có file PDF nào được tạo.")
    
    def merge_pdfs(self, pdf_paths, output_path):
        """Merge nhiều tệp PDF thành một."""
        merged_doc = fitz.open()
        for pdf_path in pdf_paths:
            individual_doc = fitz.open(pdf_path)
            merged_doc.insert_pdf(individual_doc)
            individual_doc.close()
        merged_doc.save(output_path)
        merged_doc.close()
    
    def align_left(self):
        if not self.selected_items:
            messagebox.showinfo("Thông báo", "Chưa chọn mục nào để căn chỉnh.")
            return
        min_x = None
        for item_id in self.selected_items:
            field = self.get_field_by_text_id(item_id)
            if field:
                x = field['x']
                if min_x is None or x < min_x:
                    min_x = x
        for item_id in self.selected_items:
            field = self.get_field_by_text_id(item_id)
            if field:
                dx = (min_x - field['x']) * self.zoom_level
                self.canvas.move(item_id, dx, 0)
                field['x'] = min_x
                if field.get('label_id'):
                    self.canvas.move(field['label_id'], dx, 0)
        self.update_preview()
    
    def align_right(self):
        if not self.selected_items:
            messagebox.showinfo("Thông báo", "Chưa chọn mục nào để căn chỉnh.")
            return
        max_x = None
        for item_id in self.selected_items:
            field = self.get_field_by_text_id(item_id)
            if field:
                x = field['x']
                if max_x is None or x > max_x:
                    max_x = x
        for item_id in self.selected_items:
            field = self.get_field_by_text_id(item_id)
            if field:
                dx = (max_x - field['x']) * self.zoom_level
                self.canvas.move(item_id, dx, 0)
                field['x'] = max_x
                if field.get('label_id'):
                    self.canvas.move(field['label_id'], dx, 0)
        self.update_preview()
    
    def align_top(self):
        if not self.selected_items:
            messagebox.showinfo("Thông báo", "Chưa chọn mục nào để căn chỉnh.")
            return
        min_y = None
        for item_id in self.selected_items:
            field = self.get_field_by_text_id(item_id)
            if field:
                y = field['y']
                if min_y is None or y < min_y:
                    min_y = y
        for item_id in self.selected_items:
            field = self.get_field_by_text_id(item_id)
            if field:
                dy = (min_y - field['y']) * self.zoom_level
                self.canvas.move(item_id, 0, dy)
                field['y'] = min_y
                if field.get('label_id'):
                    self.canvas.move(field['label_id'], 0, dy)
        self.update_preview()
    
    def align_bottom(self):
        if not self.selected_items:
            messagebox.showinfo("Thông báo", "Chưa chọn mục nào để căn chỉnh.")
            return
        max_y = None
        for item_id in self.selected_items:
            field = self.get_field_by_text_id(item_id)
            if field:
                y = field['y']
                if max_y is None or y > max_y:
                    max_y = y
        for item_id in self.selected_items:
            field = self.get_field_by_text_id(item_id)
            if field:
                dy = (max_y - field['y']) * self.zoom_level
                self.canvas.move(item_id, 0, dy)
                field['y'] = max_y
                if field.get('label_id'):
                    self.canvas.move(field['label_id'], 0, dy)
        self.update_preview()
    
    def align_center(self):
        if not self.selected_items:
            messagebox.showinfo("Thông báo", "Chưa chọn mục nào để căn chỉnh.")
            return
        total_x = 0
        count = 0
        for item_id in self.selected_items:
            field = self.get_field_by_text_id(item_id)
            if field:
                total_x += field['x']
                count += 1
        if count == 0:
            return
        avg_x = total_x / count
        for item_id in self.selected_items:
            field = self.get_field_by_text_id(item_id)
            if field:
                dx = (avg_x - field['x']) * self.zoom_level
                self.canvas.move(item_id, dx, 0)
                field['x'] = avg_x
                if field.get('label_id'):
                    self.canvas.move(field['label_id'], dx, 0)
        self.update_preview()
    
    def zoom_in(self):
        self.zoom_level *= 1.1
        self.display_pdf_page()
        self.display_preview_page()
    
    def zoom_out(self):
        self.zoom_level /= 1.1
        self.display_pdf_page()
        self.display_preview_page()
    
    def zoom_with_mouse_wheel(self, event):
        if event.delta > 0 or event.num == 4:
            self.zoom_in()
        elif event.delta < 0 or event.num == 5:
            self.zoom_out()
    
    def preview_pdf(self):
        """Tạo và hiển thị PDF xem trước với áp dụng impose."""
        if not self.file_path or not self.excel_path:
            messagebox.showerror("Lỗi", "Hãy chọn tệp và Excel trước khi xem trước.")
            return
        if not self.coords:
            messagebox.showerror("Lỗi", "Chưa đặt trường nào trên tệp.")
            return
    
        # Kiểm tra chỉ số hàng hợp lệ
        if self.excel_row_index < 0 or self.excel_row_index >= len(self.df):
            messagebox.showerror("Lỗi", "Chỉ số hàng không hợp lệ.")
            return
    
        # Tạo PDF xem trước trong thư mục tạm
        temp_dir = tempfile.gettempdir()
        self.preview_pdf_path = os.path.join(temp_dir, "preview.pdf")
    
        selected_font_name = self.font_var.get()
        selected_font_path = self.font_file_dict.get(selected_font_name, None)
        if not selected_font_path or not self.check_font_availability(selected_font_path):
            if sys.platform == "win32":
                selected_font_path = "C:/Windows/Fonts/Arial.ttf"
            else:
                selected_font_path = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
    
        # Sử dụng hàng dữ liệu hiện tại
        current_row = self.df.iloc[self.excel_row_index]
    
        # Tạo PDF tùy chỉnh
        self.create_text_pdf(self.preview_pdf_path, current_row, selected_font_path)
    
        # Mở PDF tùy chỉnh
        self.preview_doc = fitz.open(self.preview_pdf_path)
    
        # Mở tệp gốc và kết hợp dữ liệu
        merged_doc = fitz.open(self.temp_pdf_path)
        for page_num in range(len(merged_doc)):
            page = merged_doc.load_page(page_num)
            rect = fitz.Rect(0, 0, self.original_width, self.original_height)
            page.show_pdf_page(rect, self.preview_doc, page_num)
    
        # Đóng tài liệu xem trước cũ
        self.preview_doc.close()
    
        self.preview_page_index = 0
        self.preview_doc = merged_doc
    
        # Áp dụng Imposition và lưu vào tệp mới
        imposed_preview_pdf_path = os.path.join(temp_dir, "imposed_preview.pdf")
    
        # Áp dụng imposition trong quá trình preview
        self.apply_imposition(self.preview_pdf_path, imposed_preview_pdf_path)
    
        # Cập nhật đường dẫn và mở lại tệp xem trước đã áp dụng imposition
        self.preview_pdf_path = imposed_preview_pdf_path
        self.preview_doc = fitz.open(self.preview_pdf_path)
    
        self.is_previewing = True
        self.preview_page_index = 0
    
        # Hiển thị trang xem trước
        self.display_preview_page()
    
    
    def prev_preview(self):
        """Chuyển đến hàng dữ liệu trước trong Excel và cập nhật xem trước."""
        if self.excel_row_index > 0:
            self.excel_row_index -= 1
            self.preview_pdf()
    
    def next_preview(self):
        """Chuyển đến hàng dữ liệu tiếp theo trong Excel và cập nhật xem trước."""
        if self.excel_row_index < len(self.df) - 1:
            self.excel_row_index += 1
            self.preview_pdf()
    
    def display_preview_page(self):
        """Hiển thị trang hiện tại của PDF xem trước."""
        if self.preview_doc and 0 <= self.preview_page_index < len(self.preview_doc):
            try:
                page = self.preview_doc.load_page(self.preview_page_index)
                zoom_matrix = fitz.Matrix(self.zoom_level, self.zoom_level)
                pix = page.get_pixmap(matrix=zoom_matrix)
                img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
                self.preview_image = ImageTk.PhotoImage(img)
                self.preview_canvas.delete("all")
                self.preview_canvas.create_image(0, 0, anchor="nw", image=self.preview_image)
                self.preview_canvas.config(width=pix.width, height=pix.height)
                self.preview_canvas.config(scrollregion=self.preview_canvas.bbox(tk.ALL))
            except Exception as e:
                messagebox.showerror("Lỗi", f"Không thể hiển thị trang xem trước: {e}")
    
    def update_preview(self):
        """Cập nhật xem trước khi có thay đổi."""
        if self.is_previewing:
            self.preview_pdf()
    
    def reset_preview(self):
        """Đặt lại xem trước khi tải tệp hoặc Excel mới."""
        self.preview_doc = None
        self.preview_pdf_path = None
        self.preview_page_index = 0
        self.is_previewing = False
        self.excel_row_index = 0  # Đặt lại chỉ số hàng dữ liệu
    
    def on_closing(self):
        """Xử lý khi đóng ứng dụng."""
        if hasattr(self, 'temp_pdf_path') and os.path.exists(self.temp_pdf_path):
            try:
                os.remove(self.temp_pdf_path)
            except Exception as e:
                print(f"Lỗi khi xóa tệp tạm: {e}")
        self.root.destroy()
    
    def apply_imposition(self, input_pdf_path, output_pdf_path):
        """Apply Imposition to fit multiple data entries on a single page and center them."""
        
        # Get the new page dimensions and margins from the user inputs
        new_page_width = self.new_page_width_var.get()
        new_page_height = self.new_page_height_var.get()
        margin_top = self.margin_top_var.get()
        margin_bottom = self.margin_bottom_var.get()
        margin_left = self.margin_left_var.get()
        margin_right = self.margin_right_var.get()
        cropmark_offset = self.cropmark_offset_var.get()
    
        # Get the crop mark length from user input
        crop_length_mm = self.cropmark_length_var.get()
        crop_length_pt = self.mm_to_points(crop_length_mm)
    
        # Convert dimensions from mm to points (1 mm = 2.83465 points)
        new_page_width_pt = self.mm_to_points(new_page_width)
        new_page_height_pt = self.mm_to_points(new_page_height)
        margin_top_pt = self.mm_to_points(margin_top)
        margin_bottom_pt = self.mm_to_points(margin_bottom)
        margin_left_pt = self.mm_to_points(margin_left)
        margin_right_pt = self.mm_to_points(margin_right)
        cropmark_offset_pt = self.mm_to_points(cropmark_offset)
    
        # Calculate the available space on the page
        available_width = new_page_width_pt - margin_left_pt - margin_right_pt
        available_height = new_page_height_pt - margin_top_pt - margin_bottom_pt
    
        # Read the input PDF file
        doc = fitz.open(input_pdf_path)
        new_doc = fitz.open()
        total_pages = len(doc)
    
        # Get the size of the data entry (assume all entries have the same size)
        input_page = doc.load_page(0)
        bbox = input_page.rect
        entry_width = bbox.width
        entry_height = bbox.height
    
        # Calculate how many entries fit on the page
        entries_per_row = int(available_width / (entry_width))
        entries_per_column = int(available_height / (entry_height))
    
        # Check if at least one entry fits horizontally and vertically
        if entries_per_row < 1 or entries_per_column < 1:
            messagebox.showerror("Error", "The page size or margins are too small to fit any data entries.")
            return
    
        # Calculate total width and height of the grid (with crop marks and gaps)
        total_grid_width = entries_per_row * entry_width
        total_grid_height = entries_per_column * entry_height
    
        # Calculate the offset to center the grid on the page
        x_offset = (available_width - total_grid_width) / 2 + margin_left_pt
        y_offset = (available_height - total_grid_height) / 2 + margin_top_pt
    
        # Crop mark parameters
        crop_thickness = 0.5  # Default crop mark thickness (in points)
    
        # Place entries on the new pages
        page_index = 0
        while page_index < total_pages:
            new_page = new_doc.new_page(width=new_page_width_pt, height=new_page_height_pt)
            x = x_offset
            y = y_offset
            for row in range(entries_per_column):
                x = x_offset  # Reset X position for each row
                for col in range(entries_per_row):
                    if page_index >= total_pages:
                        break
                    # Position the current entry
                    rect = fitz.Rect(x, y, x + entry_width, y + entry_height)
                    new_page.show_pdf_page(rect, doc, pno=page_index)
    
                    # Add crop marks using user-specified length
                    self.add_crop_marks(new_page, rect, [], cropmark_offset_pt, crop_length_pt, crop_thickness)
    
                    # Move to the next entry horizontally
                    x += entry_width
                    page_index += 1
    
                # Move to the next row vertically
                y += entry_height
    
        # Save the imposed PDF
        new_doc.save(output_pdf_path)
        new_doc.close()
        doc.close()
    
    
    def add_crop_marks(self, page, rect, objects, offset, crop_length, crop_thickness):
        def is_nearby(a, b, tol=1):
            return abs(a - b) < tol
    
        # Các điểm của đối tượng
        x0, y0 = rect.x0, rect.y0
        x1, y1 = rect.x1, rect.y1
        
        # Tạo danh sách crop marks cần thêm
        crop_marks = []
    
        # Kiểm tra và thêm crop mark cho cạnh trên, đảm bảo không chồng lấn
        if not any(is_nearby(rect.y0, other[0].y1) and rect.x0 <= other[0].x1 and rect.x1 >= other[0].x0 for other in objects):
            crop_marks.append([(x0 + offset, y0 - crop_length), (x0 + offset, y0)])  # Trên - trái
            crop_marks.append([(x1 - offset, y0 - crop_length), (x1 - offset, y0)])  # Trên - phải
    
        # Kiểm tra và thêm crop mark cho cạnh dưới
        if not any(is_nearby(rect.y1, other[0].y0) and rect.x0 <= other[0].x1 and rect.x1 >= other[0].x0 for other in objects):
            crop_marks.append([(x0 + offset, y1), (x0 + offset, y1 + crop_length)])  # Dưới - trái
            crop_marks.append([(x1 - offset, y1), (x1 - offset, y1 + crop_length)])  # Dưới - phải
    
        # Kiểm tra và thêm crop mark cho cạnh trái
        if not any(is_nearby(rect.x0, other[0].x1) and rect.y0 <= other[0].y1 and rect.y1 >= other[0].y0 for other in objects):
            crop_marks.append([(x0 - crop_length, y0 + offset), (x0, y0 + offset)])  # Trái - trên
            crop_marks.append([(x0 - crop_length, y1 - offset), (x0, y1 - offset)])  # Trái - dưới
    
        # Kiểm tra và thêm crop mark cho cạnh phải
        if not any(is_nearby(rect.x1, other[0].x0) and rect.y0 <= other[0].y1 and rect.y1 >= other[0].y0 for other in objects):
            crop_marks.append([(x1, y0 + offset), (x1 + crop_length, y0 + offset)])  # Phải - trên
            crop_marks.append([(x1, y1 - offset), (x1 + crop_length, y1 - offset)])  # Phải - dưới
        
        # Vẽ các crop mark
        for start, end in crop_marks:
            page.draw_line(start, end, width=crop_thickness, color=(0.9, 0.1, 0.1))
    
    
    
    

    if name == "main": root = tk.Tk() app = PDFEditorApp(root) root.protocol("WM_DELETE_WINDOW", app.on_closing) root.mainloop() phân tích đoạn mã này và điều chỉnh phần cropmarks sao cho nó đặt xung quanh cạnh các đối tượng sau khi imposion để không bị trường hợp cropmark đè lên các đối tượng khác

  2. Assistant

    Để giải quyết vấn đề cropmarks chồng lấn lên các đối tượng khác sau khi áp dụng imposition, chúng ta cần đảm bảo rằng cropmarks chỉ được thêm vào các cạnh ngoài cùng của lưới (grid) các đối tượng sau khi imposition. Điều này có nghĩa là chúng ta sẽ không thêm cropmarks giữa các đối tượng bên trong lưới, nơi chúng có thể chồng lấn lên các đối tượng khác.

    Giải pháp: Chúng ta sẽ xác định các cạnh ngoài cùng (top, bottom, left, right) của mỗi đối tượng trong lưới và chỉ thêm cropmarks vào các cạnh này. Điều này được thực hiện bằng cách kiểm tra vị trí của đối tượng trong lưới dựa trên chỉ số hàng (row) và cột (col) của nó.

    Dưới đây là cách điều chỉnh mã của bạn:

    1. Trong hàm apply_imposition:

      • Thay vì truyền một danh sách objects trống đến hàm add_crop_marks, chúng ta sẽ xác định các cạnh ngoài cùng của mỗi đối tượng và truyền thông tin này đến hàm add_crop_marks.
      • Xác định các cạnh ngoài cùng dựa trên vị trí của đối tượng trong lưới bằng cách sử dụng các biến row, col, entries_per_row, và entries_per_column.
    2. Trong hàm add_crop_marks:

      • Chỉnh sửa hàm để chấp nhận danh sách edges thay vì objects. Danh sách edges sẽ chứa các cạnh ('top', 'bottom', 'left', 'right') mà chúng ta muốn thêm cropmarks.
      • Chỉ thêm cropmarks vào các cạnh được chỉ định trong danh sách edges.

    Mã điều chỉnh:

    Hàm apply_imposition đã chỉnh sửa:

    def apply_imposition(self, input_pdf_path, output_pdf_path):
        """Apply Imposition to fit multiple data entries on a single page and center them."""
        
        # Get the new page dimensions and margins from the user inputs
        new_page_width = self.new_page_width_var.get()
        new_page_height = self.new_page_height_var.get()
        margin_top = self.margin_top_var.get()
        margin_bottom = self.margin_bottom_var.get()
        margin_left = self.margin_left_var.get()
        margin_right = self.margin_right_var.get()
        cropmark_offset = self.cropmark_offset_var.get()
    
        # Get the crop mark length from user input
        crop_length_mm = self.cropmark_length_var.get()
        crop_length_pt = self.mm_to_points(crop_length_mm)
    
        # Convert dimensions from mm to points (1 mm = 2.83465 points)
        new_page_width_pt = self.mm_to_points(new_page_width)
        new_page_height_pt = self.mm_to_points(new_page_height)
        margin_top_pt = self.mm_to_points(margin_top)
        margin_bottom_pt = self.mm_to_points(margin_bottom)
        margin_left_pt = self.mm_to_points(margin_left)
        margin_right_pt = self.mm_to_points(margin_right)
        cropmark_offset_pt = self.mm_to_points(cropmark_offset)
    
        # Calculate the available space on the page
        available_width = new_page_width_pt - margin_left_pt - margin_right_pt
        available_height = new_page_height_pt - margin_top_pt - margin_bottom_pt
    
        # Read the input PDF file
        doc = fitz.open(input_pdf_path)
        new_doc = fitz.open()
        total_pages = len(doc)
    
        # Get the size of the data entry (assume all entries have the same size)
        input_page = doc.load_page(0)
        bbox = input_page.rect
        entry_width = bbox.width
        entry_height = bbox.height
    
        # Calculate how many entries fit on the page
        entries_per_row = int(available_width / (entry_width))
        entries_per_column = int(available_height / (entry_height))
    
        # Check if at least one entry fits horizontally and vertically
        if entries_per_row < 1 or entries_per_column < 1:
            messagebox.showerror("Error", "The page size or margins are too small to fit any data entries.")
            return
    
        # Calculate total width and height of the grid (with crop marks and gaps)
        total_grid_width = entries_per_row * entry_width
        total_grid_height = entries_per_column * entry_height
    
        # Calculate the offset to center the grid on the page
        x_offset = (available_width - total_grid_width) / 2 + margin_left_pt
        y_offset = (available_height - total_grid_height) / 2 + margin_top_pt
    
        # Crop mark parameters
        crop_thickness = 0.5  # Default crop mark thickness (in points)
    
        # Place entries on the new pages
        page_index = 0
        while page_index < total_pages:
            new_page = new_doc.new_page(width=new_page_width_pt, height=new_page_height_pt)
            x = x_offset
            y = y_offset
            for row in range(entries_per_column):
                x = x_offset  # Reset X position for each row
                for col in range(entries_per_row):
                    if page_index >= total_pages:
                        break
                    # Position the current entry
                    rect = fitz.Rect(x, y, x + entry_width, y + entry_height)
                    new_page.show_pdf_page(rect, doc, pno=page_index)
    
                    # Determine which edges are outer edges
                    edges = []
                    if row == 0:
                        edges.append('top')
                    if row == entries_per_column - 1:
                        edges.append('bottom')
                    if col == 0:
                        edges.append('left')
                    if col == entries_per_row -1:
                        edges.append('right')
    
                    # Add crop marks to the outer edges
                    self.add_crop_marks(new_page, rect, edges, cropmark_offset_pt, crop_length_pt, crop_thickness)
    
                    # Move to the next entry horizontally
                    x += entry_width
                    page_index += 1
    
                # Move to the next row vertically
                y += entry_height
    
        # Save the imposed PDF
        new_doc.save(output_pdf_path)
        new_doc.close()
        doc.close()
    

    Hàm add_crop_marks đã chỉnh sửa:

    def add_crop_marks(self, page, rect, edges, offset, crop_length, crop_thickness):
        # Các điểm của đối tượng
        x0, y0 = rect.x0, rect.y0
        x1, y1 = rect.x1, rect.y1
        
        # Vẽ các crop mark cho các cạnh được chỉ định trong edges
        crop_marks = []
        if 'top' in edges:
            # Trên - trái
            crop_marks.append([(x0 + offset, y0 - crop_length), (x0 + offset, y0)])
            # Trên - phải
            crop_marks.append([(x1 - offset, y0 - crop_length), (x1 - offset, y0)])
        if 'bottom' in edges:
            # Dưới - trái
            crop_marks.append([(x0 + offset, y1), (x0 + offset, y1 + crop_length)])
            # Dưới - phải
            crop_marks.append([(x1 - offset, y1), (x1 - offset, y1 + crop_length)])
        if 'left' in edges:
            # Trái - trên
            crop_marks.append([(x0 - crop_length, y0 + offset), (x0, y0 + offset)])
            # Trái - dưới
            crop_marks.append([(x0 - crop_length, y1 - offset), (x0, y1 - offset)])
        if 'right' in edges:
            # Phải - trên
            crop_marks.append([(x1, y0 + offset), (x1 + crop_length, y0 + offset)])
            # Phải - dưới
            crop_marks.append([(x1, y1 - offset), (x1 + crop_length, y1 - offset)])
        
        # Vẽ các crop mark
        for start, end in crop_marks:
            page.draw_line(start, end, width=crop_thickness, color=(0, 0, 0))
    

    Giải thích chi tiết:

    • Trong apply_imposition:

      • Chúng ta xác định các cạnh ngoài cùng bằng cách kiểm tra nếu row hoặc col ở vị trí đầu hoặc cuối.
        • Nếu row == 0, đối tượng nằm ở hàng đầu tiên và cạnh trên là cạnh ngoài cùng.
        • Nếu row == entries_per_column - 1, đối tượng nằm ở hàng cuối cùng và cạnh dưới là cạnh ngoài cùng.
        • Tương tự cho cột với col == 0 và col == entries_per_row - 1.
      • Danh sách edges sẽ chứa các cạnh mà chúng ta cần thêm cropmarks.
      • Chúng ta truyền danh sách edges này vào hàm add_crop_marks.
    • Trong add_crop_marks:

      • Thay vì kiểm tra chồng lấn với các đối tượng khác (danh sách objects), chúng ta chỉ cần thêm cropmarks vào các cạnh được liệt kê trong edges.
      • Hàm sẽ vẽ các cropmarks tương ứng với mỗi cạnh trong edges.

    Lợi ích của giải pháp này:

    • Không chồng lấn: Bằng cách chỉ thêm cropmarks vào các cạnh ngoài cùng, chúng ta tránh được việc cropmarks chồng lấn lên các đối tượng khác trong lưới.
    • Đơn giản hóa mã: Không cần phải kiểm tra chồng lấn với các đối tượng khác, giúp mã đơn giản và dễ hiểu hơn.
    • Hiệu suất tốt hơn: Giảm số lượng kiểm tra và tính toán, cải thiện hiệu suất của chương trình.

    Lưu ý quan trọng:

    • Đảm bảo rằng các biến như entries_per_row và entries_per_column được tính chính xác dựa trên kích thước trang và kích thước của đối tượng.
    • Đảm bảo rằng kích thước và vị trí của các cropmarks được tính toán chính xác dựa trên các thông số người dùng nhập vào.

    Với các điều chỉnh trên, chương trình của bạn sẽ thêm cropmarks vào đúng vị trí, không chồng lấn lên các đối tượng khác sau khi áp dụng imposition.