-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimage2PDF.py
More file actions
111 lines (85 loc) · 2.72 KB
/
image2PDF.py
File metadata and controls
111 lines (85 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import tkinter as tk
from tkinter import filedialog, messagebox, simpledialog
from PIL import Image
import img2pdf
from pathlib import Path
def select_images():
"""Open file dialog to select one or more image files"""
root = tk.Tk()
root.withdraw() # Hide the main window
file_paths = filedialog.askopenfilenames(
title="Select Image Files",
filetypes=[
("Image files", "*.jpg *.jpeg *.png"),
("JPEG files", "*.jpg *.jpeg"),
("PNG files", "*.png"),
("All files", "*.*")
]
)
return list(file_paths) if file_paths else None
def get_dpi():
"""Prompt user for DPI value"""
root = tk.Tk()
root.withdraw()
dpi = simpledialog.askinteger(
"DPI Input",
"Enter the DPI at which the images were scanned:",
initialvalue=300,
minvalue=72,
maxvalue=2400
)
return dpi
def save_pdf():
"""Open save dialog for PDF output"""
root = tk.Tk()
root.withdraw()
output_path = filedialog.asksaveasfilename(
title="Save PDF As",
defaultextension=".pdf",
filetypes=[("PDF files", "*.pdf"), ("All files", "*.*")]
)
return output_path if output_path else None
def convert_images_to_pdf(image_paths, dpi, output_path):
"""Convert images to PDF-A format"""
try:
# Convert images to PDF with specified DPI
# img2pdf will use the DPI metadata from images or the specified value
with open(output_path, "wb") as f:
# Pass DPI as a tuple for x and y resolution
pdf_bytes = img2pdf.convert(
image_paths,
dpi=(dpi, dpi)
)
f.write(pdf_bytes)
return True
except Exception as e:
messagebox.showerror("Error", f"Failed to create PDF:\n{str(e)}")
return False
def main():
"""Main application flow"""
# Step 1: Select images
image_paths = select_images()
if not image_paths:
messagebox.showinfo("Cancelled", "No images selected. Exiting.")
return
# Step 2: Get DPI
dpi = get_dpi()
if not dpi:
messagebox.showinfo("Cancelled", "No DPI provided. Exiting.")
return
# Step 3: Select output location
output_path = save_pdf()
if not output_path:
messagebox.showinfo("Cancelled", "No output file selected. Exiting.")
return
# Convert images to PDF
success = convert_images_to_pdf(image_paths, dpi, output_path)
if success:
messagebox.showinfo(
"Success",
f"PDF created successfully!\n\n"
f"Images processed: {len(image_paths)}\n"
f"Output: {output_path}"
)
if __name__ == "__main__":
main()