-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhtml2pdf_gui.py
More file actions
172 lines (129 loc) · 6.96 KB
/
html2pdf_gui.py
File metadata and controls
172 lines (129 loc) · 6.96 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
#!/usr/bin/env python3
"""
HTML to PDF Converter - GUI Version
A simple graphical interface for converting HTML files to PDF using WeasyPrint.
"""
import tkinter as tk
from tkinter import filedialog, scrolledtext, ttk
from pathlib import Path
import threading
from weasyprint import HTML
class HTML2PDFConverter:
def __init__(self, root):
self.root = root
self.root.title("HTML to PDF Converter")
self.root.geometry("700x600")
self.root.resizable(True, True)
self.input_dir = tk.StringVar()
self.output_dir = tk.StringVar(value="output")
self.is_converting = False
self.setup_ui()
def setup_ui(self):
main_frame = ttk.Frame(self.root, padding="10")
main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
self.root.columnconfigure(0, weight=1)
self.root.rowconfigure(0, weight=1)
main_frame.columnconfigure(1, weight=1)
ttk.Label(main_frame, text="HTML to PDF Converter",
font=('Arial', 16, 'bold')).grid(row=0, column=0, columnspan=3, pady=(0, 20))
ttk.Label(main_frame, text="Input Directory:").grid(row=1, column=0, sticky=tk.W, pady=5)
ttk.Entry(main_frame, textvariable=self.input_dir, width=50).grid(row=1, column=1, sticky=(tk.W, tk.E), pady=5, padx=5)
ttk.Button(main_frame, text="Browse...", command=self.browse_input).grid(row=1, column=2, pady=5)
ttk.Label(main_frame, text="Output Directory:").grid(row=2, column=0, sticky=tk.W, pady=5)
ttk.Entry(main_frame, textvariable=self.output_dir, width=50).grid(row=2, column=1, sticky=(tk.W, tk.E), pady=5, padx=5)
ttk.Button(main_frame, text="Browse...", command=self.browse_output).grid(row=2, column=2, pady=5)
self.convert_btn = ttk.Button(main_frame, text="Convert to PDF", command=self.start_conversion)
self.convert_btn.grid(row=3, column=0, columnspan=3, pady=20)
ttk.Label(main_frame, text="Status:", font=('Arial', 10, 'bold')).grid(row=4, column=0, sticky=tk.W, pady=(10, 5))
self.status_text = scrolledtext.ScrolledText(main_frame, height=20, width=80, wrap=tk.WORD)
self.status_text.grid(row=5, column=0, columnspan=3, sticky=(tk.W, tk.E, tk.N, tk.S), pady=5)
main_frame.rowconfigure(5, weight=1)
self.status_text.tag_configure("success", foreground="green")
self.status_text.tag_configure("error", foreground="red")
self.status_text.tag_configure("info", foreground="blue")
self.status_text.tag_configure("summary", foreground="purple", font=('Arial', 10, 'bold'))
self.log_message("Welcome! Select an input directory containing HTML files to get started.", "info")
def browse_input(self):
directory = filedialog.askdirectory(title="Select Input Directory")
if directory:
self.input_dir.set(directory)
self.log_message(f"Input directory selected: {directory}", "info")
def browse_output(self):
directory = filedialog.askdirectory(title="Select Output Directory")
if directory:
self.output_dir.set(directory)
self.log_message(f"Output directory selected: {directory}", "info")
def log_message(self, message, tag=""):
self.status_text.insert(tk.END, message + "\n", tag)
self.status_text.see(tk.END)
self.root.update_idletasks()
def log_message_safe(self, message, tag=""):
self.root.after(0, lambda: self.log_message(message, tag))
def update_button_safe(self, state, text):
self.root.after(0, lambda: self.convert_btn.config(state=state, text=text))
def convert_html_to_pdf(self, html_file, output_dir):
try:
pdf_filename = html_file.stem + '.pdf'
pdf_path = output_dir / pdf_filename
self.log_message_safe(f"Converting: {html_file.name} → {pdf_filename}")
HTML(filename=str(html_file)).write_pdf(str(pdf_path))
self.log_message_safe(f" ✓ Success: {pdf_path}", "success")
return True
except Exception as e:
self.log_message_safe(f" ✗ Error converting {html_file.name}: {str(e)}", "error")
return False
def run_conversion(self):
input_path = Path(self.input_dir.get())
output_path = Path(self.output_dir.get())
if not input_path.exists():
self.log_message_safe(f"Error: Input directory '{self.input_dir.get()}' does not exist.", "error")
self.is_converting = False
self.update_button_safe(tk.NORMAL, "Convert to PDF")
return
if not input_path.is_dir():
self.log_message_safe(f"Error: '{self.input_dir.get()}' is not a directory.", "error")
self.is_converting = False
self.update_button_safe(tk.NORMAL, "Convert to PDF")
return
output_path.mkdir(parents=True, exist_ok=True)
html_files = list(input_path.glob('*.html')) + list(input_path.glob('*.htm'))
if not html_files:
self.log_message_safe(f"No HTML files found in '{self.input_dir.get()}'", "error")
self.is_converting = False
self.update_button_safe(tk.NORMAL, "Convert to PDF")
return
self.log_message_safe(f"\n{'='*60}", "info")
self.log_message_safe(f"Found {len(html_files)} HTML file(s) in '{self.input_dir.get()}'", "info")
self.log_message_safe(f"Output directory: '{self.output_dir.get()}'", "info")
self.log_message_safe(f"{'='*60}\n", "info")
successful = 0
failed = 0
for html_file in sorted(html_files):
if self.convert_html_to_pdf(html_file, output_path):
successful += 1
else:
failed += 1
self.log_message_safe(f"\n{'='*60}", "summary")
self.log_message_safe(f"Conversion Complete!", "summary")
self.log_message_safe(f" Successful: {successful}", "summary")
self.log_message_safe(f" Failed: {failed}", "summary")
self.log_message_safe(f" Total: {len(html_files)}", "summary")
self.log_message_safe(f"{'='*60}\n", "summary")
self.is_converting = False
self.update_button_safe(tk.NORMAL, "Convert to PDF")
def start_conversion(self):
if self.is_converting:
return
if not self.input_dir.get():
self.log_message("Please select an input directory first.", "error")
return
self.is_converting = True
self.convert_btn.config(state=tk.DISABLED, text="Converting...")
thread = threading.Thread(target=self.run_conversion, daemon=True)
thread.start()
def main():
root = tk.Tk()
app = HTML2PDFConverter(root)
root.mainloop()
if __name__ == '__main__':
main()