查看原文
其他

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

码中人 码农真经 2023-12-25

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

读书App电子书下载的方法

实现步骤

  1. 1. 将PNG文件压缩转换为PDF文件

  2. 2. 将PDF文件合并为一个PDF文件

  3. 3. 删除临时PDF文件

主要使用到的库

  • • Pillow[1]

  • • PyPDF2[2]

使用方法

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

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

如:

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[3]

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.50type=float)
    parser.add_argument(
        "--dpi"'-d'help="DPI for PDF resolution", default=100type=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()

往期推荐

欢迎关注我的公众号“码农真经”,原创技术文章第一时间推送。

引用链接

[1] Pillow: https://pillow.readthedocs.io/en/stable/
[2] PyPDF2: https://pypdf2.readthedocs.io/en/3.0.0/
[3] png files merge into a pdf file: https://gist.github.com/mzhren/e80b48e144bc9e5594f7339a605e4313


继续滑动看下一个

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存