Skip to content
The Chat Archive
o1-preview-2024-09-12· OpenAI WildChat-4.8M (AI2)

def applyzigzagimposition(self, inputpdfpath, outputpdfpath): """Applies the cut and…

  1. User

    def apply_zigzag_imposition(self, input_pdf_path, output_pdf_path): """Applies the cut and stack imposition method to arrange pages. When the input PDF has exactly 2 pages, it arranges the front and back sides accordingly, reversing the columns on the back side while maintaining cut and stack numbering."""

        # Fetch parameters from the user interface
        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()
        cropmark_length = self.cropmark_length_var.get()
    
        # Convert units from mm to 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)
        crop_length_pt = self.mm_to_points(cropmark_length)
    
        crop_thickness = 0.5  # Độ dày của crop marks
    
        # Tính toán khu vực có thể sử dụng
        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)
        total_pages = len(doc)
    
        # Lấy kích thước trang đầu vào
        input_page = doc.load_page(0)
        bbox = input_page.rect
        entry_width_orig = bbox.width
        entry_height_orig = bbox.height
    
        # Các tùy chọn xoay và không xoay
        options = [
            {'rotate': False, 'entry_width': entry_width_orig, 'entry_height': entry_height_orig},
            {'rotate': True, 'entry_width': entry_height_orig, 'entry_height': entry_width_orig},
        ]
    
        # Xác định cách sắp xếp tốt nhất
        best_arrangement = None
        max_total_entries = 0
        for option in options:
            entries_per_row = int(available_width // option['entry_width'])
            entries_per_column = int(available_height // option['entry_height'])
            total_entries = entries_per_row * entries_per_column
            if total_entries > max_total_entries:
                max_total_entries = total_entries
                best_arrangement = option.copy()
                best_arrangement['entries_per_row'] = entries_per_row
                best_arrangement['entries_per_column'] = entries_per_column
    
        if not best_arrangement or best_arrangement['entries_per_row'] == 0 or best_arrangement['entries_per_column'] == 0:
            messagebox.showerror("Error", "Kích thước trang hoặc lề quá nhỏ để sắp xếp nội dung.")
            doc.close()
            return
    
        # Tính toán tổng kích thước lưới để căn giữa nội dung
        total_grid_width = best_arrangement['entries_per_row'] * best_arrangement['entry_width']
        total_grid_height = best_arrangement['entries_per_column'] * best_arrangement['entry_height']
        x_offset = margin_left_pt + (available_width - total_grid_width) / 2
        y_offset = margin_top_pt + (available_height - total_grid_height) / 2
    
        # Tạo tài liệu mới cho kết quả
        new_doc = fitz.open()
    
        # Nếu tệp PDF có đúng 2 trang, áp dụng xử lý đặc biệt
        if total_pages == 2:
            # Số trang trên mỗi mặt
            num_entries = best_arrangement['entries_per_row'] * best_arrangement['entries_per_column']
    
            # Tạo danh sách số trang cho mặt trước và mặt sau
            front_pages = [0] * num_entries  # Trang 0 cho mặt trước
            back_pages = [1] * num_entries   # Trang 1 cho mặt sau
    
            # Tạo trang mặt trước
            front_page = new_doc.new_page(width=new_page_width_pt, height=new_page_height_pt)
            arranged_rects_front = []
    
            index = 0
            for row in range(best_arrangement['entries_per_column']):
                for col in range(best_arrangement['entries_per_row']):
                    x = x_offset + col * best_arrangement['entry_width']
                    y = y_offset + row * best_arrangement['entry_height']
                    rect = fitz.Rect(
                        x,
                        y,
                        x + best_arrangement['entry_width'],
                        y + best_arrangement['entry_height']
                    )
                    if best_arrangement['rotate']:
                        front_page.show_pdf_page(rect, doc, pno=front_pages[index], rotate=90)
                    else:
                        front_page.show_pdf_page(rect, doc, pno=front_pages[index])
                    arranged_rects_front.append((rect, row, col))
                    index += 1
    
            # Thêm crop marks cho mặt trước
            for rect, row, col in arranged_rects_front:
                edges = []
                if row == 0:
                    edges.append('top')
                if row == best_arrangement['entries_per_column'] - 1:
                    edges.append('bottom')
                if col == 0:
                    edges.append('left')
                if col == best_arrangement['entries_per_row'] - 1:
                    edges.append('right')
                if edges:
                    self.add_crop_marks(front_page, rect, edges, cropmark_offset_pt, crop_length_pt, crop_thickness)
    
            # Tạo trang mặt sau
            back_page = new_doc.new_page(width=new_page_width_pt, height=new_page_height_pt)
            arranged_rects_back = []
    
            index = 0
            for row in range(best_arrangement['entries_per_column']):
                for col in range(best_arrangement['entries_per_row']):
                    # Đảo ngược toàn bộ cột: bên trái đổi sang bên phải và ngược lại
                    reversed_col = best_arrangement['entries_per_row'] - 1 - col
                    x = x_offset + col * best_arrangement['entry_width']  # Giữ nguyên cột cho mặt sau
                    y = y_offset + row * best_arrangement['entry_height']
                    rect = fitz.Rect(
                        x,
                        y,
                        x + best_arrangement['entry_width'],
                        y + best_arrangement['entry_height']
                    )
                    if best_arrangement['rotate']:
                        back_page.show_pdf_page(rect, doc, pno=back_pages[index], rotate=90)
                    else:
                        back_page.show_pdf_page(rect, doc, pno=back_pages[index])
                    arranged_rects_back.append((rect, row, col))  # Thay reversed_col bằng col để sắp xếp đúng thứ tự hàng
                    index += 1
    
            # Thêm crop marks cho mặt sau
            for rect, row, col in arranged_rects_back:
                edges = []
                if row == 0:
                    edges.append('top')
                if row == best_arrangement['entries_per_column'] - 1:
                    edges.append('bottom')
                if col == 0:
                    edges.append('left')
                if col == best_arrangement['entries_per_row'] - 1:
                    edges.append('right')
                if edges:
                    self.add_crop_marks(back_page, rect, edges, cropmark_offset_pt, crop_length_pt, crop_thickness)
    
    
        else:
            # Trường hợp khác, giữ nguyên logic hiện tại
            # Tính toán số lượng tờ in
            sheets_needed = (total_pages + max_total_entries - 1) // max_total_entries
    
            # Tạo danh sách các danh sách, mỗi danh sách con đại diện cho các trang trên một tờ in
            sheets_pages = [[] for _ in range(sheets_needed)]
    
            # Phân phối các trang vào các tờ in theo phương pháp cắt và xếp chồng
            entries_per_sheet = best_arrangement['entries_per_row'] * best_arrangement['entries_per_column']
            for page_num in range(total_pages):
                sheet_index = page_num % sheets_needed
                sheets_pages[sheet_index].append(page_num)
    
            # Sắp xếp lại thứ tự các trang trong mỗi tờ in theo hàng và cột
            for sheet_index, pages_in_sheet in enumerate(sheets_pages):
                new_page = new_doc.new_page(width=new_page_width_pt, height=new_page_height_pt)
                arranged_rects = []
                for idx, page_num in enumerate(pages_in_sheet):
                    col = idx // best_arrangement['entries_per_column']
                    row = idx % best_arrangement['entries_per_column']
                    if col < best_arrangement['entries_per_row'] and row < best_arrangement['entries_per_column']:
                        x = x_offset + col * best_arrangement['entry_width']
                        y = y_offset + row * best_arrangement['entry_height']
                        rect = fitz.Rect(
                            x,
                            y,
                            x + best_arrangement['entry_width'],
                            y + best_arrangement['entry_height']
                        )
                        if best_arrangement['rotate']:
                            new_page.show_pdf_page(rect, doc, pno=page_num, rotate=90)
                        else:
                            new_page.show_pdf_page(rect, doc, pno=page_num)
                        arranged_rects.append((rect, row, col))
    
                # Thêm crop marks
                for rect, row, col in arranged_rects:
                    edges = []
                    if row == 0:
                        edges.append('top')
                    if row == best_arrangement['entries_per_column'] - 1:
                        edges.append('bottom')
                    if col == 0:
                        edges.append('left')
                    if col == best_arrangement['entries_per_row'] - 1:
                        edges.append('right')
                    if edges:
                        self.add_crop_marks(new_page, rect, edges, cropmark_offset_pt, crop_length_pt, crop_thickness)
    
        # Lưu tệp PDF đã áp dụng imposition
        new_doc.save(output_pdf_path)
        new_doc.close()
        doc.close()
    điều chỉnh mã này tôi muốn phần tạo trang của mặt sau các cột được sắp ngược lại vị trí hiện tại tức là phần mặt trước sắp xếp cut and stack và giữ nguyên phần mặt sau cũng sắp cut and stack nhưng ngược lại vị trí các cột so với hiện tại bạn hiểu không
    
  2. Assistant

    Yes, I understand your request. You want the back page to have its columns reversed compared to the front page while maintaining the cut and stack arrangement for both sides.

    To achieve this, we need to adjust the code that creates the back page so that it reverses the column positions. Specifically, we'll modify the calculation of the x coordinate on the back page to use the reversed column index.

    Here's the adjusted code for the back page creation:

    # Tạo trang mặt sau
    back_page = new_doc.new_page(width=new_page_width_pt, height=new_page_height_pt)
    arranged_rects_back = []
    
    index = 0
    for row in range(best_arrangement['entries_per_column']):
        for col in range(best_arrangement['entries_per_row']):
            # Đảo ngược toàn bộ cột: bên trái đổi sang bên phải và ngược lại
            reversed_col = best_arrangement['entries_per_row'] - 1 - col
            x = x_offset + reversed_col * best_arrangement['entry_width']  # Sử dụng reversed_col cho mặt sau
            y = y_offset + row * best_arrangement['entry_height']
            rect = fitz.Rect(
                x,
                y,
                x + best_arrangement['entry_width'],
                y + best_arrangement['entry_height']
            )
            if best_arrangement['rotate']:
                back_page.show_pdf_page(rect, doc, pno=back_pages[index], rotate=90)
            else:
                back_page.show_pdf_page(rect, doc, pno=back_pages[index])
            arranged_rects_back.append((rect, row, reversed_col))  # Lưu reversed_col để dùng cho crop marks
            index += 1
    
    # Thêm crop marks cho mặt sau
    for rect, row, col in arranged_rects_back:
        edges = []
        if row == 0:
            edges.append('top')
        if row == best_arrangement['entries_per_column'] - 1:
            edges.append('bottom')
        if col == 0:
            edges.append('left')
        if col == best_arrangement['entries_per_row'] - 1:
            edges.append('right')
        if edges:
            self.add_crop_marks(back_page, rect, edges, cropmark_offset_pt, crop_length_pt, crop_thickness)
    

    Explanation of Changes:

    • Reversed Column Index:

      • Calculated reversed_col by subtracting col from best_arrangement['entries_per_row'] - 1.
      • This effectively flips the column order so that the leftmost column becomes the rightmost and vice versa.
    • Adjusted X Coordinate:

      • Changed the calculation of x to use reversed_col instead of col.
      • This positions the columns in reverse order on the back page.
    • Updated Rect Storage:

      • When appending to arranged_rects_back, stored reversed_col instead of col.
      • This ensures that when adding crop marks, we have the correct column index.
    • Crop Marks Alignment:

      • In the crop marks loop, col now refers to the reversed column index.
      • The conditions for adding crop marks remain the same since col represents the column position on the back page.

    By making these adjustments, the back page's columns are now reversed compared to the front page, which should meet your requirements.

    Note: The rest of the code remains unchanged, and this adjustment only affects the case when the input PDF has exactly 2 pages, as per your original special handling.

    Let me know if you need any further modifications or explanations!