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 from tkinterdnd2 import…

  1. User

    import tkinter as tk from tkinter import filedialog, messagebox from tkinterdnd2 import DND_FILES, TkinterDnD import fitz # PyMuPDF import math import os from rectpack import newPacker, MaxRectsBssf, MaxRectsBl, MaxRectsBaf, GuillotineBssfLas, SkylineBl

    class PDFLayoutApp: def init(self, root): self.root = root self.root.title("Máy tính bố trí PDF") self.root.configure(bg="#2E2E2E")

        self.pdf_files = []
        self.pdf_widgets = []
        self.paper_width = tk.DoubleVar(value=650)
        self.paper_height = tk.DoubleVar(value=430)
        self.margin = 0
    
        self.selected_algorithm = tk.StringVar(value="MaxRectsBssf")
    
        self.create_widgets()
        self.root.drop_target_register(DND_FILES)
        self.root.dnd_bind('<<Drop>>', self.drop)
    
    def create_widgets(self):
        self.file_frame = tk.Frame(self.root, bg="#2E2E2E")
        self.file_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
    
        self.add_file_button = tk.Button(self.file_frame, text="Chọn tệp PDF", command=self.add_pdf_file, bg="#444444", fg="#FFFFFF")
        self.add_file_button.grid(row=0, column=0, padx=5, pady=5)
    
        self.paper_size_frame = tk.Frame(self.root, bg="#2E2E2E")
        self.paper_size_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
    
        tk.Label(self.paper_size_frame, text="Chiều rộng giấy (mm):", bg="#2E2E2E", fg="#FFFFFF").grid(row=0, column=0, padx=5, pady=5)
        self.paper_width_entry = tk.Entry(self.paper_size_frame, textvariable=self.paper_width, bg="#444444", fg="#FFFFFF")
        self.paper_width_entry.grid(row=0, column=1, padx=5, pady=5)
    
        tk.Label(self.paper_size_frame, text="Chiều cao giấy (mm):", bg="#2E2E2E", fg="#FFFFFF").grid(row=0, column=2, padx=5, pady=5)
        self.paper_height_entry = tk.Entry(self.paper_size_frame, textvariable=self.paper_height, bg="#444444", fg="#FFFFFF")
        self.paper_height_entry.grid(row=0, column=3, padx=5, pady=5)
    
        tk.Label(self.paper_size_frame, text="Thuật toán đóng gói:", bg="#2E2E2E", fg="#FFFFFF").grid(row=1, column=0, padx=5, pady=5)
        self.algorithm_menu = tk.OptionMenu(self.paper_size_frame, self.selected_algorithm,
                                            "MaxRectsBssf", "MaxRectsBl", "MaxRectsBaf",
                                            "GuillotineBssf", "GuillotineBssfLas", "SkylineBl")
        self.algorithm_menu.config(bg="#444444", fg="#FFFFFF")
        self.algorithm_menu.grid(row=1, column=1, padx=5, pady=5)
    
        self.calculate_button = tk.Button(self.root, text="Tính toán bố trí", command=self.calculate_layout, bg="#444444", fg="#FFFFFF")
        self.calculate_button.pack(fill=tk.X, padx=10, pady=10)
    
        self.result_text = tk.Text(self.root, height=20, bg="#444444", fg="#FFFFFF")
        self.result_text.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
    
    def add_pdf_file(self):
        file_paths = filedialog.askopenfilenames(filetypes=[("Tệp PDF", "*.pdf")])
        self.process_files(file_paths)
    
    def drop(self, event):
        file_paths = self.root.tk.splitlist(event.data)
        self.process_files(file_paths)
    
    def process_files(self, file_paths):
        for file_path in file_paths:
            if file_path.endswith('.pdf'):
                try:
                    doc = fitz.open(file_path)
                    first_page = doc[0]
                    size = first_page.rect
    
                    pdf_info = {
                        "path": file_path,
                        "width": size.width * 25.4 / 72,  # Chuyển từ điểm sang mm
                        "height": size.height * 25.4 / 72,
                        "count": tk.IntVar(value=0),
                        "cropmarks": tk.BooleanVar(value=False),  # Thêm tùy chọn cropmarks cho từng PDF
                        "cropmark_offset": tk.DoubleVar(value=5.0)  # Thêm tùy chọn khoảng cách cropmarks
                    }
    
                    self.pdf_files.append(pdf_info)
                    self.update_file_widgets()
                except Exception as e:
                    messagebox.showerror("Lỗi tệp", f"Không thể mở tệp '{file_path}': {e}")
    
    def update_file_widgets(self):
        for widget in self.file_frame.winfo_children():
            widget.destroy()
    
        self.add_file_button = tk.Button(self.file_frame, text="Chọn tệp PDF", command=self.add_pdf_file, bg="#444444", fg="#FFFFFF")
        self.add_file_button.grid(row=0, column=0, padx=5, pady=5)
    
        for idx, pdf_info in enumerate(self.pdf_files):
            file_row = tk.Frame(self.file_frame, bg="#2E2E2E")
            file_row.grid(row=idx + 1, column=0, columnspan=6, sticky="w", padx=5, pady=5)
    
            path_label = tk.Label(file_row, text=pdf_info['path'], bg="#2E2E2E", fg="#FFFFFF")
            path_label.grid(row=0, column=0, padx=5, pady=5)
            size_label = tk.Label(file_row, text=f"{pdf_info['width']:.2f} x {pdf_info['height']:.2f} mm", bg="#2E2E2E", fg="#FFFFFF")
            size_label.grid(row=0, column=1, padx=5, pady=5)
            count_entry = tk.Entry(file_row, textvariable=pdf_info["count"], bg="#444444", fg="#FFFFFF")
            count_entry.grid(row=0, column=2, padx=5, pady=5)
    
            # Checkbox cho cropmarks
            cropmarks_check = tk.Checkbutton(file_row, text="Cropmarks", variable=pdf_info["cropmarks"], bg="#2E2E2E", fg="#FFFFFF", selectcolor="#444444")
            cropmarks_check.grid(row=0, column=3, padx=5, pady=5)
    
            # Ô nhập khoảng cách cho cropmarks
            cropmark_offset_entry = tk.Entry(file_row, textvariable=pdf_info["cropmark_offset"], width=5, bg="#444444", fg="#FFFFFF")
            cropmark_offset_entry.grid(row=0, column=4, padx=5, pady=5)
    
            remove_button = tk.Button(file_row, text="Xóa", command=lambda idx=idx: self.remove_pdf_file(idx), bg="#FF0000", fg="#FFFFFF")
            remove_button.grid(row=0, column=5, padx=5, pady=5)
    
            self.pdf_widgets.append(file_row)
    
        self.update_button_states()
    
    def remove_pdf_file(self, index):
        del self.pdf_files[index]
        self.update_file_widgets()
        self.update_button_states()
    
    def update_button_states(self):
        if len(self.pdf_files) == 0:
            self.calculate_button.config(state=tk.DISABLED)
        else:
            self.calculate_button.config(state=tk.NORMAL)
    
    def calculate_layout(self):
        if not self.pdf_files:
            messagebox.showwarning("Cảnh báo", "Không có tệp PDF nào để tính toán bố trí.")
            return
    
        try:
            paper_width_mm = self.paper_width.get() - 2 * self.margin
            paper_height_mm = self.paper_height.get() - 2 * self.margin
    
            sizes = [(pdf["width"], pdf["height"]) for pdf in self.pdf_files]
            counts = [pdf["count"].get() for pdf in self.pdf_files]
            cropmarks_flags = [pdf["cropmarks"].get() for pdf in self.pdf_files]
            cropmark_offsets = [pdf["cropmark_offset"].get() for pdf in self.pdf_files]
    
            if not counts:
                messagebox.showwarning("Cảnh báo", "Không có số lượng hợp lệ để tính toán.")
                return
    
            total_paper_area = paper_width_mm * paper_height_mm
            total_product_area = sum([w * h * count for (w, h), count in zip(sizes, counts)])
            required_areas = [w * h * count for (w, h), count in zip(sizes, counts)]
            area_ratios = [area / total_product_area for area in required_areas]
            allocated_areas = [int(total_paper_area * ratio) for ratio in area_ratios]
    
            combined_layout_result = self.combined_layout(int(paper_width_mm), int(paper_height_mm), sizes, counts, allocated_areas)
            total_sheets = self.calculate_sheets_needed(combined_layout_result, counts)
            total_printed = self.calculate_total_printed(combined_layout_result, total_sheets)
            excess_printed = self.calculate_excess_printed(total_printed, counts)
    
            self.result_text.delete(1.0, tk.END)
            self.result_text.insert(tk.END, f"Kết quả của combined_layout: {combined_layout_result}\n")
            self.result_text.insert(tk.END, f"Tổng số tờ giấy cần thiết: {total_sheets}\n")
            self.result_text.insert(tk.END, "Số lượng sản phẩm in ra được và số dư:\n")
            for i, (printed, excess) in enumerate(zip(total_printed, excess_printed)):
                self.result_text.insert(tk.END, f"Sản phẩm {i + 1}: {printed}, dư {excess}\n")
    
            self.save_pdf_dialog(int(paper_width_mm), int(paper_height_mm), sizes, counts, cropmarks_flags, cropmark_offsets, combined_layout_result)
        except Exception as e:
            messagebox.showerror("Lỗi tính toán", f"Có lỗi xảy ra trong quá trình tính toán bố trí: {e}")
    
    def combined_layout(self, paper_width, paper_height, sizes, counts, allocated_areas):
        layout = []
        for (w, h), allocated_area in zip(sizes, allocated_areas):
            num_per_sheet = self.fill_section(paper_width, paper_height, int(w), int(h), allocated_area)
            layout.append(num_per_sheet)
        return layout
    
    def fill_section(self, paper_width, paper_height, w, h, allocated_area):
        try:
            if w > paper_width or h > paper_height:
                return 0
    
            num_per_sheet_no_rotation = (paper_width // w) * (paper_height // h)
            num_per_sheet_rotation = (paper_width // h) * (paper_height // w)
    
            max_num_per_sheet = max(num_per_sheet_no_rotation, num_per_sheet_rotation)
            if max_num_per_sheet == 0:
                return 0
    
            return min(int(allocated_area // (w * h)), max_num_per_sheet)
        except Exception as e:
            messagebox.showerror("Lỗi khi điền phần", f"Có lỗi xảy ra trong quá trình điền phần: {e}")
            return 0
    
    def calculate_sheets_needed(self, layout, counts):
        try:
            sheets_needed = [math.ceil(count / per_sheet) if per_sheet > 0 else float('inf') for count, per_sheet in zip(counts, layout)]
            for idx, per_sheet in enumerate(layout):
                if per_sheet == 0:
                    print(f"Lỗi: Số lượng vật phẩm trên mỗi tờ giấy cho sản phẩm {idx + 1} là 0.")
            total_sheets = max(sheets_needed)
            return total_sheets
        except Exception as e:
            messagebox.showerror("Lỗi tính số lượng giấy cần", f"Có lỗi xảy ra trong quá trình tính số lượng giấy cần: {e}")
            return 0
    
    def calculate_total_printed(self, layout, total_sheets):
        try:
            total_printed = [int(layout[idx] * total_sheets) for idx in range(len(layout))]
            return total_printed
        except Exception as e:
            messagebox.showerror("Lỗi tính tổng số lượng in", f"Có lỗi xảy ra trong quá trình tính tổng số lượng in: {e}")
            return []
    
    def calculate_excess_printed(self, total_printed, counts):
        try:
            excess = [int(printed - count) for printed, count in zip(total_printed, counts)]
            return excess
        except Exception as e:
            messagebox.showerror("Lỗi tính số lượng dư", f"Có lỗi xảy ra trong quá trình tính số lượng dư: {e}")
            return []
    
    def save_pdf_dialog(self, paper_width, paper_height, sizes, counts, cropmarks_flags, cropmark_offsets, layout):
        output_file_path = filedialog.asksaveasfilename(defaultextension=".pdf", filetypes=[("Tệp PDF", "*.pdf")])
        if output_file_path:
            self.create_output_pdf(output_file_path, paper_width, paper_height, sizes, counts, cropmarks_flags, cropmark_offsets, layout)
    
    def create_output_pdf(self, output_file_path, paper_width_mm, paper_height_mm, sizes, counts, cropmarks_flags, cropmark_offsets, layout):
        try:
            output_pdf = fitz.open()
            page = output_pdf.new_page(width=int(paper_width_mm * 72 / 25.4), height=int(paper_height_mm * 72 / 25.4))  # Đảm bảo kích thước đúng bằng mm
            objects = []
            for i, (w, h) in enumerate(sizes):
                num = layout[i]
                for _ in range(num):
                    objects.append({'width': w, 'height': h, 'path': self.pdf_files[i]['path'], 'cropmarks': cropmarks_flags[i], 'cropmark_offset': cropmark_offsets[i]})
    
            packed_objects = self.pack_objects(objects, int(paper_width_mm), int(paper_height_mm))
    
            max_x = max([x + obj['width'] if rotation == 0 else x + obj['height'] for x, y, obj, rotation in packed_objects])
            max_y = max([y + obj['height'] if rotation == 0 else y + obj['width'] for x, y, obj, rotation in packed_objects])
            x_offset = (paper_width_mm - max_x) / 2
            y_offset = (paper_height_mm - max_y) / 2
    
            for x, y, obj, rotation in packed_objects:
                x += x_offset
                y += y_offset
                w, h = (obj['width'], obj['height']) if rotation == 0 else (obj['height'], obj['width'])
                
                # Chuyển đổi sang fitz.Rect
                rect = fitz.Rect(int(x * 72 / 25.4), int(y * 72 / 25.4), int((x + w) * 72 / 25.4), int((y + h) * 72 / 25.4))
                
                try:
                    if not os.path.exists(obj['path']):
                        raise FileNotFoundError(f"Không tìm thấy tệp: {obj['path']}")
                    src_pdf = fitz.open(obj['path'])
    
                    # Đảm bảo clip_rect là fitz.Rect và không phải int
                    clip_rect = fitz.Rect(0, 0, obj['width'] * 72 / 25.4, obj['height'] * 72 / 25.4)
                    page.show_pdf_page(rect, src_pdf, 0, clip=clip_rect, rotate=rotation)
                    
                    # Thêm crop marks nếu cần
                    if obj["cropmarks"]:
                        self.add_crop_marks(page, rect, packed_objects, obj['cropmark_offset'], crop_length=5, crop_thickness=0.5)
    
                except Exception as e:
                    messagebox.showerror("Lỗi chèn trang PDF", f"Không thể chèn trang PDF '{obj['path']}']: {e}")
                    break
    
            output_pdf.save(output_file_path)
        except Exception as e:
            messagebox.showerror("Lỗi tạo PDF", f"Có lỗi xảy ra trong quá trình tạo PDF: {e}")
    
    def pack_objects(self, objects, paper_width, paper_height):
        try:
            algorithm_name = self.selected_algorithm.get()
            if algorithm_name == "MaxRectsBssf":
                algorithm = MaxRectsBssf
            elif algorithm_name == "MaxRectsBl":
                algorithm = MaxRectsBl
            elif algorithm_name == "MaxRectsBaf":
                algorithm = MaxRectsBaf
            elif algorithm_name == "GuillotineBssfLas":
                algorithm = GuillotineBssfLas
            elif algorithm_name == "SkylineBl":
                algorithm = SkylineBl
            else:
                algorithm = MaxRectsBssf  # Default to MaxRectsBssf if nothing is selected
    
            packer = newPacker(rotation=True, pack_algo=algorithm)
            packer.add_bin(paper_width, paper_height)
    
            for idx, obj in enumerate(objects):
                packer.add_rect(obj['width'], obj['height'], rid=idx)
    
            packer.pack()
    
            packed_objects = []
            for abin in packer:
                for rect in abin:
                    x, y, w, h, rid = rect.x, rect.y, rect.width, rect.height, rect.rid
                    obj = objects[rid]
                    rotation = 0 if (obj['width'], obj['height']) == (w, h) else 90
                    packed_objects.append((x, y, obj, rotation))
    
            return packed_objects
        except Exception as e:
            messagebox.showerror("Lỗi đóng gói đối tượng", f"Có lỗi xảy ra trong quá trình đóng gói đối tượng: {e}")
            return []
    
    def add_crop_marks(self, page, rect, objects, offset, crop_length, crop_thickness):
        try:
            # Đảm bảo rằng 'rect' là đối tượng fitz.Rect
            if not isinstance(rect, fitz.Rect):
                raise ValueError("Đối tượng 'rect' không hợp lệ")
    
            # Chuyển đổi các giá trị cropmark từ mm sang points
            crop_length = crop_length * 2.83465  # Convert mm to points
            crop_thickness = crop_thickness * 2.83465  # Convert mm to points
    
            # Tọa độ của các cạnh của 'rect'
            x0, y0 = rect.x0, rect.y0
            x1, y1 = rect.x1, rect.y1
    
            # Tạo danh sách các crop marks
            crop_marks = [
                # Top-left
                [(x0 - crop_length, y0 - offset), (x0, y0 - offset)],
                [(x0 - offset, y0 - crop_length), (x0 - offset, y0)],
    
                # Top-right
                [(x1 + offset, y0 - crop_length), (x1 + offset, y0)],
                [(x1, y0 - offset), (x1 + crop_length, y0 - offset)],
    
                # Bottom-left
                [(x0 - crop_length, y1 + offset), (x0, y1 + offset)],
                [(x0 - offset, y1), (x0 - offset, y1 + crop_length)],
    
                # Bottom-right
                [(x1 + offset, y1 + crop_length), (x1 + offset, y1)],
                [(x1, y1 + offset), (x1 + crop_length, y1 + offset)]
            ]
    
            # Vẽ các crop marks lên trang PDF
            for start, end in crop_marks:
                # Kiểm tra các giá trị bắt đầu và kết thúc của đường kẻ là hợp lệ
                if isinstance(start, tuple) and isinstance(end, tuple):
                    page.draw_line(start, end, width=crop_thickness, color=(0, 0, 0))  # Màu đăng ký thường là màu đen
                else:
                    raise ValueError(f"Giá trị bắt đầu ({start}) hoặc kết thúc ({end}) không hợp lệ")
    
        except Exception as e:
            messagebox.showerror("Lỗi tạo crop marks", f"Không thể tạo crop marks: {e}")
    

    if name == "main": root = TkinterDnD.Tk() app = PDFLayoutApp(root) root.mainloop() phân tích mã

  2. Assistant

    The provided Python script is a graphical application that assists users in arranging PDF files onto a larger sheet of paper for printing purposes. This tool is particularly useful for print layout planning, especially in contexts like printing multiple small PDFs onto larger sheets to optimize paper usage.

    Let's break down the code to understand its functionality and components step by step.

    Overview of the Application

    The application utilizes several libraries:

    • tkinter: For creating the graphical user interface (GUI).
    • tkinterdnd2: To enable drag-and-drop functionality within the tkinter interface.
    • PyMuPDF (fitz): For handling PDF files, reading their dimensions, and manipulating pages.
    • rectpack: For packing rectangles (PDF pages) efficiently onto a larger rectangle (the paper size) using various algorithms.

    Key Components of the Code

    Importing Libraries

    import tkinter as tk
    from tkinter import filedialog, messagebox
    from tkinterdnd2 import DND_FILES, TkinterDnD
    import fitz  # PyMuPDF
    import math
    import os
    from rectpack import newPacker, MaxRectsBssf, MaxRectsBl, MaxRectsBaf, GuillotineBssfLas, SkylineBl
    
    • tkinter: Standard Python GUI library.
    • tkinterdnd2: Adds drag-and-drop support to tkinter.
    • fitz (PyMuPDF): For PDF manipulation.
    • rectpack: For rectangle packing algorithms.

    The PDFLayoutApp Class

    This is the main class that builds and manages the application.

    Initialization

    def __init__(self, root):
        self.root = root
        self.root.title("Máy tính bố trí PDF")
        self.root.configure(bg="#2E2E2E")
    
        self.pdf_files = []
        self.pdf_widgets = []
        self.paper_width = tk.DoubleVar(value=650)
        self.paper_height = tk.DoubleVar(value=430)
        self.margin = 0
    
        self.selected_algorithm = tk.StringVar(value="MaxRectsBssf")
    
        self.create_widgets()
        self.root.drop_target_register(DND_FILES)
        self.root.dnd_bind('<<Drop>>', self.drop)
    
    • Initializes the main window and variables:
      • self.pdf_files: List to store PDF file information.
      • self.paper_width and self.paper_height: Variables to store the paper size.
      • self.selected_algorithm: The rectangle packing algorithm selected by the user.
    • Calls self.create_widgets() to set up the GUI components.
    • Registers the drag-and-drop event handlers.

    Creating the GUI Components

    The application's GUI comprises several sections:

    • File Frame: Allows users to add PDF files.
    • Paper Size Frame: Users can specify the paper dimensions and select the packing algorithm.
    • Calculate Button: Initiates the layout calculation.
    • Result Text: Displays the calculation results.
    def create_widgets(self):
        # ... Code to create and pack widgets ...
    
    • Uses tk.Frame, tk.Label, tk.Entry, tk.OptionMenu, and tk.Button to build the interface.
    • The interface is designed with a dark theme, using custom background (bg) and foreground (fg) colors.

    Adding PDF Files

    Users can add PDF files either by clicking a button or by dragging and dropping them onto the application.

    def add_pdf_file(self):
        file_paths = filedialog.askopenfilenames(filetypes=[("Tệp PDF", "*.pdf")])
        self.process_files(file_paths)
    
    def drop(self, event):
        file_paths = self.root.tk.splitlist(event.data)
        self.process_files(file_paths)
    
    • add_pdf_file: Opens a file dialog for selecting PDF files.
    • drop: Handles files dropped onto the application window.
    • Both methods call process_files to handle the selected files.

    Processing Added Files

    def process_files(self, file_paths):
        for file_path in file_paths:
            if file_path.endswith('.pdf'):
                # Open PDF and retrieve first page dimensions
                # Store file information in self.pdf_files
                # Update the GUI to reflect the new files
    
    • Opens each PDF file using fitz.open(file_path) and reads the dimensions of the first page.
    • Converts the dimensions from points to millimeters (size.width * 25.4 / 72).
    • Creates a dictionary pdf_info to store:
      • File path.
      • Width and height.
      • Quantity to place on the sheet (count).
      • Whether to include crop marks (cropmarks).
      • Crop mark offset (cropmark_offset).
    • Updates the GUI to display the added files.

    Updating the File Widgets

    def update_file_widgets(self):
        # Clears existing widgets and recreates them based on self.pdf_files
    
    • Rebuilds the file list section of the GUI to include entries for each added PDF file.
    • Each file entry includes:
      • File path and dimensions.
      • Entry for specifying the quantity to print.
      • Checkbox for crop marks.
      • Entry for crop mark offset.
      • Button to remove the file from the list.

    Calculating the Layout

    def calculate_layout(self):
        # Validates inputs and prepares data
        # Calculates the layout using selected algorithm
        # Displays results and prompts to save the output PDF
    
    • Retrieves paper dimensions and margins.
    • Collects sizes, counts, crop mark options, and offsets.
    • Validates that quantities are provided.
    • Computes:
      • Total area of the paper and products.
      • Area required for each product based on quantity.
      • Allocates areas proportionally.
    • Calls combined_layout to compute how many of each product can fit on a sheet.
    • Calculates the number of sheets needed and any excess prints.
    • Displays the results in the result_text widget.
    • Prompts the user to save the output PDF.

    Combining Layout

    def combined_layout(self, paper_width, paper_height, sizes, counts, allocated_areas):
        layout = []
        for (w, h), allocated_area in zip(sizes, allocated_areas):
            num_per_sheet = self.fill_section(paper_width, paper_height, int(w), int(h), allocated_area)
            layout.append(num_per_sheet)
        return layout
    
    • Iterates over each product and determines how many can fit on the sheet, considering the allocated area.
    • Uses fill_section to calculate the maximum number of times the product can be placed without rotation or with a 90-degree rotation.

    Filling Sections

    def fill_section(self, paper_width, paper_height, w, h, allocated_area):
        # Calculates how many products can fit on the sheet without and with rotation
        # Returns the maximum number fitting within the allocated area
    
    • Computes the number of products that fit horizontally and vertically.
    • Considers both orientations (landscape and portrait).
    • Ensures that the product dimensions are less than the paper dimensions.

    Calculating Sheets Needed

    def calculate_sheets_needed(self, layout, counts):
        sheets_needed = [math.ceil(count / per_sheet) if per_sheet > 0 else float('inf') for count, per_sheet in zip(counts, layout)]
        total_sheets = max(sheets_needed)
        return total_sheets
    
    • Determines how many sheets are needed to fulfill the required counts for all products.
    • Uses the maximum number among individual products to ensure that all quantities are met.

    Creating the Output PDF

    def create_output_pdf(self, output_file_path, paper_width_mm, paper_height_mm, sizes, counts, cropmarks_flags, cropmark_offsets, layout):
        # Creates a new PDF and adds pages with the arranged PDFs
        # Adds crop marks if requested
        # Saves the final PDF to the specified path
    
    • Initializes a new PDF document.
    • Calculates offsets to center the layout on the paper.
    • For each packed object, it:
      • Places the PDF onto the page at the specified position.
      • Applies rotation if needed.
      • Adds crop marks if requested by the user.
    • Uses self.pack_objects to determine the positions of the PDFs on the sheet using the selected packing algorithm.

    Packing Objects

    def pack_objects(self, objects, paper_width, paper_height):
        algorithm_name = self.selected_algorithm.get()
        # Selects the algorithm based on user input
        packer = newPacker(rotation=True, pack_algo=algorithm)
        packer.add_bin(paper_width, paper_height)
        # Adds rectangles representing the PDFs to pack
        packer.pack()
        # Collects and returns the positions and rotations of the packed objects
    
    • Uses the rectpack library to pack rectangles efficiently.
    • Supports several algorithms:
      • MaxRectsBssf
      • MaxRectsBl
      • MaxRectsBaf
      • GuillotineBssfLas
      • SkylineBl
    • Allows rotation to optimize space usage.

    Adding Crop Marks

    def add_crop_marks(self, page, rect, packed_objects, offset, crop_length, crop_thickness):
        # Draws crop marks around the placed PDF on the page
    
    • Converts parameters from millimeters to points (the unit used in PDF rendering).
    • Calculates the positions for the crop marks around each PDF.
    • Draws lines on the page to represent the crop marks.

    Running the Application

    if __name__ == "__main__":
        root = TkinterDnD.Tk()
        app = PDFLayoutApp(root)
        root.mainloop()
    
    • Initializes the main application window.
    • Creates an instance of PDFLayoutApp.
    • Starts the tkinter event loop.

    Analysis and Potential Improvements

    • Error Handling: The code includes several try-except blocks to catch exceptions and display error messages using messagebox.showerror. This is good practice to handle unexpected issues gracefully.

    • Measurement Units: There is consistent conversion between millimeters and points (1 point = 1/72 inch, 1 inch = 25.4 mm). However, ensure that all conversions are accurate and consistent throughout the code.

    • User Interface:

      • The GUI is built using the classic tkinter widgets. For a more modern look, consider using ttk themed widgets or additional libraries like tkinter with ttkbootstrap.
      • The application labels and messages are in Vietnamese (e.g., "Máy tính bố trí PDF", "Chọn tệp PDF"). Ensure that the intended audience is Vietnamese users or adapt the language accordingly.
    • Functionality:

      • Supports adding multiple PDFs and specifying quantities and crop marks individually.
      • Provides several packing algorithms to choose from, allowing users to experiment with different packing strategies.
    • Performance:

      • For large numbers of PDFs or very large page sizes, performance could be impacted. Consider optimizing the packing process or providing feedback during long operations.
    • User Experience:

      • Currently, the application requires users to input exact quantities and dimensions. Adding validation to ensure inputs are within reasonable ranges can improve usability.
      • Providing a visual preview of the layout before saving the PDF could enhance the application's usefulness.
    • Code Organization:

      • The code is structured within a class, which is good for encapsulation. However, consider splitting the code into smaller methods or even separate modules for better maintainability.
      • Comments and docstrings can be added to functions to explain their purpose and parameters.
    • Compatibility:

      • Ensure that all external libraries (tkinterdnd2, fitz, rectpack) are installed and compatible with the user's Python environment.
      • Consider packaging the application with a virtual environment or specifying the requirements in a requirements.txt file.

    Summary

    The provided Python script is a comprehensive tool for arranging multiple PDF files onto larger sheets for printing, optimizing the usage of paper, and fulfilling specific quantities of each product. It offers:

    • A GUI for user interaction, allowing file selection, quantity specification, and crop mark options.
    • Multiple packing algorithms for efficient layout calculation.
    • The ability to generate a final PDF with the arranged content and optional crop marks.

    The code demonstrates effective use of various libraries to achieve its functionality and includes error handling to manage exceptions. With some improvements in user experience and code organization, this tool can be highly beneficial for printing and layout tasks.

import tkinter as tk from tkinter import filedialog… · The Chat Archive