button_frame = tk.Frame(root, bg='#2e2e2e')
button_frame.grid(row=0, column=0, sticky='nsew', padx=10, pady=10)
for i in range(12):
button_frame.grid_columnconfigure(i, weight=1)
def log_message(message):
log_file_path = os.path.join(directory, "conversion_log.txt")
with open(log_file_path, "a", encoding="utf-8") as log_file:
log_file.write(message + "\n")
print(message) # In thông báo ra màn hình để dễ kiểm tra
def convert_doc_to_pdf(doc_path, pdf_path):
try:
docx2pdf_convert(doc_path, pdf_path)
log_message(f"Successfully converted DOC to PDF: {pdf_path}")
except Exception as e:
log_message(f"Failed to convert DOC to PDF: {doc_path}, Error: {str(e)}")
Assistant
def convert_excel_to_pdf(excel_path, pdf_path):
try:
excel = win32.Dispatch("Excel.Application")
sheets = excel.Workbooks.Open(excel_path)
sheets.ExportAsFixedFormat(0, pdf_path)
sheets.Close(False)
excel.Quit()
log_message(f"Successfully converted Excel to PDF: {pdf_path}")
except Exception as e:
log_message(f"Failed to convert Excel to PDF: {excel_path}, Error: {str(e)}")
def convert_ai_files(ai_files, output_directory):
app = None
try:
app = comtypes.client.CreateObject("Illustrator.Application")
app.UserInteractionLevel = -1 # Giảm thiểu các hộp thoại
for ai_path in ai_files:
try:
pdf_path = os.path.join(output_directory, os.path.basename(ai_path).replace(".ai", ".pdf"))
doc = app.Open(ai_path)
options = comtypes.client.CreateObject("Illustrator.PDFSaveOptions")
doc.SaveAs(pdf_path, options)
doc.Close(2) # Lưu thay đổi và đóng tài liệu
log_message(f"Successfully converted AI to PDF: {pdf_path}")
except Exception as e:
log_message(f"Failed to convert AI to PDF: {ai_path}, Error: {str(e)}")
except Exception as e:
log_message(f"Failed to initialize Illustrator application: {str(e)}")
finally:
if app:
app.Quit()
def convert_cdr_to_pdf(cdr_path, pdf_path):
try:
app = comtypes.client.CreateObject("CorelDRAW.Application")
doc = app.OpenDocument(cdr_path)
doc.PublishToPDF(pdf_path)
doc.Close()
app.Quit()
log_message(f"Successfully converted CDR to PDF: {pdf_path}")
except Exception as e:
log_message(f"Failed to convert CDR to PDF: {cdr_path}, Error: {str(e)}")
def convert_psd_to_pdf(psd_path, pdf_path):
try:
app = comtypes.client.CreateObject("Photoshop.Application")
doc = app.Open(psd_path)
options = comtypes.client.CreateObject("Photoshop.PDFSaveOptions")
doc.SaveAs(pdf_path, options)
doc.Close()
app.Quit()
log_message(f"Successfully converted PSD to PDF: {pdf_path}")
except Exception as e:
log_message(f"Failed to convert PSD to PDF: {psd_path}, Error: {str(e)}")
def convert_jpg_to_pdf(jpg_path, pdf_path):
try:
image = Image.open(jpg_path)
image.save(pdf_path, "PDF", resolution=100.0)
log_message(f"Successfully converted JPG to PDF: {pdf_path}")
except Exception as e:
log_message(f"Failed to convert JPG to PDF: {jpg_path}, Error: {str(e)}")
def convert_png_to_pdf(png_path, pdf_path):
try:
image = Image.open(png_path)
image.save(pdf_path, "PDF", resolution=100.0)
log_message(f"Successfully converted PNG to PDF: {pdf_path}")
except Exception as e:
log_message(f"Failed to convert PNG to PDF: {png_path}, Error: {str(e)}")
def convert_tiff_to_pdf(tiff_path, pdf_path):
try:
image = Image.open(tiff_path)
image.save(pdf_path, "PDF", resolution=100.0)
log_message(f"Successfully converted TIFF to PDF: {pdf_path}")
except Exception as e:
log_message(f"Failed to convert TIFF to PDF: {tiff_path}, Error: {str(e)}")
def convert_webp_to_pdf(webp_path, pdf_path):
try:
image = Image.open(webp_path)
image.save(pdf_path, "PDF", resolution=100.0)
log_message(f"Successfully converted WebP to PDF: {pdf_path}")
except Exception as e:
log_message(f"Failed to convert WebP to PDF: {webp_path}, Error: {str(e)}")
def convert_indd_to_pdf(indd_path, pdf_path):
try:
app = comtypes.client.CreateObject("InDesign.Application.CC.2020")
doc = app.Open(indd_path)
options = app.PDFExportPresets.Item("High Quality Print")
doc.Export(1242363897, pdf_path, False, options)
doc.Close()
app.Quit()
log_message(f"Successfully converted InDesign to PDF: {pdf_path}")
except Exception as e:
log_message(f"Failed to convert InDesign to PDF: {indd_path}, Error: {str(e)}")
def display_image():
global img, scale, x_shift, y_shift, img_buffer, scaled_img
canvas.delete("all")
new_width = int(img_buffer.width * scale)
new_height = int(img_buffer.height * scale)
scaled_img = img_buffer.resize((new_width, new_height), Image.LANCZOS)
scaled_img = ImageTk.PhotoImage(scaled_img)
canvas.create_image(canvas.winfo_width() // 2 + x_shift, canvas.winfo_height() // 2 + y_shift, anchor='center', image=scaled_img)
canvas.image = scaled_img # Giữ tham chiếu để không bị thu hồi bởi garbage collector
if total_pages > 1:
update_navigation_controls()
def update_navigation_controls():
# Tính toán tọa độ cho các nút điều hướng
canvas_width = canvas.winfo_width()
canvas_height = canvas.winfo_height()
control_height = 30
control_width = 40
# Vị trí của các nút và ô nhập
back_button_x = canvas_width - 3 * control_width - 20
page_entry_x = back_button_x + control_width + 5
next_button_x = page_entry_x + control_width + 5
y_position = canvas_height - control_height - 10
canvas.create_window(next_button_x, y_position, anchor='se', window=next_button)
canvas.create_window(back_button_x, y_position, anchor='se', window=back_button)
canvas.create_window(page_entry_x, y_position, anchor='se', window=page_entry)
def next_page():
global current_page_index
if current_page_index < total_pages - 1:
current_page_index += 1
load_page(current_page_index)
display_image()
update_page_number()
def previous_page():
global current_page_index
if current_page_index > 0:
current_page_index -= 1
load_page(current_page_index)
display_image()
update_page_number()
def process_pdf():
global current_file, current_pix, new_file_path, img_buffer
if not current_file:
messagebox.showwarning("Warning", "Vui lòng chọn file PDF trước.")
return
try:
new_width = float(width_entry.get()) * 2.83465
new_height = float(height_entry.get()) * 2.83465
offset = float(offset_entry.get()) * 2.83465
margin_top = float(margin_top_entry.get()) * 2.83465
margin_bottom = float(margin_bottom_entry.get()) * 2.83465
margin_left = float(margin_left_entry.get()) * 2.83465
margin_right = float(margin_right_entry.get()) * 2.83465
except ValueError:
messagebox.showerror("Error", "Vui lòng nhập đúng các giá trị kích thước và số lượng.")
return
# Lưu thông số vào tệp JSON
settings = {
"width": new_width / 2.83465,
"height": new_height / 2.83465,
"crop_offset": offset / 2.83465,
"margin_top": margin_top / 2.83465,
"margin_bottom": margin_bottom / 2.83465,
"margin_left": margin_left / 2.83465,
"margin_right": margin_right / 2.83465,
}
save_settings(settings)
# Kiểm tra loại tem và chọn module tương ứng
if template_var.get() == 1:
module = "module1.py" # Tem thẳng
elif template_var.get() == 2:
module = "module2.py" # Tem demi
elif template_var.get() == 3:
module = "module3.py" # Tem tròn
elif template_var.get() == 4:
module = "module4.py" # Hình dạng khác
else:
messagebox.showerror("Error", "Chỉ hỗ trợ tem thẳng, tem tròn và tem demi hiện tại.")
return
# Gọi module với các thông số đã nhập
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
result = subprocess.run(
["python", module, current_file, str(new_width), str(new_height), str(offset),
str(margin_top), str(margin_bottom), str(margin_left), str(margin_right), print_technique_var.get()],
capture_output=True,
text=True,
startupinfo=startupinfo
)
# In kết quả để debug
print(f"result.stdout: {result.stdout}")
print(f"result.stderr: {result.stderr}")
# Kiểm tra kết quả trả về
if result.returncode != 0:
messagebox.showerror("Error", f"Đã xảy ra lỗi trong quá trình xử lý: {result.stderr}")
return
# Parse JSON result
output_data = json.loads(result.stdout)
total_objects = output_data['total_objects']
new_file_path = output_data['new_file_path']
# Đọc kết quả và hiển thị lên canvas
doc = fitz.open(new_file_path)
page = doc.load_page(0)
pix = page.get_pixmap()
img_buffer = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
img = ImageTk.PhotoImage(img_buffer)
scale = 1.0
x_shift = 0
y_shift = 0
display_image()
# Hiển thị tổng số con
count_entry.config(state='normal')
count_entry.delete(0, tk.END)
count_entry.insert(0, str(total_objects))
count_entry.config(state='readonly')
Hàm lưu PDF
def save_pdf():
global new_file_path
if not new_file_path:
messagebox.showwarning("Warning", "Vui lòng xử lý file PDF trước.")
return
save_path = filedialog.asksaveasfilename(defaultextension=".pdf", filetypes=[("PDF files", "*.pdf")])
if save_path:
shutil.copy(new_file_path, save_path)
messagebox.showinfo("Info", f"PDF đã được lưu thành công tại {save_path}")
# Xóa thư mục output và các file liên quan
output_folder = os.path.dirname(new_file_path)
shutil.rmtree(output_folder, ignore_errors=True)
Hàm xử lý kéo thả file
def drop(event):
file_path = event.data
if file_path.startswith("{") and file_path.endswith("}"):
file_path = file_path[1:-1]
select_file(file_path)
root.mainloop()
hãy xem mã này tại sao lỗi PS C:\Users\tamhi> & C:/Python311/python.exe "d:/code python/repack new/Optimumpro.py"
result.stdout:
result.stderr: python: can't open file 'C:\Users\tamhi\module1.py': [Errno 2] No such file or directory mặc dù các module đang cùng thư mục với mã
The error you're encountering occurs because when your main script Optimumpro.py runs the subprocess to execute module1.py, the Python interpreter cannot find module1.py because it's looking in the wrong directory.
Here's what's happening:
In your code, you set module = "module1.py" (or module2.py, etc.).
When you call subprocess.run, you pass this module variable as an argument, resulting in a command like python module1.py ....
Unless the current working directory is the same as the directory containing module1.py, Python won't find module1.py.
The error message you're seeing indicates that Python is looking for module1.py in C:\Users\tamhi\, which is likely your user home directory, not the directory where your script and modules are located.
Solution:
To fix this issue, you need to ensure that Python knows the exact path to module1.py when you run it as a subprocess. Here's how you can do it:
Modify the Module Paths to Include the Full Path
Update your code where you assign module to include the full path by joining it with the directory where your scripts are located. Here's how you can modify your process_pdf function:
# Add this import at the top if not already present
import os
# ...
def process_pdf():
global current_file, current_pix, new_file_path, img_buffer
if not current_file:
messagebox.showwarning("Warning", "Vui lòng chọn file PDF trước.")
return
try:
new_width = float(width_entry.get()) * 2.83465
new_height = float(height_entry.get()) * 2.83465
offset = float(offset_entry.get()) * 2.83465
margin_top = float(margin_top_entry.get()) * 2.83465
margin_bottom = float(margin_bottom_entry.get()) * 2.83465
margin_left = float(margin_left_entry.get()) * 2.83465
margin_right = float(margin_right_entry.get()) * 2.83465
except ValueError:
messagebox.showerror("Error", "Vui lòng nhập đúng các giá trị kích thước và số lượng.")
return
# Save settings to JSON file
settings = {
"width": new_width / 2.83465,
"height": new_height / 2.83465,
"crop_offset": offset / 2.83465,
"margin_top": margin_top / 2.83465,
"margin_bottom": margin_bottom / 2.83465,
"margin_left": margin_left / 2.83465,
"margin_right": margin_right / 2.83465,
}
save_settings(settings)
# Determine the module to use based on the template
if template_var.get() == 1:
module = os.path.join(directory, "module1.py") # Tem thẳng
elif template_var.get() == 2:
module = os.path.join(directory, "module2.py") # Tem demi
elif template_var.get() == 3:
module = os.path.join(directory, "module3.py") # Tem tròn
elif template_var.get() == 4:
module = os.path.join(directory, "module4.py") # Hình dạng khác
else:
messagebox.showerror("Error", "Chỉ hỗ trợ tem thẳng, tem tròn và tem demi hiện tại.")
return
# Call the module with the input parameters
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
result = subprocess.run(
["python", module, current_file, str(new_width), str(new_height), str(offset),
str(margin_top), str(margin_bottom), str(margin_left), str(margin_right), print_technique_var.get()],
capture_output=True,
text=True,
startupinfo=startupinfo
)
# Rest of your code...
By using os.path.join(directory, "module1.py"), you provide the full path to module1.py, ensuring that Python can find it regardless of the current working directory.
Alternatively, Specify the Working Directory for the Subprocess
If you prefer, you can set the cwd (current working directory) parameter in your subprocess.run call to the directory where your scripts are located:
result = subprocess.run(
["python", module, current_file, str(new_width), str(new_height), str(offset),
str(margin_top), str(margin_bottom), str(margin_left), str(margin_right), print_technique_var.get()],
capture_output=True,
text=True,
startupinfo=startupinfo,
cwd=directory # Add this line
)
This way, the subprocess will run from the directory where your scripts are located, and it should be able to find module1.py or any other modules.
Additional Considerations:
Paths with Spaces:
Your directory path 'd:/code python/repack new/' contains spaces. While subprocess.run handles this correctly when you pass arguments as a list, ensure that the paths are properly handled. By providing the full path or setting the cwd, you mitigate any issues related to spaces in the path.
Verify Paths and Directories:
You can add print statements or logging to confirm that directory is correctly set, and that the modules exist at the expected paths.
Double-check that module1.py, module2.py, etc., are indeed in the same directory as your main script.
Explanation of the Error Message:
Error Message:
result.stdout:
result.stderr: python: can't open file 'C:\\Users\\tamhi\\module1.py': [Errno 2] No such file or directory
Cause:
The error indicates that Python attempted to open module1.py in C:\Users\tamhi\, which is your home directory, not where module1.py is actually located. This happens because the subprocess uses the current working directory by default, which, in your case, is not the directory containing module1.py. As a result, Python cannot find and open module1.py, leading to the error.
By making the above changes to your code, you should resolve the issue and enable your script to locate and execute module1.py (or the appropriate module) correctly.
Let me know if you have any further questions or if the issue persists after making these changes.