import fitz # PyMuPDF
import sys
import json
import os
import re
import time
import shutil
Hằng số
MARGIN_MM = 5 # Lề 5mm mỗi cạnh
POINTS_PER_MM = 2.83465 # Hệ số chuyển đổi từ mm sang points
Thư mục đầu vào, đầu ra và thư mục lưu trữ tệp đã xử lý
input_folder = "C:/Users/tamhi/Desktop/in demi hg" # Thay thế bằng đường dẫn thư mục đầu vào của bạn
output_folder = "C:/Users/tamhi/Desktop/outdemi hg" # Thay thế bằng đường dẫn thư mục đầu ra của bạn
processed_folder = "C:/Users/tamhi/Desktop/processed" # Thay thế bằng đường dẫn thư mục lưu trữ tệp đã xử lý
Đảm bảo các thư mục tồn tại
if not os.path.exists(output_folder):
os.makedirs(output_folder)
if not os.path.exists(processed_folder):
os.makedirs(processed_folder)
# Trích xuất kích thước từ tên tệp
dimensions_match = re.search(r'\((\d+)[xX](\d+)\)', name_without_ext)
if dimensions_match:
new_width_mm = int(dimensions_match.group(1)) # mm
new_height_mm = int(dimensions_match.group(2)) # mm
else:
# Nếu không tìm thấy kích thước, báo lỗi
raise ValueError(f"Không tìm thấy kích thước trong tên tệp '{filename}'.")
# Xác định khoảng cách crop marks dựa trên '1 dao' hoặc '2 dao' trong tên tệp
name_lower = name_without_ext.lower().replace(' ', '')
if '1dao' in name_lower:
crop_marks_offset_mm = 0 # mm
else:
crop_marks_offset_mm = 4 # mm
return new_width_mm, new_height_mm, crop_marks_offset_mm, name_without_ext
Hàm kiểm tra đối tượng có chồng lên các đối tượng khác hay không
def is_overlapping(new_rect, objects):
for obj, angle in objects:
if new_rect.intersects(obj):
return True
return False
Nhân bản và sắp xếp đối tượng
def arrange_objects(new_width, new_height, obj_width, obj_height, margin_top, margin_bottom, margin_left, margin_right):
def place_objects(new_width, new_height, obj_width, obj_height, angle):
objects = []
x, y = margin_left, margin_top
while (x + obj_width) <= new_width - margin_right:
while (y + obj_height) <= new_height - margin_bottom:
new_rect = fitz.Rect(x, y, x + obj_width, y + obj_height)
if not is_overlapping(new_rect, objects):
objects.append((new_rect, angle))
y += obj_height
x += obj_width
y = margin_top
return len(objects), objects
Assistant
code
# Không xoay
count_no_rotate, objects_no_rotate = place_objects(new_width, new_height, obj_width, obj_height, 0)
# Xoay 90 độ
count_rotate_90, objects_rotate_90 = place_objects(new_width, new_height, obj_height, obj_width, 90)
# Hỗn hợp
objects_mixed = []
x, y = margin_left, margin_top
while (x + obj_width) <= new_width - margin_right:
while (y + obj_height) <= new_height - margin_bottom:
new_rect = fitz.Rect(x, y, x + obj_width, y + obj_height)
if not is_overlapping(new_rect, objects_mixed):
objects_mixed.append((new_rect, 0))
y += obj_height
x += obj_width
y = margin_top
width_remaining = new_width - margin_right - (x - obj_width)
if width_remaining >= obj_height:
x = new_width - margin_right - width_remaining
y = margin_top
while (x + obj_height) <= new_width - margin_right:
while (y + obj_width) <= new_height - margin_bottom:
new_rect = fitz.Rect(x, y, x + obj_height, y + obj_width)
if not is_overlapping(new_rect, objects_mixed):
objects_mixed.append((new_rect, 90))
y += obj_width
x += obj_height
y = margin_top
count_mixed = len(objects_mixed)
# Chọn cách sắp xếp tối ưu
if count_mixed > max(count_no_rotate, count_rotate_90):
return objects_mixed
elif count_rotate_90 > count_no_rotate:
return objects_rotate_90
else:
return objects_no_rotate
Lặp lại để tận dụng các khoảng trống còn lại
def fill_remaining_space(objects, obj_width, obj_height, new_width, new_height, margin_top, margin_bottom, margin_left, margin_right):
remaining_space = True
while remaining_space:
remaining_space = False
new_objects = []
x, y = margin_left, margin_top
while (x + obj_width) <= new_width - margin_right:
while (y + obj_height) <= new_height - margin_bottom:
new_rect = fitz.Rect(x, y, x + obj_width, y + obj_height)
if not is_overlapping(new_rect, objects):
new_objects.append((new_rect, 0))
objects.append((new_rect, 0))
remaining_space = True
y += obj_height
x += obj_width
y = margin_top
code
x, y = margin_left, margin_top
while (x + obj_height) <= new_width - margin_right:
while (y + obj_width) <= new_height - margin_bottom:
new_rect = fitz.Rect(x, y, x + obj_height, y + obj_width)
if not is_overlapping(new_rect, objects):
new_objects.append((new_rect, 90))
objects.append((new_rect, 90))
remaining_space = True
y += obj_width
x += obj_height
y = margin_top
# Tính toán vị trí crop marks
left = x0 - offset if offset > 0 else x0
right = x1 + offset if offset > 0 else x1
top = y0 - offset if offset > 0 else y0
bottom = y1 + offset if offset > 0 else y1
unique_y_positions.update([top, bottom])
unique_x_positions.update([left, right])
# Vẽ các đường crop mark
for y in unique_y_positions:
if y >= margin_top and y <= new_height - margin_bottom:
page.draw_line((margin_left, y), (new_width - margin_right, y), width=crop_thickness, color=(0, 0, 0))
for x in unique_x_positions:
if x >= margin_left and x <= new_width - margin_right:
page.draw_line((x, margin_top), (x, new_height - margin_bottom), width=crop_thickness, color=(0, 0, 0))
Hàm xử lý PDF
def process_pdf(input_file, output_folder, new_width, new_height, offset, margin_top, margin_bottom, margin_left, margin_right):
# Định nghĩa thông số crop mark
crop_thickness = 0.5 # pt
crop_length = 2 * POINTS_PER_MM # 2mm
code
# Đọc file PDF và trích xuất đối tượng
doc = fitz.open(input_file)
new_doc = fitz.open()
total_objects = 0
for page_num in range(len(doc)):
page = doc.load_page(page_num) # Đọc mỗi trang trong file PDF
# Tìm bounding box của nội dung trang
bbox = page.bound() if page.bound() else page.rect
if bbox.is_empty:
# Nếu không tìm thấy bounding box, sử dụng toàn bộ trang
bbox = page.rect
obj_width, obj_height = bbox.width, bbox.height
# Tính toán các sắp xếp không xoay, có xoay và hỗn hợp
initial_objects = arrange_objects(new_width, new_height, obj_width, obj_height, margin_top, margin_bottom, margin_left, margin_right)
# Lặp lại để tận dụng các khoảng trống còn lại
fill_remaining_space(initial_objects, obj_width, obj_height, new_width, new_height, margin_top, margin_bottom, margin_left, margin_right)
total_objects += len(initial_objects) # Đếm số con
# Căn chỉnh các đối tượng để sắp xếp sát nhau
initial_objects = align_objects(initial_objects)
# Tính toán vị trí bắt đầu để canh giữa các đối tượng
if initial_objects:
min_x = min(obj[0].x0 for obj in initial_objects)
min_y = min(obj[0].y0 for obj in initial_objects)
max_x = max(obj[0].x1 for obj in initial_objects)
max_y = max(obj[0].y1 for obj in initial_objects)
offset_x = (new_width - (max_x - min_x)) / 2 - min_x
offset_y = (new_height - (max_y - min_y)) / 2 - min_y
for i in range(len(initial_objects)):
obj_rect, angle = initial_objects[i]
initial_objects[i] = (fitz.Rect(obj_rect.x0 + offset_x, obj_rect.y0 + offset_y,
obj_rect.x1 + offset_x, obj_rect.y1 + offset_y), angle)
# Tạo trang mới trong file PDF mới và thêm các đối tượng đã nhân bản vào
new_page = new_doc.new_page(width=new_width, height=new_height)
for obj_rect, angle in initial_objects:
new_page.show_pdf_page(obj_rect, doc, page_num, clip=bbox, rotate=angle)
# Thêm crop marks
add_crop_marks(new_page, initial_objects, offset, crop_length, crop_thickness, new_width, new_height, margin_top, margin_bottom, margin_left, margin_right)
# Tạo tên file đầu ra với tổng số đối tượng nhân bản
base_filename = os.path.basename(input_file)
output_filename = f"{os.path.splitext(base_filename)[0]} {total_objects}.pdf"
output_filepath = os.path.join(output_folder, output_filename)
new_doc.save(output_filepath)
new_doc.close()
doc.close()
return total_objects
Bắt đầu quá trình xử lý
processed_files = set()
while True:
pdf_files = [f for f in os.listdir(input_folder) if f.lower().endswith('.pdf')]
code
for pdf_file in pdf_files:
if pdf_file in processed_files:
continue # Bỏ qua các tệp đã xử lý
input_file = os.path.join(input_folder, pdf_file)
try:
new_width_mm, new_height_mm, crop_marks_offset_mm, base_filename = parse_filename(pdf_file)
except ValueError as e:
print(f"Lỗi khi phân tích tên tệp '{pdf_file}': {e}")
# Di chuyển tệp lỗi sang thư mục processed để không xử lý lại
shutil.move(input_file, os.path.join(processed_folder, pdf_file))
processed_files.add(pdf_file)
continue # Bỏ qua tệp này
# Chuyển đổi kích thước và lề sang points
new_width_pt = new_width_mm * POINTS_PER_MM
new_height_pt = new_height_mm * POINTS_PER_MM
margin_top_pt = MARGIN_MM * POINTS_PER_MM
margin_bottom_pt = MARGIN_MM * POINTS_PER_MM
margin_left_pt = MARGIN_MM * POINTS_PER_MM
margin_right_pt = MARGIN_MM * POINTS_PER_MM
offset_pt = crop_marks_offset_mm * POINTS_PER_MM
# Xử lý PDF và lấy số lượng đối tượng nhân bản
total_objects = process_pdf(
input_file,
output_folder,
new_width_pt,
new_height_pt,
offset_pt,
margin_top_pt,
margin_bottom_pt,
margin_left_pt,
margin_right_pt
)
print(f"Đã xử lý '{pdf_file}', tổng số con nhân bản: {total_objects}")
# Di chuyển tệp đã xử lý sang thư mục processed
shutil.move(input_file, os.path.join(processed_folder, pdf_file))
processed_files.add(pdf_file)
# Chờ 3 giây trước khi quét lại
time.sleep(3)
giữ nguyên mã này loaii bỏ phần tính toán hỗn hợp trong mã
python
import fitz # PyMuPDF
import sys
import json
import os
import re
import time
import shutil
# Hằng số
MARGIN_MM = 5 # Lề 5mm mỗi cạnh
POINTS_PER_MM = 2.83465 # Hệ số chuyển đổi từ mm sang points
# Thư mục đầu vào, đầu ra và thư mục lưu trữ tệp đã xử lý
input_folder = "C:/Users/tamhi/Desktop/in demi hg" # Thay thế bằng đường dẫn thư mục đầu vào của bạn
output_folder = "C:/Users/tamhi/Desktop/outdemi hg" # Thay thế bằng đường dẫn thư mục đầu ra của bạn
processed_folder = "C:/Users/tamhi/Desktop/processed" # Thay thế bằng đường dẫn thư mục lưu trữ tệp đã xử lý
# Đảm bảo các thư mục tồn tại
if not os.path.exists(output_folder):
os.makedirs(output_folder)
if not os.path.exists(processed_folder):
os.makedirs(processed_folder)
# Hàm phân tích tên tệp để trích xuất các thông số
def parse_filename(filename):
base_name = os.path.basename(filename)
name_without_ext = os.path.splitext(base_name)[0] # Bỏ phần mở rộng '.pdf'
# Trích xuất kích thước từ tên tệp
dimensions_match = re.search(r'\((\d+)[xX](\d+)\)', name_without_ext)
if dimensions_match:
new_width_mm = int(dimensions_match.group(1)) # mm
new_height_mm = int(dimensions_match.group(2)) # mm
else:
# Nếu không tìm thấy kích thước, báo lỗi
raise ValueError(f"Không tìm thấy kích thước trong tên tệp '{filename}'.")
# Xác định khoảng cách crop marks dựa trên '1 dao' hoặc '2 dao' trong tên tệp
name_lower = name_without_ext.lower().replace(' ', '')
if '1dao' in name_lower:
crop_marks_offset_mm = 0 # mm
else:
crop_marks_offset_mm = 4 # mm
return new_width_mm, new_height_mm, crop_marks_offset_mm, name_without_ext
# Hàm kiểm tra đối tượng có chồng lên các đối tượng khác hay không
def is_overlapping(new_rect, objects):
for obj, angle in objects:
if new_rect.intersects(obj):
return True
return False
# Nhân bản và sắp xếp đối tượng
def arrange_objects(new_width, new_height, obj_width, obj_height, margin_top, margin_bottom, margin_left, margin_right):
def place_objects(new_width, new_height, obj_width, obj_height, angle):
objects = []
x, y = margin_left, margin_top
while (x + obj_width) <= new_width - margin_right:
while (y + obj_height) <= new_height - margin_bottom:
new_rect = fitz.Rect(x, y, x + obj_width, y + obj_height)
if not is_overlapping(new_rect, objects):
objects.append((new_rect, angle))
y += obj_height
x += obj_width
y = margin_top
return len(objects), objects
# Không xoay
count_no_rotate, objects_no_rotate = place_objects(new_width, new_height, obj_width, obj_height, 0)
# Xoay 90 độ
count_rotate_90, objects_rotate_90 = place_objects(new_width, new_height, obj_height, obj_width, 90)
# Chọn cách sắp xếp tối ưu
if count_rotate_90 > count_no_rotate:
return objects_rotate_90
else:
return objects_no_rotate
# Lặp lại để tận dụng các khoảng trống còn lại
def fill_remaining_space(objects, obj_width, obj_height, new_width, new_height, margin_top, margin_bottom, margin_left, margin_right):
remaining_space = True
while remaining_space:
remaining_space = False
new_objects = []
x, y = margin_left, margin_top
while (x + obj_width) <= new_width - margin_right:
while (y + obj_height) <= new_height - margin_bottom:
new_rect = fitz.Rect(x, y, x + obj_width, y + obj_height)
if not is_overlapping(new_rect, objects):
new_objects.append((new_rect, 0))
objects.append((new_rect, 0))
remaining_space = True
y += obj_height
x += obj_width
y = margin_top
x, y = margin_left, margin_top
while (x + obj_height) <= new_width - margin_right:
while (y + obj_width) <= new_height - margin_bottom:
new_rect = fitz.Rect(x, y, x + obj_height, y + obj_width)
if not is_overlapping(new_rect, objects):
new_objects.append((new_rect, 90))
objects.append((new_rect, 90))
remaining_space = True
y += obj_width
x += obj_height
y = margin_top
# Hàm căn chỉnh các đối tượng để sắp xếp sát nhau
def align_objects(objects):
sorted_objects = sorted(objects, key=lambda obj: (obj[0].y0, obj[0].x0))
for i in range(1, len(sorted_objects)):
prev_rect, prev_angle = sorted_objects[i-1]
curr_rect, curr_angle = sorted_objects[i]
if curr_rect.x0 > prev_rect.x1:
new_x0 = prev_rect.x1
new_x1 = new_x0 + (curr_rect.x1 - curr_rect.x0)
sorted_objects[i] = (fitz.Rect(new_x0, curr_rect.y0, new_x1, curr_rect.y1), curr_angle)
return sorted_objects
# Hàm thêm crop marks vào đối tượng
def add_crop_marks(page, objects, offset, crop_length, crop_thickness, new_width, new_height, margin_top, margin_bottom, margin_left, margin_right):
unique_y_positions = set()
unique_x_positions = set()
for obj_rect, angle in objects:
x0, y0 = obj_rect.x0, obj_rect.y0
x1, y1 = obj_rect.x1, obj_rect.y1
# Tính toán vị trí crop marks
left = x0 - offset if offset > 0 else x0
right = x1 + offset if offset > 0 else x1
top = y0 - offset if offset > 0 else y0
bottom = y1 + offset if offset > 0 else y1
unique_y_positions.update([top, bottom])
unique_x_positions.update([left, right])
# Vẽ các đường crop mark
for y in unique_y_positions:
if y >= margin_top and y <= new_height - margin_bottom:
page.draw_line((margin_left, y), (new_width - margin_right, y), width=crop_thickness, color=(0, 0, 0))
for x in unique_x_positions:
if x >= margin_left and x <= new_width - margin_right:
page.draw_line((x, margin_top), (x, new_height - margin_bottom), width=crop_thickness, color=(0, 0, 0))
# Hàm xử lý PDF
def process_pdf(input_file, output_folder, new_width, new_height, offset, margin_top, margin_bottom, margin_left, margin_right):
# Định nghĩa thông số crop mark
crop_thickness = 0.5 # pt
crop_length = 2 * POINTS_PER_MM # 2mm
# Đọc file PDF và trích xuất đối tượng
doc = fitz.open(input_file)
new_doc = fitz.open()
total_objects = 0
for page_num in range(len(doc)):
page = doc.load_page(page_num) # Đọc mỗi trang trong file PDF
# Tìm bounding box của nội dung trang
bbox = page.bound() if page.bound() else page.rect
if bbox.is_empty:
# Nếu không tìm thấy bounding box, sử dụng toàn bộ trang
bbox = page.rect
obj_width, obj_height = bbox.width, bbox.height
# Tính toán các sắp xếp không xoay và có xoay
initial_objects = arrange_objects(new_width, new_height, obj_width, obj_height, margin_top, margin_bottom, margin_left, margin_right)
# Lặp lại để tận dụng các khoảng trống còn lại
fill_remaining_space(initial_objects, obj_width, obj_height, new_width, new_height, margin_top, margin_bottom, margin_left, margin_right)
total_objects += len(initial_objects) # Đếm số con
# Căn chỉnh các đối tượng để sắp xếp sát nhau
initial_objects = align_objects(initial_objects)
# Tính toán vị trí bắt đầu để canh giữa các đối tượng
if initial_objects:
min_x = min(obj[0].x0 for obj in initial_objects)
min_y = min(obj[0].y0 for obj in initial_objects)
max_x = max(obj[0].x1 for obj in initial_objects)
max_y = max(obj[0].y1 for obj in initial_objects)
offset_x = (new_width - (max_x - min_x)) / 2 - min_x
offset_y = (new_height - (max_y - min_y)) / 2 - min_y
for i in range(len(initial_objects)):
obj_rect, angle = initial_objects[i]
initial_objects[i] = (fitz.Rect(obj_rect.x0 + offset_x, obj_rect.y0 + offset_y,
obj_rect.x1 + offset_x, obj_rect.y1 + offset_y), angle)
# Tạo trang mới trong file PDF mới và thêm các đối tượng đã nhân bản vào
new_page = new_doc.new_page(width=new_width, height=new_height)
for obj_rect, angle in initial_objects:
new_page.show_pdf_page(obj_rect, doc, page_num, clip=bbox, rotate=angle)
# Thêm crop marks
add_crop_marks(new_page, initial_objects, offset, crop_length, crop_thickness, new_width, new_height, margin_top, margin_bottom, margin_left, margin_right)
# Tạo tên file đầu ra với tổng số đối tượng nhân bản
base_filename = os.path.basename(input_file)
output_filename = f"{os.path.splitext(base_filename)[0]} {total_objects}.pdf"
output_filepath = os.path.join(output_folder, output_filename)
new_doc.save(output_filepath)
new_doc.close()
doc.close()
return total_objects
# Bắt đầu quá trình xử lý
processed_files = set()
while True:
pdf_files = [f for f in os.listdir(input_folder) if f.lower().endswith('.pdf')]
for pdf_file in pdf_files:
if pdf_file in processed_files:
continue # Bỏ qua các tệp đã xử lý
input_file = os.path.join(input_folder, pdf_file)
try:
new_width_mm, new_height_mm, crop_marks_offset_mm, base_filename = parse_filename(pdf_file)
except ValueError as e:
print(f"Lỗi khi phân tích tên tệp '{pdf_file}': {e}")
# Di chuyển tệp lỗi sang thư mục processed để không xử lý lại
shutil.move(input_file, os.path.join(processed_folder, pdf_file))
processed_files.add(pdf_file)
continue # Bỏ qua tệp này
# Chuyển đổi kích thước và lề sang points
new_width_pt = new_width_mm * POINTS_PER_MM
new_height_pt = new_height_mm * POINTS_PER_MM
margin_top_pt = MARGIN_MM * POINTS_PER_MM
margin_bottom_pt = MARGIN_MM * POINTS_PER_MM
margin_left_pt = MARGIN_MM * POINTS_PER_MM
margin_right_pt = MARGIN_MM * POINTS_PER_MM
offset_pt = crop_marks_offset_mm * POINTS_PER_MM
# Xử lý PDF và lấy số lượng đối tượng nhân bản
total_objects = process_pdf(
input_file,
output_folder,
new_width_pt,
new_height_pt,
offset_pt,
margin_top_pt,
margin_bottom_pt,
margin_left_pt,
margin_right_pt
)
print(f"Đã xử lý '{pdf_file}', tổng số con nhân bản: {total_objects}")
# Di chuyển tệp đã xử lý sang thư mục processed
shutil.move(input_file, os.path.join(processed_folder, pdf_file))
processed_files.add(pdf_file)
# Chờ 3 giây trước khi quét lại
time.sleep(3)
Giải thích thay đổi:
Trong đoạn mã trên, phần tính toán sắp xếp hỗn hợp đã được loại bỏ khỏi hàm arrange_objects. Cụ thể:
Phần mã liên quan đến sắp xếp hỗn hợp (phần có chú thích # Hỗn hợp) đã được xóa.
Hàm arrange_objects bây giờ chỉ tính toán hai trường hợp:
count_no_rotate, objects_no_rotate: Sắp xếp không xoay.
count_rotate_90, objects_rotate_90: Sắp xếp với góc xoay 90 độ.
Cuối cùng, hàm sẽ chọn cách sắp xếp cho số lượng đối tượng tối ưu hơn giữa hai phương án trên.