Please enable Javascript to view the contents

【Python实用脚本】打包PNG图片为PDF文件

 ·  ☕ 2 分钟

前段时间给大家介绍了各大平台的电子书下载方法,今天给大家分享一个Python脚本,可以将PNG图片打包成PDF文件。

读书App电子书下载的方法

实现步骤

  1. 将PNG文件压缩转换为PDF文件
  2. 将PDF文件合并为一个PDF文件
  3. 删除临时PDF文件

主要使用到的库

使用方法

将脚本放到PNG图片所在的文件夹下,执行脚本即可。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
usage: main2.py [-h] -f FOLDER_PATH [--scaling_factor SCALING_FACTOR] [--dpi DPI] [--book_name BOOK_NAME]

Compress and merge PNG images into a PDF file

optional arguments:
  -h, --help            show this help message and exit
  -f FOLDER_PATH, --folder_path FOLDER_PATH
                        Path to the folder containing PNG images
  --scaling_factor SCALING_FACTOR, -s SCALING_FACTOR
                        Scaling factor for PNG images (0-1)
  --dpi DPI, -d DPI     DPI for PDF resolution
  --book_name BOOK_NAME, -n BOOK_NAME
                        Book name

如:

1
2
3
4
5
6
python .\pngs-to-pdf.py -f C:\Users\mzhren\Documents\MuMu共享文件夹\资本论的读法 -n 资本论的读法 -s 0.5 -d 120 
Step 1:PNG-->PDF: [------------------->] 100%
Step 2: 正在合并PDF文件
合并完成: C:\Users\mzhren\Documents\MuMu共享文件夹\资本论的读法\资本论的读法.pdf
Step 3: 删除临时的PDF: [------------------->] 100%
删除完成

png-to-pdf

完整代码

png files merge into a pdf file

 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()
分享

码中人
作者
码中人
Web Developer