Skip to content

Instantly share code, notes, and snippets.

@cheadrian
Created February 14, 2023 08:58
Show Gist options
  • Save cheadrian/f8f30730b8c7c3224ecf0e9646ade63d to your computer and use it in GitHub Desktop.
Save cheadrian/f8f30730b8c7c3224ecf0e9646ade63d to your computer and use it in GitHub Desktop.
PDF page fill ration counter, drag and drop, GUI Tkinter
import fitz
import tkinter as tk
from tkinter import ttk
from tkinter import *
from tkinter import filedialog
from tkinterdnd2 import DND_FILES, TkinterDnD
def on_drop(file_path):
# Split multiple files:
paths = file_path.split(' ')
# Process the dropped file
results_text.delete(1.0, tk.END)
for p in paths:
results_text.insert(tk.END, p+"\n")
estimate_pdf_fill(p)
def select_pdf_button():
# Open a file dialog to select the PDF document
file_path = filedialog.askopenfilename(
title="Select PDF document", filetypes=(("PDF files", "*.pdf"), ("all files", "*.*"))
)
results_text.delete(1.0, tk.END)
results_text.insert(tk.END, file_path+"\n")
estimate_pdf_fill(file_path)
def estimate_pdf_fill(file_path):
# Check if PDF
if not file_path.endswith(".pdf"):
results_text.insert(tk.END, f"Not PDF.\n")
return
# Open the PDF file
pdf_doc = fitz.open(file_path)
# Initialize the number of blank and colored pixels
blank_pixels = 0
colored_pixels = 0
zoom_x = 2 # horizontal zoom
zoom_y = 2 # vertical zoom
mat = fitz.Matrix(zoom_x, zoom_y) # zoom factor 2 in each dimension
#results_text.delete(1.0, tk.END)
total_white_perc, total_color_perc = 0, 0
page_count = pdf_doc.page_count
for page_num in range(page_count):
page = pdf_doc.load_page(page_num)
pix = page.get_pixmap(matrix=mat)
color_count = pix.color_count(colors=True)
total_pixels = sum(color_count.values())
white_pixels = color_count.get(b'\xff\xff\xff') or 0
color_pixels = total_pixels - white_pixels
white_perc = white_pixels / total_pixels * 100
color_perc = color_pixels / total_pixels * 100
total_white_perc += white_perc
total_color_perc += color_perc
results_text.insert(tk.END, f"Page {page_num + 1 } - Fill: {color_perc:.2f}%\n")
avg_white_perc = total_white_perc / page_count
avg_color_perc = total_color_perc / page_count
results_text.insert(tk.END, f"Average for {page_count} page(s) - Fill: {avg_color_perc:.2f}%\n")
pdf_doc.close()
root = TkinterDnD.Tk()
root.title("PDF Fill Percentage")
root.columnconfigure(0, weight=1)
root.rowconfigure(1, weight=1)
ttk.Button(root, text="Open file", command=select_pdf_button).grid(column=0, row=0, sticky=(tk.N, tk.W))
results_text = tk.Text(root)#, height=20, width=90)
results_text.grid(column=0, row=1, sticky=(tk.N, tk.W, tk.E, tk.S))
results_text.insert(tk.END, "Drag and drop PDF files here.")
results_text.drop_target_register(DND_FILES)
results_text.dnd_bind('<<Drop>>', lambda e: on_drop(e.data))
for child in root.winfo_children(): child.grid_configure(padx=5, pady=5)
root.mainloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment