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, # Convert points to mm
"height": size.height * 25.4 / 72,
"count": tk.IntVar(value=0),
"cropmarks": tk.BooleanVar(value=False),
"cropmark_offset": tk.DoubleVar(value=5.0)
}
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 for 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)
# Entry for cropmark offset
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
# Combine data into products list
products = []
for pdf in self.pdf_files:
size = (pdf["width"], pdf["height"])
count = pdf["count"].get()
cropmarks_flag = pdf["cropmarks"].get()
cropmark_offset = pdf["cropmark_offset"].get()
products.append({
"size": size,
"count": count,
"cropmarks_flag": cropmarks_flag,
"cropmark_offset": cropmark_offset,
"path": pdf["path"],
"pdf_info": pdf
})
# Sort products by count descending
products.sort(key=lambda x: x["count"], reverse=True)
if not any(p["count"] > 0 for p in products):
messagebox.showwarning("Cảnh báo", "Số lượng sản phẩm phải lớn hơn 0.")
return
total_sheets, layout_per_sheet = self.optimize_layout(
int(paper_width_mm), int(paper_height_mm), products
)
if total_sheets == 0:
messagebox.showwarning("Cảnh báo", "Không thể thực hiện bố trí với kích thước hiện tại.")
return
total_printed = [
layout_per_sheet[i] * total_sheets for i in range(len(products))
]
counts = [p["count"] for p in products]
excess_printed = [
total_printed[i] - counts[i] for i in range(len(products))
]
self.result_text.delete(1.0, tk.END)
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, product) in enumerate(zip(total_printed, excess_printed, products)):
self.result_text.insert(
tk.END,
f"Sản phẩm {i + 1} ({os.path.basename(product['path'])}): {printed}, dư {excess}\n"
)
# Pass products to save_pdf_dialog
self.save_pdf_dialog(
int(paper_width_mm), int(paper_height_mm),
products, layout_per_sheet, total_sheets
)
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 optimize_layout(self, paper_width, paper_height, products):
try:
# Initialize packer
algorithm_name = self.selected_algorithm.get()
algorithm = {
"MaxRectsBssf": MaxRectsBssf,
"MaxRectsBl": MaxRectsBl,
"MaxRectsBaf": MaxRectsBaf,
"GuillotineBssfLas": GuillotineBssfLas,
"SkylineBl": SkylineBl
}.get(algorithm_name, MaxRectsBssf)
# Prepare rectangles for packing
rectangles = []
for idx, product in enumerate(products):
w, h = product["size"]
count = product["count"]
if count <= 0:
continue
# Add enough rectangles to meet the required count
for _ in range(count):
rectangles.append({
'width': w,
'height': h,
'rid': idx,
'path': product['path'],
'cropmarks': product['cropmarks_flag'],
'cropmark_offset': product['cropmark_offset']
})
if not rectangles:
return 0, []
# Create packer and add the bin (sheet)
packer = newPacker(rotation=True, pack_algo=algorithm)
packer_rects = []
for rect in rectangles:
packer.add_rect(rect['width'], rect['height'], rid=rect)
packer.add_bin(paper_width, paper_height)
packer.pack()
total_sheets = len(packer)
layout_per_sheet = [0] * len(products)
# Count how many of each product are packed per sheet
for b in packer:
packed_rects = b.rect_list()
for rect in packed_rects:
rect_data = rect.rid # rect.rid contains the rectangle data
idx = rect_data['rid']
layout_per_sheet[idx] += 1
return total_sheets, layout_per_sheet
except Exception as e:
messagebox.showerror(
"Lỗi tối ưu bố trí", f"Có lỗi xảy ra trong quá trình tối ưu bố trí: {e}"
)
return 0, []
def save_pdf_dialog(self, paper_width, paper_height, products, layout_per_sheet, total_sheets):
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,
products, layout_per_sheet, total_sheets
)
def create_output_pdf(self, output_file_path, paper_width_mm, paper_height_mm, products, layout_per_sheet, total_sheets):
try:
algorithm_name = self.selected_algorithm.get()
algorithm = {
"MaxRectsBssf": MaxRectsBssf,
"MaxRectsBl": MaxRectsBl,
"MaxRectsBaf": MaxRectsBaf,
"GuillotineBssfLas": GuillotineBssfLas,
"SkylineBl": SkylineBl
}.get(algorithm_name, MaxRectsBssf)
output_pdf = fitz.open()
for _ in range(total_sheets):
page = output_pdf.new_page(
width=int(paper_width_mm * 72 / 25.4),
height=int(paper_height_mm * 72 / 25.4)
)
# Prepare rectangles for this sheet
packer = newPacker(rotation=True, pack_algo=algorithm)
packer.add_bin(paper_width_mm, paper_height_mm)
rects_to_pack = []
for idx, num in enumerate(layout_per_sheet):
product = products[idx]
w, h = product['size']
# Add the number of rectangles per sheet for this product
for _ in range(num):
packer.add_rect(w, h, rid=product)
packer.pack()
# Place the rectangles on the page
for b in packer:
for rect in b:
x, y, w, h = rect.x, rect.y, rect.width, rect.height
product = rect.rid
rotation = 0 if (product['size'][0], product['size'][1]) == (w, h) else 90
x_pt = x * 72 / 25.4
y_pt = y * 72 / 25.4
w_pt = w * 72 / 25.4
h_pt = h * 72 / 25.4
rect_fitz = fitz.Rect(
x_pt, y_pt,
x_pt + w_pt, y_pt + h_pt
)
src_pdf = fitz.open(product['path'])
clip_rect = fitz.Rect(0, 0, w_pt, h_pt)
page.show_pdf_page(
rect_fitz, src_pdf, 0,
clip=clip_rect, rotate=rotation
)
# Add crop marks if needed
if product['cropmarks_flag']:
self.add_crop_marks(
page, rect_fitz,
product['cropmark_offset'], crop_length=5,
crop_thickness=0.5
)
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 add_crop_marks(self, page, rect, offset, crop_length, crop_thickness):
try:
# Convert units from mm to points
crop_length *= 72 / 25.4
crop_thickness *= 72 / 25.4
offset *= 72 / 25.4
x0, y0 = rect.x0, rect.y0
x1, y1 = rect.x1, rect.y1
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)],
]
for start, end in crop_marks:
page.draw_line(
start, end,
width=crop_thickness, color=(0, 0, 0)
)
except Exception as e:
messagebox.showerror(
"Lỗi tạo crop marks", f"Không thể tạo crop marks: {e}"
)