self.file_path = None
self.excel_path = None
self.pdf_image = None
self.coords = {}
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
self.pdf_doc = None
self.font_file_dict = {}
self.undo_stack = []
self.redo_stack = []
self.field_type = tk.StringVar(value="Text")
self.image_width_var = tk.DoubleVar(value=100.0)
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
self.excel_row_index = 0 # Start with the first data row
self.scaled_rows = set() # Keep track of rows where scaling occurs
self.cropmark_offset_var = tk.DoubleVar(value=3.0)
self.cropmark_length_var = tk.DoubleVar(value=5.0)
self.scale_option = tk.StringVar(value="Scale đều")
self.setup_ui()
def get_installed_fonts(self):
"""Get a list of installed TrueType fonts."""
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):
"""Get the full name of the font using 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):
"""Check if the font file is available and valid."""
try:
font = FontToolsTTFont(font_path)
font.close()
return True
except Exception:
return False
def setup_ui(self):
"""Set up the user interface components."""
# First row of buttons
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)
prev_data_button = tk.Button(button_frame, text="Dữ liệu trước", command=self.prev_data_row, bg='#7289da', fg='white')
prev_data_button.pack(side=tk.LEFT, padx=2)
next_data_button = tk.Button(button_frame, text="Dữ liệu tiếp", command=self.next_data_row, bg='#7289da', fg='white')
next_data_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)
# Get and sort the font list
self.font_files = sorted(self.get_installed_fonts())
# Create Entry for font input and selection
self.font_entry = tk.Entry(button_frame, textvariable=self.font_var)
self.font_entry.pack(side=tk.LEFT, padx=2)
self.font_entry.bind('<KeyRelease>', self.on_font_entry_keyrelease)
self.font_entry.bind('<Button-1>', self.show_font_listbox)
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)
# CMYK color input
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)
# Field type selection
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)
# Image size input
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)
# Second row of buttons (Alignment and Scale options)
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)
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)
# Add Combobox for scale option
scale_options = ["Scale đều", "Scale ngang", "Scale dọc", "Điều chỉnh kerning"]
self.scale_option_combobox = ttk.Combobox(button_frame2, textvariable=self.scale_option,
values=scale_options, state="readonly")
self.scale_option_combobox.pack(side=tk.LEFT, padx=2)
self.scale_option_combobox.current(0) # Default to "Scale đều"
# Mapping display value to internal value
self.scale_option_mapping = {
"Scale đều": "uniform",
"Scale ngang": "horizontal",
"Scale dọc": "vertical",
"Điều chỉnh kerning": "kerning"
}
# Bind event when scale option changes
self.scale_option_combobox.bind("<<ComboboxSelected>>", self.on_scale_option_changed)
# Third row (Imposition settings)
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)
# Crop mark settings
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)
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)
tk.Entry(imposition_frame, textvariable=self.cropmark_length_var, width=5).pack(side=tk.LEFT, padx=2)
# Fourth row: Field selection buttons
field_button_frame = tk.Frame(self.root, bg='#2c2f33')
field_button_frame.pack(pady=5, fill=tk.X)
# Add canvas with scrollbar to hold the buttons
field_canvas = tk.Canvas(field_button_frame, bg='#2c2f33', highlightthickness=0)
field_scrollbar = tk.Scrollbar(field_button_frame, orient=tk.HORIZONTAL, command=field_canvas.xview)
field_canvas.configure(xscrollcommand=field_scrollbar.set)
field_inner_frame = tk.Frame(field_canvas, bg='#2c2f33')
field_canvas.create_window((0, 0), window=field_inner_frame, anchor='nw')
field_canvas.pack(side=tk.TOP, fill=tk.X, expand=True)
field_scrollbar.pack(side=tk.BOTTOM, fill=tk.X)
def configure_field_canvas(event):
field_canvas.configure(scrollregion=field_canvas.bbox("all"))
field_inner_frame.bind("<Configure>", configure_field_canvas)
# Store reference for use in create_field_radiobuttons
self.field_inner_frame = field_inner_frame
# Adjust frame to display the canvas and Excel data
content_frame = tk.Frame(self.root, bg='#2c2f33')
content_frame.pack(pady=5, fill=tk.BOTH, expand=True)
# Main canvas frame
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)
# Add scrollbar to 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)
# Frame to display Excel data
self.preview_frame = tk.Frame(content_frame, bg='#2c2f33')
self.preview_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# Data Treeview to display Excel data
self.data_treeview = ttk.Treeview(self.preview_frame)
self.data_treeview.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) # For Linux
self.canvas.bind("<Button-5>", self.zoom_with_mouse_wheel)
def load_file(self):
"""Load the selected file and display the first page."""
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:
# Close current document if open
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 # Reset page index
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()
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 show_font_listbox(self, event):
"""Hiển thị Listbox với danh sách font và thanh cuộn."""
if hasattr(self, 'font_listbox_window') and self.font_listbox_window.winfo_exists():
return # Nếu cửa sổ Listbox đang hiển thị, không làm gì cả
# Tạo cửa sổ toplevel mới
self.font_listbox_window = tk.Toplevel(self.root)
self.font_listbox_window.wm_overrideredirect(True)
# Lấy vị trí của Entry để đặt cửa sổ Listbox
x = self.font_entry.winfo_rootx()
y = self.font_entry.winfo_rooty() + self.font_entry.winfo_height()
width = self.font_entry.winfo_width()
self.font_listbox_window.geometry(f"{width}x200+{x}+{y}")
# Tạo Listbox và thanh cuộn
self.font_scrollbar = tk.Scrollbar(self.font_listbox_window)
self.font_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.font_listbox = tk.Listbox(self.font_listbox_window, yscrollcommand=self.font_scrollbar.set, height=10)
self.font_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.font_scrollbar.config(command=self.font_listbox.yview)
# Điền danh sách font vào Listbox
self.update_font_listbox(self.font_files)
# Liên kết sự kiện chọn font
self.font_listbox.bind('<<ListboxSelect>>', self.on_font_listbox_select)
# Thay vì liên kết sự kiện nhấp chuột lên root, chúng ta liên kết FocusOut trên Listbox window
self.font_listbox_window.bind('<FocusOut>', self.hide_font_listbox)
def hide_font_listbox(self, event=None):
"""Ẩn Listbox và bỏ liên kết sự kiện."""
if hasattr(self, 'font_listbox_window') and self.font_listbox_window.winfo_exists():
self.font_listbox_window.destroy()
del self.font_listbox # Xóa thuộc tính font_listbox để tránh lỗi sau này
del self.font_scrollbar # Xóa thuộc tính font_scrollbar
# Không cần bỏ liên kết sự kiện trên root nữa vì chúng ta không liên kết nó
def on_font_listbox_select(self, event):
"""Xử lý khi người dùng chọn font từ Listbox."""
selection = self.font_listbox.curselection()
if selection:
index = selection[0]
font_name = self.font_listbox.get(index)
self.font_var.set(font_name)
self.update_canvas_font()
# Đóng cửa sổ Listbox
self.hide_font_listbox()
def on_font_entry_keyrelease(self, event):
"""Cập nhật Listbox dựa trên đầu vào của người dùng."""
value = self.font_var.get()
value = value.strip().lower()
if value == '':
data = self.font_files
else:
data = []
for item in self.font_files:
if value in item.lower():
data.append(item)
# Cập nhật Listbox
if hasattr(self, 'font_listbox') and self.font_listbox.winfo_exists():
self.update_font_listbox(data)
else:
self.show_font_listbox(event)
def update_font_listbox(self, font_list):
"""Cập nhật nội dung của Listbox."""
if not (hasattr(self, 'font_listbox') and self.font_listbox.winfo_exists()):
return # Nếu Listbox không tồn tại, không làm gì cả
self.font_listbox.delete(0, tk.END)
for font in font_list:
self.font_listbox.insert(tk.END, font)
def on_scale_option_changed(self, event):
"""Xử lý khi người dùng thay đổi tùy chọn scale."""
# Cập nhật xem trước nếu cần
self.update_preview()
def on_font_entry_keyrelease(self, event):
"""Cập nhật Listbox dựa trên đầu vào của người dùng."""
value = self.font_var.get()
value = value.strip().lower()
if value == '':
data = self.font_files
else:
data = []
for item in self.font_files:
if value in item.lower():
data.append(item)
# Cập nhật Listbox
if hasattr(self, 'font_listbox') and self.font_listbox.winfo_exists():
self.update_font_listbox(data)
else:
self.show_font_listbox(event)
def update_font_listbox(self, font_list):
"""Cập nhật nội dung của Listbox."""
if not (hasattr(self, 'font_listbox') and self.font_listbox.winfo_exists()):
return # Nếu Listbox không tồn tại, không làm gì cả
self.font_listbox.delete(0, tk.END)
for font in font_list:
self.font_listbox.insert(tk.END, font)
def on_font_listbox_select(self, event):
"""Handle the font selection from the listbox."""
selection = self.font_listbox.curselection()
if selection:
index = selection[0]
font_name = self.font_listbox.get(index)
self.font_var.set(font_name)
self.font_listbox.destroy()
# Update the font settings on the canvas if needed
self.update_canvas_font()
def display_pdf_page(self):
"""Display the current page of the 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
# Adjust matrix for 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)
# Update canvas size
self.canvas.config(width=pix.width, height=pix.height)
self.canvas.config(scrollregion=self.canvas.bbox(tk.ALL))
# Render text and images on the page
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):
"""Go to the previous page of the PDF."""
if self.pdf_doc:
if self.current_page_index > 0:
self.current_page_index -= 1
self.display_pdf_page()
def next_page(self):
"""Go to the next page of the PDF."""
if 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):
"""Render text and images on the current PDF page according to the current data row."""
# Reset current selection
self.current_selected_text = None
# Clear previous text items from the canvas (except the PDF background)
self.canvas.delete("text_item")
self.canvas.delete("rect_item")
self.canvas.delete("anchor_item")
page_items = self.coords.get(self.current_page_index, [])
current_row = self.get_current_data_row() # Get the current data row
scaling_occurred = False # Flag to check if any text scaling happened
for item in page_items:
# Compute display coordinates considering zoom level
x = item["x"] * self.zoom_level
y = item["y"] * self.zoom_level
field_name = item["field"]
# Get the value from the current data row
if current_row is not None and field_name in current_row:
value = str(current_row[field_name])
else:
value = f"<{field_name}>"
if item.get('type', 'Text') == 'Text':
font_name = item["font"]
size = item["size"]
bounding_width = item["width"] * self.zoom_level
bounding_height = item["height"] * self.zoom_level
# Create text item on canvas
text_id = self.canvas.create_text(
x, y, text=value, anchor="center", fill="red", tags="text_item"
)
text_font = (font_name, int(size * self.zoom_level))
self.canvas.itemconfig(text_id, font=text_font)
# Get actual size of the text
bbox = self.canvas.bbox(text_id)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
# Calculate scaling factors
scale_x = scale_y = 1.0
if text_width > bounding_width:
scale_x = bounding_width / text_width
if text_height > bounding_height:
scale_y = bounding_height / text_height
# Retrieve scale option chosen by user
scale_option_display = self.scale_option.get()
scale_option = self.scale_option_mapping.get(scale_option_display, "uniform")
scaled = False # Flag to check if this text item is scaled
if scale_option == "uniform":
# Uniform scaling
scale = min(scale_x, scale_y)
if scale < 1.0:
scaled = True
new_size = size * scale
text_font = (font_name, int(new_size * self.zoom_level))
self.canvas.itemconfig(text_id, font=text_font)
elif scale_option == "horizontal":
# Horizontal scaling - not directly possible in Tkinter canvas
pass # You may implement custom logic if needed
elif scale_option == "vertical":
# Vertical scaling - not directly possible in Tkinter canvas
pass # You may implement custom logic if needed
elif scale_option == "kerning":
# Adjust spacing between characters - complex in Tkinter canvas
pass # You may implement custom logic if needed
else:
# Default to uniform scaling
scale = min(scale_x, scale_y)
if scale < 1.0:
scaled = True
new_size = size * scale
text_font = (font_name, int(new_size * self.zoom_level))
self.canvas.itemconfig(text_id, font=text_font)
# Update text color based on CMYK values
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 # Update ID in coords
# Draw bounding box
rect_id = self.canvas.create_rectangle(
x - (item["width"] / 2) * self.zoom_level,
y - (item["height"] / 2) * self.zoom_level,
x + (item["width"] / 2) * self.zoom_level,
y + (item["height"] / 2) * self.zoom_level,
outline='green', dash=(2, 2), tags="rect_item"
)
item["rect_id"] = rect_id
# Create anchor points for bounding box
anchors = self.create_anchor_points(rect_id)
item["anchors"] = anchors
# Ensure the correct display order on the canvas
self.canvas.tag_raise(text_id, rect_id)
for anchor in anchors:
self.canvas.tag_raise(anchor, rect_id)
# If scaling occurred for this text item, set scaling_occurred to True
if scaled:
scaling_occurred = True
elif item.get('type') == 'Image':
# Handle image fields
# Assuming you have similar logic for images
# Compute image dimensions
width_points = item.get("width_points", self.mm_to_points(self.image_width_var.get()))
height_points = item.get("height_points", self.mm_to_points(self.image_height_var.get()))
width = width_points * self.zoom_level
height = 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), tags="rect_item"
)
label_id = self.canvas.create_text(
x, y, text=value, anchor="center", fill="blue", tags="text_item"
)
item["id"] = rect_id
item["label_id"] = label_id
# Create anchor points
anchors = self.create_anchor_points(rect_id)
item["anchors"] = anchors
# Ensure correct display order
self.canvas.tag_raise(label_id, rect_id)
for anchor in anchors:
self.canvas.tag_raise(anchor, rect_id)
# After rendering all items, if scaling occurred, mark the data row
if scaling_occurred:
self.scaled_rows.add(self.excel_row_index)
# Update the Treeview to mark the row red
self.data_treeview.tag_configure('scaled', background='red')
self.data_treeview.item(str(self.excel_row_index), tags=('scaled',))
else:
if self.excel_row_index in self.scaled_rows:
self.scaled_rows.remove(self.excel_row_index)
# Remove the 'scaled' tag to reset the row color
self.data_treeview.item(str(self.excel_row_index), tags=())
def get_current_data_row(self):
"""Return the current data row as a dictionary."""
if self.df is not None and 0 <= self.excel_row_index < len(self.df):
return self.df.iloc[self.excel_row_index].to_dict()
else:
return None
def canvas_click(self, event):
"""Handle when the user clicks on the 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" or "anchor" in self.canvas.gettags(clicked_item):
if event.state & 0x0001 or event.state & 0x0004: # Shift or Control pressed
if clicked_item in self.selected_items:
self.selected_items.remove(clicked_item)
# Deselect the item
self.deselect_item(clicked_item)
else:
self.selected_items.add(clicked_item)
# Select the item
self.select_item(clicked_item)
else:
# Deselect previous selections
for item in self.selected_items:
self.deselect_item(item)
self.selected_items = set([clicked_item])
self.select_item(clicked_item)
# Initialize move coordinates
self.last_move_x = event.x
self.last_move_y = event.y
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):
"""Highlight the selected item."""
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):
"""Deselect the item."""
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):
"""Get the field properties based on the 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):
"""Add a new text or image field to the canvas and coords."""
field = self.selected_field.get()
field_type = self.field_type.get()
# Adjust for zoom level
x /= self.zoom_level
y /= self.zoom_level
current_row = self.get_current_data_row()
if current_row is not None and field in current_row:
display_value = str(current_row[field])
else:
display_value = f"<{field}>"
if field_type == "Text":
# Initial size for bounding box in points
bounding_box_width = 100 # Default width
bounding_box_height = 30 # Default height
# Compute positions for text and bounding box
display_x = x * self.zoom_level
display_y = y * self.zoom_level
# Create text object
text_id = self.canvas.create_text(
display_x, display_y,
text=display_value,
anchor="center",
fill="red",
tags="text_item"
)
# Create a rectangle representing the bounding box
rect_id = self.canvas.create_rectangle(
display_x - (bounding_box_width / 2) * self.zoom_level,
display_y - (bounding_box_height / 2) * self.zoom_level,
display_x + (bounding_box_width / 2) * self.zoom_level,
display_y + (bounding_box_height / 2) * self.zoom_level,
outline='green', dash=(2, 2), tags="rect_item"
)
# Create anchor points at the corners
anchors = self.create_anchor_points(rect_id)
# Ensure text is displayed above the rectangle and anchors
self.canvas.tag_raise(text_id, rect_id)
for anchor in anchors:
self.canvas.tag_raise(anchor, rect_id)
# Initialize item data
new_item = {
"id": text_id,
"rect_id": rect_id, # Reference to the bounding box
"anchors": anchors, # Reference to the anchor points
"field": field,
"x": x,
"y": y,
"width": bounding_box_width, # Width of the bounding box
"height": bounding_box_height, # Height of the bounding box
"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(),
},
# Additional properties for scaling
"is_resizing": False, # Flag to indicate if the item is being resized
"resize_anchor": None, # Which anchor point is used for resizing
}
# Add the new item to the coords data structure
if self.current_page_index not in self.coords:
self.coords[self.current_page_index] = []
self.coords[self.current_page_index].append(new_item)
# Update selected items
self.selected_items = set([text_id, rect_id] + anchors)
# Update font and other properties
self.update_canvas_font()
# Add to undo stack
self.undo_stack.append(('add', new_item))
self.redo_stack.clear() # Clear redo stack
self.update_preview()
elif field_type == "Image":
# Convert size from mm to points
width_points = self.mm_to_points(self.image_width_var.get())
height_points = self.mm_to_points(self.image_height_var.get())
display_x = x * self.zoom_level
display_y = y * self.zoom_level
# Create rectangle representing the image area
rect_id = self.canvas.create_rectangle(
display_x - (width_points / 2) * self.zoom_level,
display_y - (height_points / 2) * self.zoom_level,
display_x + (width_points / 2) * self.zoom_level,
display_y + (height_points / 2) * self.zoom_level,
outline='blue', dash=(2, 2), tags="rect_item"
)
label_id = self.canvas.create_text(display_x, display_y, text=f"<{field}>", anchor="center", fill="blue", tags="text_item")
anchors = self.create_anchor_points(rect_id)
# Ensure correct display order
self.canvas.tag_raise(label_id, rect_id)
for anchor in anchors:
self.canvas.tag_raise(anchor, rect_id)
new_item = {
"id": rect_id,
"label_id": label_id,
"rect_id": rect_id,
"anchors": anchors,
"field": field,
"x": x,
"y": y,
"width_points": width_points,
"height_points": height_points,
"type": "Image",
"is_resizing": False,
"resize_anchor": None,
}
if self.current_page_index not in self.coords:
self.coords[self.current_page_index] = []
self.coords[self.current_page_index].append(new_item)
# Update selected items
self.selected_items = set([rect_id, label_id] + anchors)
# Add to undo stack
self.undo_stack.append(('add', new_item))
self.redo_stack.clear()
self.update_preview()
def create_anchor_points(self, rect_id):
"""Create small anchor points at the corners of the bounding box."""
# Get current coordinates of the rectangle
coords = self.canvas.coords(rect_id)
x0, y0, x1, y1 = coords
# Define the size of the anchor point
anchor_size = 6 # Size of the anchor point
# Positions for four corners
positions = [
(x0, y0), # Top-left
(x1, y0), # Top-right
(x1, y1), # Bottom-right
(x0, y1), # Bottom-left
]
anchors = []
for (x, y) in positions:
anchor = self.canvas.create_oval(
x - anchor_size / 2, y - anchor_size / 2,
x + anchor_size / 2, y + anchor_size / 2,
fill='blue', outline='black', tags='anchor_item'
)
# Bind mouse events to the anchor point
self.canvas.tag_bind(anchor, '<ButtonPress-1>', self.on_anchor_press)
self.canvas.tag_bind(anchor, '<B1-Motion>', self.on_anchor_drag)
self.canvas.tag_bind(anchor, '<ButtonRelease-1>', self.on_anchor_release)
anchors.append(anchor)
return anchors
def on_anchor_press(self, event):
"""Handle mouse press on an anchor point."""
# Identify which anchor is being pressed
anchor_id = self.canvas.find_withtag(tk.CURRENT)[0]
self.resizing_item = self.get_field_by_anchor_id(anchor_id)
if self.resizing_item:
self.resizing_item["is_resizing"] = True
self.resizing_item["resize_anchor"] = anchor_id
# Record the initial position
self.resizing_start = (event.x, event.y)
def on_anchor_drag(self, event):
"""Handle dragging of an anchor point."""
if not hasattr(self, 'resizing_item') or not self.resizing_item.get("is_resizing"):
return
dx = event.x - self.resizing_start[0]
dy = event.y - self.resizing_start[1]
anchor_id = self.resizing_item.get("resize_anchor")
if not anchor_id:
return
# Update starting position
self.resizing_start = (event.x, event.y)
# Get the rectangle related to this anchor point
rect_id = self.resizing_item["rect_id"]
coords = self.canvas.coords(rect_id)
x0, y0, x1, y1 = coords
# Determine which anchor is being dragged and update rectangle coordinates
if anchor_id == self.resizing_item["anchors"][0]: # Top-left
new_x0 = x0 + dx
new_y0 = y0 + dy
self.canvas.coords(rect_id, new_x0, new_y0, x1, y1)
elif anchor_id == self.resizing_item["anchors"][1]: # Top-right
new_x1 = x1 + dx
new_y0 = y0 + dy
self.canvas.coords(rect_id, x0, new_y0, new_x1, y1)
elif anchor_id == self.resizing_item["anchors"][2]: # Bottom-right
new_x1 = x1 + dx
new_y1 = y1 + dy
self.canvas.coords(rect_id, x0, y0, new_x1, new_y1)
elif anchor_id == self.resizing_item["anchors"][3]: # Bottom-left
new_x0 = x0 + dx
new_y1 = y1 + dy
self.canvas.coords(rect_id, new_x0, y0, x1, new_y1)
# Update the position of related text or image if needed
field_id = self.resizing_item["id"]
self.update_field_position_after_resize(field_id, rect_id)
# Move the corresponding anchor points
self.update_anchor_positions(self.resizing_item)
def on_anchor_release(self, event):
"""Handle mouse release on an anchor point."""
if hasattr(self, 'resizing_item') and self.resizing_item.get("is_resizing"):
self.resizing_item["is_resizing"] = False
self.resizing_item["resize_anchor"] = None
self.resizing_start = None
# Add resize action to undo stack if needed
self.undo_stack.append(('resize', self.resizing_item.copy()))
self.redo_stack.clear()
self.update_preview()
def get_field_by_anchor_id(self, anchor_id):
"""Get the field related to an anchor point ID."""
page_items = self.coords.get(self.current_page_index, [])
for item in page_items:
if anchor_id in item.get("anchors", []):
return item
return None
def update_field_position_after_resize(self, field_id, rect_id):
"""Update the size of the bounding box without changing the field's position."""
# Get new coordinates of the bounding box
coords = self.canvas.coords(rect_id)
x0, y0, x1, y1 = coords
new_width = (x1 - x0) / self.zoom_level
new_height = (y1 - y0) / self.zoom_level
# Update the size of the bounding box in the item
for item in self.coords[self.current_page_index]:
if item["id"] == field_id:
item["width"] = new_width
item["height"] = new_height
break
# No need to move the field, keep its position
def update_anchor_positions(self, item):
"""Reposition the anchor points based on the resized rectangle."""
rect_id = item["rect_id"]
anchors = item["anchors"]
coords = self.canvas.coords(rect_id)
x0, y0, x1, y1 = coords
# Define the size of the anchor point
anchor_size = 6
# New positions for the anchor points
positions = [
(x0, y0), # Top-left
(x1, y0), # Top-right
(x1, y1), # Bottom-right
(x0, y1), # Bottom-left
]
for anchor, (x, y) in zip(anchors, positions):
self.canvas.coords(
anchor,
x - anchor_size / 2, y - anchor_size / 2,
x + anchor_size / 2, y + anchor_size / 2
)
def move_text(self, event):
"""Handle moving text or image fields on the canvas."""
if self.selected_items:
dx = event.x - self.last_move_x
dy = event.y - self.last_move_y
for item_id in self.selected_items.copy():
field = self.get_field_by_text_id(item_id)
if field:
# Move bounding box
self.canvas.move(field["rect_id"], dx, dy)
# Move anchor points
for anchor in field.get("anchors", []):
self.canvas.move(anchor, dx, dy)
# Move text or image
self.canvas.move(field["id"], dx, dy)
# Update coordinates
field["x"] += dx / self.zoom_level
field["y"] += dy / self.zoom_level
if field.get('label_id'):
self.canvas.move(field['label_id'], dx, dy)
self.last_move_x = event.x
self.last_move_y = event.y
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):
"""Update the font properties of the selected text fields."""
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':
# Check font size
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):
"""Delete the selected text or image fields from the canvas."""
if self.selected_items:
for item_id in list(self.selected_items):
field = self.get_field_by_text_id(item_id)
if field:
# Delete related items
items_to_delete = [field["id"], field["rect_id"]] + field.get("anchors", [])
if field.get("label_id"):
items_to_delete.append(field["label_id"])
for del_id in items_to_delete:
self.canvas.delete(del_id)
self.coords[self.current_page_index].remove(field)
self.undo_stack.append(('delete', field))
self.redo_stack.clear() # Clear redo stack
self.selected_items.clear()
self.update_preview()
def undo(self, event=None):
"""Undo the last action."""
if self.undo_stack:
action = self.undo_stack.pop()
if action[0] == 'add':
# Delete the added item
item = action[1]
self.canvas.delete(item["id"])
if item.get("label_id"):
self.canvas.delete(item["label_id"])
for anchor in item.get("anchors", []):
self.canvas.delete(anchor)
self.canvas.delete(item.get("rect_id", ""))
self.coords[self.current_page_index].remove(item)
self.redo_stack.append(('add', item))
elif action[0] == 'move':
# Move back to the previous position
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:
if field.get("label_id"):
self.canvas.move(field["label_id"], -dx * self.zoom_level, -dy * self.zoom_level)
for anchor in field.get("anchors", []):
self.canvas.move(anchor, -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':
# Add back the deleted item
item = action[1]
if item.get('type', 'Text') == 'Text':
self.add_text(item["x"] * self.zoom_level, item["y"] * self.zoom_level)
elif item.get('type') == 'Image':
self.add_text(item["x"] * self.zoom_level, item["y"] * self.zoom_level)
self.coords[self.current_page_index].append(item)
self.redo_stack.append(('delete', item))
elif action[0] == 'resize':
# Revert the resize action
item = action[1]
rect_id = item["rect_id"]
old_width = item["width"]
old_height = item["height"]
x = item["x"] * self.zoom_level
y = item["y"] * self.zoom_level
self.canvas.coords(rect_id,
x - (old_width / 2) * self.zoom_level,
y - (old_height / 2) * self.zoom_level,
x + (old_width / 2) * self.zoom_level,
y + (old_height / 2) * self.zoom_level)
self.update_anchor_positions(item)
self.redo_stack.append(('resize', item))
self.update_preview()
def redo(self, event=None):
"""Redo the last undone action."""
if self.redo_stack:
action = self.redo_stack.pop()
if action[0] == 'add':
# Add back the item
item = action[1]
self.add_text(item["x"] * self.zoom_level, item["y"] * self.zoom_level)
self.coords[self.current_page_index].append(item)
self.undo_stack.append(('add', item))
elif action[0] == 'move':
# Move to the new position
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:
if field.get("label_id"):
self.canvas.move(field["label_id"], dx * self.zoom_level, dy * self.zoom_level)
for anchor in field.get("anchors", []):
self.canvas.move(anchor, 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':
# Delete the item
item = action[1]
self.canvas.delete(item["id"])
if item.get("label_id"):
self.canvas.delete(item["label_id"])
for anchor in item.get("anchors", []):
self.canvas.delete(anchor)
self.canvas.delete(item.get("rect_id", ""))
self.coords[self.current_page_index].remove(item)
self.undo_stack.append(('delete', item))
elif action[0] == 'resize':
# Redo the resize action
item = action[1]
rect_id = item["rect_id"]
new_width = item["width"]
new_height = item["height"]
x = item["x"] * self.zoom_level
y = item["y"] * self.zoom_level
self.canvas.coords(rect_id,
x - (new_width / 2) * self.zoom_level,
y - (new_height / 2) * self.zoom_level,
x + (new_width / 2) * self.zoom_level,
y + (new_height / 2) * self.zoom_level)
self.update_anchor_positions(item)
self.undo_stack.append(('resize', item))
self.update_preview()
def load_excel(self):
"""Load the Excel file and display data."""
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()
# Clear previous Treeview content
for item in self.data_treeview.get_children():
self.data_treeview.delete(item)
# Set up the Treeview columns
self.data_treeview['columns'] = self.fields
self.data_treeview['show'] = 'headings'
for field in self.fields:
self.data_treeview.heading(field, text=field)
self.data_treeview.column(field, width=100)
# Clear the scaled rows set
self.scaled_rows = set()
# Add data to Treeview
for index, row in self.df.iterrows():
self.data_treeview.insert('', tk.END, values=list(row), iid=str(index))
self.create_field_radiobuttons()
self.reset_preview()
# Bind click event to the Treeview
self.data_treeview.bind("<Double-1>", self.on_data_row_click)
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):
"""Create radio buttons for Excel data fields."""
# Clear existing buttons
for widget in self.field_inner_frame.winfo_children():
widget.destroy()
# Add new buttons
for field in self.fields:
rb = tk.Radiobutton(
self.field_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)
def on_data_row_click(self, event):
"""Handle when user clicks on a data row in the Treeview."""
selected_item = self.data_treeview.focus()
if selected_item:
row_index = int(selected_item)
self.excel_row_index = row_index
self.display_pdf_page() # Update the canvas to show the selected data
def cmyk_to_rgb(self, c, m, y, k):
"""Convert CMYK color values to 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):
"""Convert millimeters to points."""
return mm * 72 / 25.4
def points_to_mm(self, points):
"""Convert points to 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))
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"]
bounding_width = item["width"]
bounding_height = item["height"]
# 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))
value = str(row[field_name])
# Cài đặt màu
c.setFillColorCMYK(
color_cmyk["C"] / 100,
color_cmyk["M"] / 100,
color_cmyk["Y"] / 100,
color_cmyk["K"] / 100
)
# Tính kích thước nội dung
text_width = pdfmetrics.stringWidth(value, font_name, size)
text_height = size # Xấp xỉ chiều cao bằng kích thước font
# Tính toán scale
scale_x = scale_y = 1.0
if text_width > bounding_width:
scale_x = bounding_width / text_width
if text_height > bounding_height:
scale_y = bounding_height / text_height
scale_option_display = self.scale_option.get()
scale_option = self.scale_option_mapping.get(scale_option_display, "uniform")
if scale_option == "uniform":
scale = min(scale_x, scale_y)
new_size = size * scale
c.setFont(font_name, new_size)
text_width_scaled = pdfmetrics.stringWidth(value, font_name, new_size)
adjusted_y = self.original_height - y - new_size / 2
adjusted_x = x - text_width_scaled / 2
c.drawString(adjusted_x, adjusted_y, value)
elif scale_option == "horizontal":
scale = scale_x
new_size = size # Giữ nguyên kích thước font
c.setFont(font_name, new_size)
c.saveState()
c.translate(x, self.original_height - y)
c.scale(scale, 1)
adjusted_x = -text_width / 2
adjusted_y = -new_size / 2
c.drawString(adjusted_x, adjusted_y, value)
c.restoreState()
elif scale_option == "vertical":
scale = scale_y
new_size = size # Giữ nguyên kích thước font
c.setFont(font_name, new_size)
c.saveState()
c.translate(x, self.original_height - y)
c.scale(1, scale)
adjusted_x = -text_width / 2
adjusted_y = -new_size / 2
c.drawString(adjusted_x, adjusted_y, value)
c.restoreState()
elif scale_option == "kerning":
# Điều chỉnh khoảng cách giữa các ký tự
total_characters = len(value)
if total_characters > 1:
total_space_needed = text_width - bounding_width
if total_space_needed > 0:
extra_space_per_char = total_space_needed / (total_characters - 1)
c.setFont(font_name, size)
adjusted_x_positions = []
current_x = x - text_width / 2
for char in value:
adjusted_x_positions.append(current_x)
char_width = pdfmetrics.stringWidth(char, font_name, size)
current_x += char_width - extra_space_per_char
# Vẽ từng ký tự tại vị trí mới
adjusted_y = self.original_height - y - size / 2
for i, char in enumerate(value):
c.drawString(adjusted_x_positions[i], adjusted_y, char)
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}")
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):
"""Căn trái các mục đã chọn."""
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):
"""Căn phải các mục đã chọn."""
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):
"""Căn trên các mục đã chọn."""
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):
"""Căn dưới các mục đã chọn."""
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):
"""Căn giữa các mục đã chọn."""
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):
"""Phóng to canvas."""
self.zoom_level *= 1.1
self.display_pdf_page()
self.display_preview_page()
def zoom_out(self):
"""Thu nhỏ canvas."""
self.zoom_level /= 1.1
self.display_pdf_page()
self.display_preview_page()
def zoom_with_mouse_wheel(self, event):
"""Phóng to hoặc thu nhỏ bằng con lăn chuột."""
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 imposition."""
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
# Nếu self.preview_doc đã mở, đóng nó trước
if self.preview_doc is not None:
self.preview_doc.close()
self.preview_doc = None
# 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"
# Tạo một file PDF duy nhất chứa tất cả các trang với dữ liệu được điền
doc = fitz.open()
for index, row in self.df.iterrows():
# Tạo PDF tùy chỉnh với dữ liệu từ hàng hiện tại
temp_pdf_path = self.create_temp_pdf_with_data(row, selected_font_path)
# Mở PDF tùy chỉnh và thêm vào doc
temp_doc = fitz.open(temp_pdf_path)
doc.insert_pdf(temp_doc)
temp_doc.close()
# Xóa tệp PDF tùy chỉnh tạm thời
os.remove(temp_pdf_path)
# Lưu tài liệu PDF với dữ liệu
output_pdf_path = os.path.join(temp_dir, "output_with_data_preview.pdf")
doc.save(output_pdf_path)
doc.close()
# Á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")
self.apply_imposition(output_pdf_path, imposed_preview_pdf_path)
# Mở 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):
"""Áp dụng Imposition để sắp xếp nhiều dữ liệu trên một trang."""
# 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()
# Lấy độ dài crop marks
crop_length_mm = self.cropmark_length_var.get()
crop_length_pt = self.mm_to_points(crop_length_mm)
# Chuyển đổi đơ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)
# Tính diện tích khả dụng trên trang
available_width = new_page_width_pt - margin_left_pt - margin_right_pt
available_height = new_page_height_pt - margin_top_pt - margin_bottom_pt
# Đọc tệp PDF đầu vào
doc = fitz.open(input_pdf_path)
new_doc = fitz.open()
total_pages = len(doc)
# Lấy kích thước của dữ liệu
input_page = doc.load_page(0)
bbox = input_page.rect
entry_width = bbox.width
entry_height = bbox.height
# Tính số lượng mục có thể đặt trên trang
entries_per_row = int(available_width / entry_width)
entries_per_column = int(available_height / entry_height)
# Kiểm tra nếu ít nhất một mục phù hợp
if entries_per_row < 1 or entries_per_column < 1:
messagebox.showerror("Lỗi", "Kích thước trang hoặc lề quá nhỏ để đặt bất kỳ dữ liệu nào.")
return
# Tính tổng chiều rộng và chiều cao của lưới
total_grid_width = entries_per_row * entry_width
total_grid_height = entries_per_column * entry_height
# Tính offset để căn giữa lưới trên trang
x_offset = (available_width - total_grid_width) / 2 + margin_left_pt
y_offset = (available_height - total_grid_height) / 2 + margin_top_pt
# Tham số cho crop marks
crop_thickness = 0.5 # Độ dày mặc định của crop marks (in points)
# Đặt các mục trên các trang mới
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
# Tính số lượng mục sẽ đặt trên trang này
entries_remaining = total_pages - page_index
entries_on_this_page = min(entries_per_row * entries_per_column, entries_remaining)
rows_on_this_page = (entries_on_this_page + entries_per_row - 1) // entries_per_row
for row in range(rows_on_this_page):
x = x_offset # Reset vị trí X cho mỗi hàng
for col in range(entries_per_row):
if page_index >= total_pages:
break
# Định vị mục hiện tại
rect = fitz.Rect(x, y, x + entry_width, y + entry_height)
new_page.show_pdf_page(rect, doc, pno=page_index)
# Xác định các cạnh là cạnh ngoài
edges = []
if row == 0:
edges.append('top')
if row == rows_on_this_page - 1:
edges.append('bottom')
if col == 0:
edges.append('left')
if col == entries_per_row - 1:
edges.append('right')
# Thêm crop marks vào các cạnh ngoài
self.add_crop_marks(new_page, rect, edges, cropmark_offset_pt, crop_length_pt, crop_thickness)
# Chuyển đến mục tiếp theo theo chiều ngang
x += entry_width
page_index += 1
# Chuyển đến hàng tiếp theo theo chiều dọc
y += entry_height
# Lưu tệp PDF đã áp dụng imposition
new_doc.save(output_pdf_path)
new_doc.close()
doc.close()
def add_crop_marks(self, page, rect, edges, offset, crop_length, crop_thickness):
"""Thêm crop marks vào các cạnh chỉ định."""
x0, y0 = rect.x0, rect.y0
x1, y1 = rect.x1, rect.y1
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))
def create_temp_pdf_with_data(self, row, selected_font_path):
"""Tạo tệp PDF tạm thời với dữ liệu từ một hàng Excel."""
temp_dir = tempfile.gettempdir()
temp_pdf_path = os.path.join(temp_dir, f"temp_data_{uuid.uuid4()}.pdf")
# Tạo PDF tùy chỉnh
self.create_text_pdf(temp_pdf_path, row, selected_font_path)
return temp_pdf_path
def prev_data_row(self):
"""Go to the previous data row."""
if self.excel_row_index > 0:
self.excel_row_index -= 1
self.display_pdf_page()
def next_data_row(self):
"""Go to the next data row."""
if self.excel_row_index < len(self.df) - 1:
self.excel_row_index += 1
self.display_pdf_page()