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
|
from PIL import Image
import os
import sys
import glob
from PyPDF2 import PdfMerger
from argparse import ArgumentParser
def compressed_and_merge(folder_path, book_name, scaling_factor, resolution):
output_file = os.path.join(folder_path, book_name + ".pdf")
# Get all PNG files in the directory
png_files = glob.glob(os.path.join(folder_path, "*.png"))
# Create a new PDF file
merger = PdfMerger()
png_files_total = len(png_files)
for i, png_file in enumerate(png_files):
show_progress_bar("Step 1:PNG-->PDF", i+1, png_files_total)
pdf_file = convert_png_to_pdf(png_file, scaling_factor, resolution)
merger.append(pdf_file)
print("\nStep 2: 正在合并PDF文件")
merger.write(output_file)
print("合并完成: " + output_file)
merger.close()
remove_pdf_files(folder_path, output_file)
def convert_png_to_pdf(png_file, scaling_factor, resolution):
image = Image.open(png_file)
image = image.convert('RGB')
width, height = image.size
width = int(width * scaling_factor)
height = int(height * scaling_factor)
image = image.resize(
(width, height), resample=Image.LANCZOS)
pdf_file = png_file.replace(".png", ".pdf")
image.save(pdf_file, "PDF", resolution=resolution,
options={"optimize": True})
return pdf_file
def remove_pdf_files(folder_path, except_file):
label = "Step 3: 删除临时的PDF"
pdf_files = glob.glob(os.path.join(folder_path, "*.pdf"))
total = len(pdf_files)
if except_file in pdf_files:
total -= 1
for i, pdf_file in enumerate(pdf_files):
show_progress_bar(label, i, total)
if pdf_file != except_file:
os.remove(pdf_file)
print("\n删除完成")
def show_progress_bar(label, current, total, bar_length=20):
percent = float(current) * 100 / total
arrow = '-' * int(percent / 100 * bar_length - 1) + '>'
spaces = ' ' * (bar_length - len(arrow))
sys.stdout.write("\r{0}: [{1}] {2}%".format(
label, arrow + spaces, int(percent)))
sys.stdout.flush()
def main():
parser = ArgumentParser(
description="Compress and merge PNG images into a PDF file")
parser.add_argument('-f', "--folder_path",
help="Path to the folder containing PNG images", required=True)
parser.add_argument("--scaling_factor", '-s',
help="Scaling factor for PNG images (0-1)", default=0.50, type=float)
parser.add_argument(
"--dpi", '-d', help="DPI for PDF resolution", default=100, type=int)
parser.add_argument("--book_name", '-n', help="Book name", default="book")
args = parser.parse_args()
compressed_and_merge(args.folder_path, args.book_name,
args.scaling_factor, args.dpi)
if __name__ == "__main__":
main()
|