Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import tkinter as tk
- from tkinter import ttk, filedialog, messagebox
- from PyPDF2 import PdfReader, PdfWriter
- import os
- import traceback
- import sys
- class PDFImposerApp:
- PAGES_PER_SHEET = 4 # Constant for pages per sheet
- def __init__(self, root):
- self.root = root
- self.root.title("PDF Imposer")
- self.root.geometry("600x450") # Adjusted height for LabelFrames
- main_frame = ttk.Frame(root, padding="10") # Reduced padding
- main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
- root.columnconfigure(0, weight=1)
- root.rowconfigure(0, weight=1)
- # Input File Section
- input_frame = ttk.LabelFrame(main_frame, text="Input PDF", padding=10)
- input_frame.grid(row=0, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=5, padx=5)
- input_frame.columnconfigure(1, weight=1)
- ttk.Label(input_frame, text="Input PDF:").grid(row=0, column=0, sticky=tk.W, pady=5, padx=5)
- self.input_path = tk.StringVar()
- ttk.Entry(input_frame, textvariable=self.input_path, width=50).grid(row=0, column=1, padx=5, sticky=(tk.W, tk.E))
- ttk.Button(input_frame, text="Browse", command=self.browse_input).grid(row=0, column=2, padx=5)
- # Output File Section
- output_frame = ttk.LabelFrame(main_frame, text="Output PDF", padding=10)
- output_frame.grid(row=1, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=5, padx=5)
- output_frame.columnconfigure(1, weight=1)
- ttk.Label(output_frame, text="Output PDF:").grid(row=0, column=0, sticky=tk.W, pady=5, padx=5)
- self.output_path = tk.StringVar()
- ttk.Entry(output_frame, textvariable=self.output_path, width=50).grid(row=0, column=1, padx=5, sticky=(tk.W, tk.E))
- ttk.Button(output_frame, text="Browse", command=self.browse_output).grid(row=0, column=2, padx=5)
- # Blank Pages Control
- blank_frame = ttk.LabelFrame(main_frame, text="Blank Pages", padding=10)
- blank_frame.grid(row=2, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=10, padx=5)
- blank_frame.columnconfigure(1, weight=1)
- ttk.Label(blank_frame, text="Additional Blank Pages:").grid(row=0, column=0, sticky=tk.W, pady=5, padx=5)
- self.blank_pages = tk.IntVar(value=0)
- blank_controls_frame = ttk.Frame(blank_frame)
- blank_controls_frame.grid(row=0, column=1, sticky=tk.E, padx=5)
- ttk.Button(blank_controls_frame, text="-", width=3, command=self.decrease_blank).pack(side=tk.LEFT, padx=2)
- ttk.Label(blank_controls_frame, textvariable=self.blank_pages, width=5, anchor="center").pack(side=tk.LEFT, padx=2)
- ttk.Button(blank_controls_frame, text="+", width=3, command=self.increase_blank).pack(side=tk.LEFT, padx=2)
- # Impose button
- ttk.Button(main_frame, text="Rearrange that SHEET!", command=self.impose_pdf).grid(row=3, column=0, columnspan=3, pady=15)
- # Status message
- self.status_var = tk.StringVar()
- ttk.Label(main_frame, textvariable=self.status_var, wraplength=580).grid(row=4, column=0, columnspan=3, sticky=(tk.W, tk.E), padx=5)
- def browse_input(self):
- filename = filedialog.askopenfilename(filetypes=[("PDF files", "*.pdf")])
- if filename:
- self.input_path.set(filename)
- output_dir = os.path.dirname(filename)
- input_name = os.path.splitext(os.path.basename(filename))[0] # Get name without extension
- output_name = f"imposed_{input_name}.pdf"
- self.output_path.set(os.path.join(output_dir, output_name))
- def browse_output(self):
- filename = filedialog.asksaveasfilename(
- defaultextension=".pdf",
- filetypes=[("PDF files", "*.pdf")]
- )
- if filename:
- self.output_path.set(filename)
- def decrease_blank(self):
- if self.blank_pages.get() > 0:
- self.blank_pages.set(self.blank_pages.get() - 1)
- def increase_blank(self):
- self.blank_pages.set(self.blank_pages.get() + 1)
- def create_blank_page(self, template_page):
- """Creates a blank page with the same size as the template page."""
- try:
- media_box = template_page.mediabox
- writer = PdfWriter()
- writer.add_blank_page(width=float(media_box.width), height=float(media_box.height))
- return writer.pages[0]
- except Exception as e:
- raise Exception(f"Error creating blank page: {str(e)}")
- def impose_pdf(self):
- try:
- input_path = self.input_path.get()
- output_path = self.output_path.get()
- if not input_path or not output_path:
- messagebox.showerror("Error", "Please select both input and output files.")
- return
- if not os.path.exists(input_path):
- messagebox.showerror("Error", "Input file not found.")
- return
- self.status_var.set("Processing PDF...")
- self.root.update()
- pdf_reader = PdfReader(input_path)
- pdf_writer = PdfWriter()
- num_pages = len(pdf_reader.pages)
- if not pdf_reader.pages:
- messagebox.showerror("Error", "Input PDF has no pages.")
- return
- template_page = pdf_reader.pages[0]
- # Calculate required blank pages directly
- blanks_needed = (self.PAGES_PER_SHEET - (num_pages % self.PAGES_PER_SHEET)) % self.PAGES_PER_SHEET
- total_pages = num_pages + blanks_needed
- all_pages = list(pdf_reader.pages) # Create a copy
- for _ in range(blanks_needed):
- all_pages.append(self.create_blank_page(template_page))
- for i in range(0, total_pages, self.PAGES_PER_SHEET):
- page_indices = [i + 3, i, i + 1, i + 2]
- for idx in page_indices:
- if idx < total_pages:
- pdf_writer.add_page(all_pages[idx])
- with open(output_path, "wb") as output_file:
- pdf_writer.write(output_file)
- self.status_var.set(f"Success! Imposed PDF saved to: {output_path}")
- messagebox.showinfo("Success", "PDF imposition completed successfully!")
- except FileNotFoundError:
- self.status_var.set("Error: Input file not found.")
- messagebox.showerror("Error", "Input file not found.")
- except Exception as e:
- error_msg = f"Error: {str(e)}\n\nFull traceback:\n{traceback.format_exc()}"
- self.status_var.set(error_msg)
- messagebox.showerror("Error", error_msg)
- if __name__ == "__main__":
- root = tk.Tk()
- app = PDFImposerApp(root)
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement