-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
755 lines (631 loc) · 28.1 KB
/
Copy pathmain.py
File metadata and controls
755 lines (631 loc) · 28.1 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
import os
import sys
import time
import traceback
import threading
import argparse
import logging
from pathlib import Path
from typing import Optional
import requests
import jwt
import hashlib
from dotenv import load_dotenv
# 加载.env文件
load_dotenv()
# 配置日志
def setup_logger(level=logging.INFO):
"""配置日志记录器"""
logger = logging.getLogger('URL2PDF')
logger.setLevel(level)
# 避免重复添加handler
if logger.handlers:
return logger
# 创建格式器
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
# 控制台处理器
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(level)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
# 文件处理器(可选,保存到日志文件)
log_file = Path("url2pdf.log")
file_handler = logging.FileHandler(log_file, encoding='utf-8')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
return logger
# 初始化logger
logger = setup_logger()
# GUI相关导入(仅在GUI模式时导入)
try:
import tkinter as tk
from tkinter import ttk, scrolledtext, filedialog, messagebox
GUI_AVAILABLE = True
except ImportError:
GUI_AVAILABLE = False
def convert_url_to_pdf(url: str, output_dir: str, public_key: str, secret_key: str,
page_orientation: str = "portrait", page_size: str = "A4",
single_page: bool = False) -> tuple[Optional[str], Optional[str]]:
"""
使用 iLovePDF API 将 URL 转换为 PDF(同步版本)
Args:
url: 要转换的URL地址
output_dir: 输出目录
public_key: iLovePDF API 公钥
secret_key: iLovePDF API 私钥
page_orientation: 页面方向 ("portrait" 或 "landscape")
page_size: 页面大小 ("A4", "A3", "Letter", "Fit", "Auto")
single_page: 是否启用长图片PDF模式(单页输出,适合长网页)
Returns:
tuple: (PDF文件路径, 错误信息) 如果成功返回(路径, None),失败返回(None, 错误信息)
"""
logger.info(f"开始转换URL: {url}")
logger.debug(f"输出目录: {output_dir}, 页面设置: {page_orientation}, {page_size}, 长图片模式: {single_page}")
try:
api_base = "https://api.ilovepdf.com/v1"
# 1. 获取认证token
logger.info("步骤 1/6: 获取API认证token...")
try:
logger.debug(f"请求认证端点: {api_base}/auth")
auth_response = requests.post(
f"{api_base}/auth",
json={"public_key": public_key},
timeout=30,
)
logger.debug(f"认证响应状态码: {auth_response.status_code}")
if auth_response.status_code == 200:
auth_data = auth_response.json()
token = auth_data["token"]
logger.info("✓ 成功通过/auth端点获取token")
if "remaining_credits" in auth_data:
logger.info(f" 剩余额度: {auth_data['remaining_credits']}")
else:
logger.warning(f"认证端点返回 {auth_response.status_code},尝试自签名方式")
raise ValueError("Auth endpoint failed")
except Exception as e:
# 回退到自签名方式
logger.info("使用JWT自签名方式生成token...")
now = int(time.time())
payload = {
"iss": public_key,
"exp": now + 7200,
"nbf": now,
"iat": now,
}
token = jwt.encode(payload, secret_key, algorithm="HS256")
logger.info("✓ 成功生成JWT token")
headers = {"Authorization": f"Bearer {token}"}
logger.debug(f"Token前8位: {token[:8]}...")
# 2. 开始任务
logger.info("步骤 2/6: 启动htmlpdf任务...")
region = os.getenv("ILOVEPDF_REGION", "eu")
start_url = f"{api_base}/start/htmlpdf"
logger.debug(f"任务启动URL: {start_url}, 区域: {region}")
start_response = requests.get(
start_url,
headers=headers,
timeout=30,
)
logger.debug(f"启动任务响应状态码: {start_response.status_code}")
if start_response.status_code == 404 and region != "eu":
logger.debug("尝试不带区域参数...")
start_response = requests.get(
start_url,
headers=headers,
timeout=30,
)
if start_response.status_code == 404:
start_url_with_region = f"{api_base}/start/htmlpdf/{region}"
logger.debug(f"尝试带区域参数: {start_url_with_region}")
start_response = requests.get(
start_url_with_region,
headers=headers,
timeout=30,
)
logger.debug(f"带区域参数响应状态码: {start_response.status_code}")
if start_response.status_code == 401:
error_detail = start_response.text
logger.error(f"认证失败 (401): {error_detail}")
return None, f"认证失败 (401): {error_detail}"
if start_response.status_code == 404:
logger.error("htmlpdf工具不可用 (404)")
return None, "htmlpdf工具不可用 (404),请检查您的API计划是否包含此功能"
start_response.raise_for_status()
start_data = start_response.json()
server = start_data["server"]
task = start_data["task"]
logger.info(f"✓ 任务已启动 - 服务器: {server}, 任务ID: {task}")
# 3. 上传URL
logger.info("步骤 3/6: 上传URL到服务器...")
upload_url = f"https://{server}/v1/upload"
upload_data = {
"task": task,
"cloud_file": url,
}
logger.debug(f"上传URL: {upload_url}")
logger.debug(f"上传数据: task={task}, cloud_file={url}")
upload_response = requests.post(
upload_url,
headers=headers,
json=upload_data,
timeout=60,
)
logger.debug(f"上传响应状态码: {upload_response.status_code}")
upload_response.raise_for_status()
upload_result = upload_response.json()
server_filename = upload_result["server_filename"]
logger.info(f"✓ URL已上传 - 服务器文件名: {server_filename}")
# 4. 处理URL转PDF
logger.info("步骤 4/6: 处理URL转PDF...")
process_url = f"https://{server}/v1/process"
process_payload = {
"task": task,
"tool": "htmlpdf",
"files": [
{
"server_filename": server_filename,
"filename": "webpage.pdf"
}
],
"page_orientation": page_orientation,
"page_size": page_size,
"page_margin": 0,
"view_width": 1980,
"single_page": single_page,
}
if single_page:
logger.info("启用长图片PDF模式(单页输出)")
logger.debug(f"处理URL: {process_url}")
logger.debug(f"处理参数: {process_payload}")
process_response = requests.post(
process_url,
headers=headers,
json=process_payload,
timeout=300,
)
logger.debug(f"处理响应状态码: {process_response.status_code}")
if process_response.status_code != 200:
error_detail = process_response.text
logger.error(f"处理失败 ({process_response.status_code}): {error_detail}")
return None, f"处理失败 ({process_response.status_code}): {error_detail}"
process_response.raise_for_status()
logger.info("✓ PDF处理完成")
# 5. 下载PDF
logger.info("步骤 5/6: 下载PDF文件...")
download_url = f"https://{server}/v1/download/{task}"
logger.debug(f"下载URL: {download_url}")
download_response = requests.get(download_url, headers=headers, timeout=60)
logger.debug(f"下载响应状态码: {download_response.status_code}, 大小: {len(download_response.content)} bytes")
download_response.raise_for_status()
logger.info(f"✓ PDF下载完成,大小: {len(download_response.content)} bytes")
# 6. 保存PDF
logger.info("步骤 6/6: 保存PDF文件...")
pdf_content = download_response.content
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
logger.debug(f"输出目录: {output_path}")
# 使用URL的hash和域名作为文件名
url_hash = hashlib.md5(url.encode()).hexdigest()[:8]
try:
from urllib.parse import urlparse
domain = urlparse(url).netloc.replace(".", "_")
filename = f"{domain}_{url_hash}.pdf"
except Exception as e:
logger.warning(f"解析域名失败,使用默认文件名: {e}")
filename = f"webpage_{url_hash}_{int(time.time())}.pdf"
pdf_path = output_path / filename
logger.debug(f"保存路径: {pdf_path}")
with open(pdf_path, "wb") as f:
f.write(pdf_content)
logger.info(f"✓ PDF已保存: {pdf_path}")
logger.info(f"转换完成: {url} -> {pdf_path}")
return str(pdf_path), None
except requests.exceptions.Timeout as e:
error_msg = f"请求超时: {str(e)}"
logger.error(error_msg)
logger.debug(traceback.format_exc())
return None, error_msg
except requests.exceptions.RequestException as e:
error_msg = f"网络请求错误: {str(e)}"
logger.error(error_msg)
logger.debug(traceback.format_exc())
return None, error_msg
except Exception as e:
error_msg = f"{type(e).__name__}: {str(e)}"
logger.error(f"转换失败: {error_msg}")
logger.debug(traceback.format_exc())
return None, error_msg
class URL2PDFApp:
def __init__(self, root):
self.root = root
self.root.title("URL转PDF工具 - 批量转换")
self.root.geometry("900x700")
# 从.env文件读取API密钥
env_public_key = os.getenv("ILOVEPDF_PUBLIC_KEY", "")
env_secret_key = os.getenv("ILOVEPDF_SECRET_KEY", "")
# 变量
self.output_dir = tk.StringVar(value=str(Path.home() / "Downloads" / "URL2PDF"))
self.public_key = tk.StringVar(value=env_public_key)
self.secret_key = tk.StringVar(value=env_secret_key)
self.page_orientation = tk.StringVar(value="portrait")
self.page_size = tk.StringVar(value="A4")
self.single_page = tk.BooleanVar(value=False)
self.is_processing = False
# 如果从.env读取到了密钥,在GUI中显示提示
if env_public_key and env_secret_key:
self.api_from_env = True
else:
self.api_from_env = 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)
row = 0
# API配置区域
api_title = "API配置(已从.env文件加载)" if self.api_from_env else "API配置(未找到.env文件,请手动输入)"
api_frame = ttk.LabelFrame(main_frame, text=api_title, padding="10")
api_frame.grid(row=row, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=5)
api_frame.columnconfigure(1, weight=1)
row += 1
ttk.Label(api_frame, text="Public Key:").grid(row=0, column=0, sticky=tk.W, padx=5, pady=5)
public_key_entry = ttk.Entry(api_frame, textvariable=self.public_key, width=50, show="*")
public_key_entry.grid(row=0, column=1, sticky=(tk.W, tk.E), padx=5, pady=5)
ttk.Label(api_frame, text="Secret Key:").grid(row=1, column=0, sticky=tk.W, padx=5, pady=5)
secret_key_entry = ttk.Entry(api_frame, textvariable=self.secret_key, width=50, show="*")
secret_key_entry.grid(row=1, column=1, sticky=(tk.W, tk.E), padx=5, pady=5)
# PDF设置区域
settings_frame = ttk.LabelFrame(main_frame, text="PDF设置", padding="10")
settings_frame.grid(row=row, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=5)
row += 1
ttk.Label(settings_frame, text="页面方向:").grid(row=0, column=0, sticky=tk.W, padx=5, pady=5)
orientation_combo = ttk.Combobox(settings_frame, textvariable=self.page_orientation,
values=["portrait", "landscape"], state="readonly", width=20)
orientation_combo.grid(row=0, column=1, sticky=tk.W, padx=5, pady=5)
ttk.Label(settings_frame, text="页面大小:").grid(row=0, column=2, sticky=tk.W, padx=5, pady=5)
size_combo = ttk.Combobox(settings_frame, textvariable=self.page_size,
values=["A4", "A3", "Letter", "Fit", "Auto"], state="readonly", width=20)
size_combo.grid(row=0, column=3, sticky=tk.W, padx=5, pady=5)
# 长图片PDF选项
single_page_check = ttk.Checkbutton(
settings_frame,
text="启用长图片PDF(单页输出,适合长网页)",
variable=self.single_page
)
single_page_check.grid(row=1, column=0, columnspan=4, sticky=tk.W, padx=5, pady=5)
# 输出目录选择
output_frame = ttk.Frame(main_frame)
output_frame.grid(row=row, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=5)
output_frame.columnconfigure(1, weight=1)
row += 1
ttk.Label(output_frame, text="输出目录:").grid(row=0, column=0, sticky=tk.W, padx=5)
ttk.Entry(output_frame, textvariable=self.output_dir, width=50).grid(row=0, column=1, sticky=(tk.W, tk.E), padx=5)
ttk.Button(output_frame, text="浏览", command=self.browse_output_dir).grid(row=0, column=2, padx=5)
# URL输入区域
url_frame = ttk.LabelFrame(main_frame, text="URL列表(每行一个URL)", padding="10")
url_frame.grid(row=row, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S), pady=5)
url_frame.columnconfigure(0, weight=1)
url_frame.rowconfigure(0, weight=1)
main_frame.rowconfigure(row, weight=1)
row += 1
self.url_text = scrolledtext.ScrolledText(url_frame, height=15, wrap=tk.WORD)
self.url_text.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
# 按钮区域
button_frame = ttk.Frame(main_frame)
button_frame.grid(row=row, column=0, columnspan=2, pady=10)
row += 1
self.convert_button = ttk.Button(button_frame, text="开始转换", command=self.start_conversion)
self.convert_button.pack(side=tk.LEFT, padx=5)
ttk.Button(button_frame, text="清空URL", command=self.clear_urls).pack(side=tk.LEFT, padx=5)
# 进度条
self.progress_var = tk.DoubleVar()
self.progress_bar = ttk.Progressbar(main_frame, variable=self.progress_var, maximum=100, length=400)
self.progress_bar.grid(row=row, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=5)
row += 1
# 状态文本
self.status_text = scrolledtext.ScrolledText(main_frame, height=8, wrap=tk.WORD, state=tk.DISABLED)
self.status_text.grid(row=row, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S), pady=5)
main_frame.rowconfigure(row, weight=1)
def browse_output_dir(self):
directory = filedialog.askdirectory(initialdir=self.output_dir.get())
if directory:
self.output_dir.set(directory)
def clear_urls(self):
self.url_text.delete(1.0, tk.END)
def log_status(self, message: str, level: str = "INFO"):
"""在状态文本框中添加日志"""
self.status_text.config(state=tk.NORMAL)
timestamp = time.strftime("%H:%M:%S")
# 根据级别添加前缀
prefix = {
"DEBUG": "[DEBUG]",
"INFO": "[INFO]",
"WARNING": "[WARN]",
"ERROR": "[ERROR]"
}.get(level, "[INFO]")
self.status_text.insert(tk.END, f"[{timestamp}] {prefix} {message}\n")
self.status_text.see(tk.END)
self.status_text.config(state=tk.DISABLED)
self.root.update_idletasks()
# 同时输出到logger
log_func = getattr(logger, level.lower(), logger.info)
log_func(message)
def start_conversion(self):
"""开始转换(在后台线程中运行)"""
if self.is_processing:
messagebox.showwarning("警告", "转换正在进行中,请稍候...")
return
# 验证API密钥
if not self.public_key.get() or not self.secret_key.get():
messagebox.showerror("错误", "请配置iLovePDF API的Public Key和Secret Key")
return
# 获取URL列表
url_content = self.url_text.get(1.0, tk.END).strip()
if not url_content:
messagebox.showwarning("警告", "请输入至少一个URL")
return
urls = [url.strip() for url in url_content.split("\n") if url.strip()]
if not urls:
messagebox.showwarning("警告", "请输入有效的URL")
return
# 验证输出目录
output_dir = self.output_dir.get().strip()
if not output_dir:
messagebox.showerror("错误", "请选择输出目录")
return
# 在后台线程中运行转换
self.is_processing = True
self.convert_button.config(state=tk.DISABLED, text="转换中...")
self.status_text.config(state=tk.NORMAL)
self.status_text.delete(1.0, tk.END)
self.status_text.config(state=tk.DISABLED)
self.progress_var.set(0)
thread = threading.Thread(
target=self.convert_urls,
args=(urls, output_dir),
daemon=True
)
thread.start()
def convert_urls(self, urls: list[str], output_dir: str):
"""批量转换URL为PDF"""
total = len(urls)
success_count = 0
fail_count = 0
logger.info("=" * 60)
logger.info("启动GUI模式批量转换")
logger.info(f"URL数量: {total}, 输出目录: {output_dir}")
logger.info("=" * 60)
self.log_status(f"开始转换 {total} 个URL...", "INFO")
self.log_status(f"输出目录: {output_dir}", "INFO")
single_page_text = "启用" if self.single_page.get() else "禁用"
self.log_status(f"PDF设置: {self.page_orientation.get()}, {self.page_size.get()}, 长图片模式: {single_page_text}", "INFO")
for idx, url in enumerate(urls, 1):
if not self.is_processing: # 允许取消(虽然当前UI没有取消按钮)
break
self.log_status(f"[{idx}/{total}] 开始处理URL: {url}", "INFO")
pdf_path, error = convert_url_to_pdf(
url=url,
output_dir=output_dir,
public_key=self.public_key.get(),
secret_key=self.secret_key.get(),
page_orientation=self.page_orientation.get(),
page_size=self.page_size.get(),
single_page=self.single_page.get()
)
if pdf_path:
self.log_status(f"[{idx}/{total}] ✓ 转换成功: {pdf_path}", "INFO")
success_count += 1
else:
self.log_status(f"[{idx}/{total}] ✗ 转换失败: {error}", "ERROR")
fail_count += 1
# 更新进度
progress = (idx / total) * 100
self.progress_var.set(progress)
self.log_status(f"[{idx}/{total}] 进度: {progress:.1f}%", "INFO")
# 完成
self.is_processing = False
self.root.after(0, lambda: self.convert_button.config(state=tk.NORMAL, text="开始转换"))
self.progress_var.set(100)
logger.info("=" * 60)
logger.info(f"批量转换完成!成功: {success_count}, 失败: {fail_count}")
logger.info(f"文件保存在: {output_dir}")
logger.info("=" * 60)
summary = f"\n转换完成!成功: {success_count}, 失败: {fail_count}"
self.log_status(summary, "INFO")
if success_count > 0:
messagebox.showinfo("完成", f"转换完成!\n成功: {success_count}\n失败: {fail_count}\n\n文件保存在: {output_dir}")
def run_cli_mode(input_file: str, output_dir: str, page_orientation: str = "portrait",
page_size: str = "A4", single_page: bool = False):
"""
命令行模式:批量转换URL文件中的URL为PDF
Args:
input_file: 包含URL列表的文件路径(每行一个URL)
output_dir: 输出目录
page_orientation: 页面方向
page_size: 页面大小
single_page: 是否启用长图片PDF模式
"""
logger.info("=" * 60)
logger.info("启动命令行模式")
logger.info("=" * 60)
# 从.env文件读取API密钥
public_key = os.getenv("ILOVEPDF_PUBLIC_KEY", "")
secret_key = os.getenv("ILOVEPDF_SECRET_KEY", "")
if not public_key or not secret_key:
logger.error("未找到iLovePDF API密钥!")
logger.error("请确保.env文件中包含以下配置:")
logger.error(" ILOVEPDF_PUBLIC_KEY=your_public_key")
logger.error(" ILOVEPDF_SECRET_KEY=your_secret_key")
print("错误: 未找到iLovePDF API密钥!")
print("请确保.env文件中包含以下配置:")
print(" ILOVEPDF_PUBLIC_KEY=your_public_key")
print(" ILOVEPDF_SECRET_KEY=your_secret_key")
sys.exit(1)
logger.info(f"API密钥已加载 (Public Key前8位: {public_key[:8]}...)")
# 读取URL文件
input_path = Path(input_file)
if not input_path.exists():
logger.error(f"输入文件不存在: {input_file}")
print(f"错误: 输入文件不存在: {input_file}")
sys.exit(1)
logger.info(f"读取URL文件: {input_file}")
try:
with open(input_path, 'r', encoding='utf-8') as f:
urls = [line.strip() for line in f if line.strip()]
except Exception as e:
logger.error(f"无法读取输入文件: {e}")
print(f"错误: 无法读取输入文件: {e}")
sys.exit(1)
if not urls:
logger.error("输入文件中没有有效的URL")
print("错误: 输入文件中没有有效的URL")
sys.exit(1)
logger.info(f"找到 {len(urls)} 个URL")
# 验证输出目录
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
logger.info(f"输出目录: {output_dir}")
logger.info(f"PDF设置: 方向={page_orientation}, 大小={page_size}, 长图片模式={single_page}")
print(f"开始转换 {len(urls)} 个URL...")
print(f"输出目录: {output_dir}")
print(f"PDF设置: {page_orientation}, {page_size}, 长图片模式: {'启用' if single_page else '禁用'}")
print("-" * 60)
success_count = 0
fail_count = 0
for idx, url in enumerate(urls, 1):
logger.info("")
logger.info(f"[{idx}/{len(urls)}] 开始处理URL: {url}")
print(f"\n[{idx}/{len(urls)}] 正在转换: {url}")
pdf_path, error = convert_url_to_pdf(
url=url,
output_dir=str(output_path),
public_key=public_key,
secret_key=secret_key,
page_orientation=page_orientation,
page_size=page_size,
single_page=single_page
)
if pdf_path:
logger.info(f"[{idx}/{len(urls)}] ✓ 转换成功: {pdf_path}")
print(f" ✓ 成功: {pdf_path}")
success_count += 1
else:
logger.error(f"[{idx}/{len(urls)}] ✗ 转换失败: {error}")
print(f" ✗ 失败: {error}")
fail_count += 1
# 更新进度
progress = (idx / len(urls)) * 100
logger.info(f"[{idx}/{len(urls)}] 进度: {progress:.1f}%")
print(f" 进度: {progress:.1f}%")
logger.info("")
logger.info("=" * 60)
logger.info(f"批量转换完成!成功: {success_count}, 失败: {fail_count}")
logger.info(f"文件保存在: {output_dir}")
logger.info("=" * 60)
print("\n" + "-" * 60)
print(f"转换完成!")
print(f"成功: {success_count}")
print(f"失败: {fail_count}")
print(f"文件保存在: {output_dir}")
def main():
parser = argparse.ArgumentParser(
description="URL转PDF工具 - 支持GUI和命令行模式",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
示例:
# GUI模式(默认)
python main.py
# 命令行模式
python main.py --cli --input url.txt --output ./pdfs
# 命令行模式(自定义PDF设置)
python main.py --cli --input url.txt --output ./pdfs --orientation landscape --size A3
# 命令行模式(启用长图片PDF)
python main.py --cli --input url.txt --output ./pdfs --single-page
"""
)
parser.add_argument(
"--cli",
action="store_true",
help="使用命令行模式(无GUI)"
)
parser.add_argument(
"--input",
type=str,
default="url.txt",
help="输入文件路径(包含URL列表,每行一个URL),默认: url.txt"
)
parser.add_argument(
"--output",
type=str,
help="输出目录路径(必需在命令行模式下)"
)
parser.add_argument(
"--orientation",
type=str,
choices=["portrait", "landscape"],
default="portrait",
help="页面方向,默认: portrait"
)
parser.add_argument(
"--size",
type=str,
choices=["A4", "A3", "Letter", "Fit", "Auto"],
default="A4",
help="页面大小,默认: A4"
)
parser.add_argument(
"--single-page",
action="store_true",
help="启用长图片PDF模式(单页输出,适合长网页)"
)
parser.add_argument(
"--verbose",
"-v",
action="store_true",
help="显示详细日志(DEBUG级别)"
)
args = parser.parse_args()
# 根据verbose参数设置日志级别
if args.verbose:
logger.setLevel(logging.DEBUG)
for handler in logger.handlers:
handler.setLevel(logging.DEBUG)
logger.debug("启用详细日志模式(DEBUG级别)")
else:
logger.setLevel(logging.INFO)
for handler in logger.handlers:
if isinstance(handler, logging.FileHandler):
handler.setLevel(logging.DEBUG) # 文件日志保持DEBUG级别
else:
handler.setLevel(logging.INFO) # 控制台日志INFO级别
# 命令行模式
if args.cli:
if not args.output:
print("错误: 命令行模式下必须指定 --output 参数")
parser.print_help()
sys.exit(1)
run_cli_mode(
input_file=args.input,
output_dir=args.output,
page_orientation=args.orientation,
page_size=args.size,
single_page=args.single_page
)
else:
# GUI模式
if not GUI_AVAILABLE:
print("错误: GUI模式需要tkinter,但当前环境不支持")
print("请使用命令行模式: python main.py --cli --input url.txt --output ./pdfs")
sys.exit(1)
root = tk.Tk()
app = URL2PDFApp(root)
root.mainloop()
if __name__ == "__main__":
main()