import tkinter as tk from tkinter import filedialog, messagebox from tkinterdnd2 import…
- 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}") - Assistant