吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 3513|回复: 43
收起左侧

[Python 原创] 目录内图片转PDF(多图片打印助手)

  [复制链接]
wkdxz 发表于 2023-9-25 14:37
本帖最后由 wkdxz 于 2023-10-14 09:30 编辑

最近同事经常找我帮她打印试卷,很奇葩的是,她的试卷都是*红书上下载的图片,一张张打印不好看,而且可能打印不完全,大小也不协调,所以有了这个脚本。

打包好的EXE:
https://wkdxz.lanzout.com/b03qxp94b  密码:1wy5


当需要给小孩打印图片格式的试卷时比较实用



使用方法:



方法一:直接将脚本放到图片文件夹内,并运行脚本

方法二:命令行运行

命令行参数: python convert_images_to_pdf.py [<图片文件夹路径>] [<PDF保存路径>]


> 图片文件夹路径:可选,默认为:python脚本所在目录


> PDF保存路径:可选,默认路径为 <图片文件夹路径> ,文件名为:<图片文件夹名>.PDF。需先指定<图片文件夹路径>再指定<PDF保存路径>





命令行示例:


假设脚本名为:convert_images_to_pdf.py


只指定图片目录
> python convert_images_to_pdf.py C:\img_folder


同时指定图片目录和pdf路径
> python convert_images_to_pdf.py C:\img_folder  D:\result.pdf



[Python] 纯文本查看 复制代码
# -*- coding: utf-8 -*-

import os
import subprocess
import sys

from PIL import Image
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas


def pause_exit():
    subprocess.run("pause", shell=True)
    exit()


def get_images(img_folder):
    """遍历目录,获取目录下所有的图片"""
    img_format = (".jpg", ".png", ".bmp")
    images = []
    for file_name in os.listdir(img_folder):
        if file_name.lower().endswith(img_format):
            images.append(os.path.join(img_folder, file_name))
    return sorted(images)


def get_image_size(img_file, page_width, page_height):
    """设置每个图片的大小"""
    with Image.open(img_file) as img:
        img_width, img_height = img.size
        if img_height > page_height * 0.95 or img_width > page_width * 0.95:
            height_scale = (page_height * 0.95) / img_height
            width_scale = (page_width * 0.95) / img_width
            scale = min(height_scale, width_scale)
            img_width *= scale
            img_height *= scale
    return img_width, img_height


def create_pdf(pdf_file, images, page_width, page_height):
    """创建 pdf 文件,并添加图片"""
    c = canvas.Canvas(pdf_file, pagesize=letter)

    total_images = len(images)
    for i, img_path in enumerate(images):
        img_width, img_height = get_image_size(img_path, page_width, page_height)
        x = (page_width - img_width) / 2
        y = (page_height - img_height) / 2
        c.drawImage(img_path, x, y, img_width, img_height)
        c.showPage()

        progress_bar(i + 1, total_images)

    c.save()


def create_pdf_from_path(img_folder, pdf_file=None):
    """遍历给定路径,将路径下的图片添加进pdf,并将pdf保存在指定路径下"""
    images = get_images(img_folder)
    if images:
        if not pdf_file:
            pdf_name = os.path.basename(img_folder) + ".pdf"
            pdf_file = os.path.join(img_folder, pdf_name)
        page_width, page_height = letter
        create_pdf(pdf_file, images, page_width, page_height)
        return pdf_file
    else:
        print(f"{img_folder} 下没有图片,当前支持的图片格式为 jpg、png 和 bmp")
        pause_exit()


def progress_bar(current, total, bar_length=60):
    """进度条"""
    filled_length = int(bar_length * current // total)
    bar = "+" * filled_length + "-" * (bar_length - filled_length)
    percent = current / total * 100
    sys.stdout.write(f"\r处理进度:|{bar}| {percent:.2f}%")
    sys.stdout.flush()


if __name__ == "__main__":
    subprocess.run("title 目录内图片转PDF", shell=True)

    try:
        (*rest,) = sys.argv[1:]
        if not rest:
            img_folder = os.getcwd()  # 使用当前文件夹作为 img_folder
            pdf_file = None
        else:
            img_folder, *pdf_file = rest
            pdf_file = pdf_file[0] if pdf_file else None
    except ValueError:
        print("请提供图片文件夹路径作为参数")
        pause_exit()

    if not os.path.exists(img_folder):
        print(f"{img_folder} 路径不存在!")
        pause_exit()
    elif not os.path.isdir(img_folder):
        print(f"{img_folder} 不是一个文件夹!")
        pause_exit()
    else:
        pdf_file = create_pdf_from_path(img_folder, pdf_file)

        if pdf_file:
            subprocess.run(["explorer", pdf_file])
        else:
            pause_exit()

免费评分

参与人数 7吾爱币 +13 热心值 +7 收起 理由
jk33 + 1 + 1 谢谢@Thanks!
pinglantingluoy + 1 + 1 谢谢@Thanks!
dizzy0001 + 1 + 1 我很赞同!
vitrel + 1 + 1 谢谢@Thanks!
苏紫方璇 + 7 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
zpzwz + 1 + 1 谢谢@Thanks!
dhwl9899 + 1 + 1 谢谢@Thanks!

查看全部评分

本帖被以下淘专辑推荐:

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

pinglantingluoy 发表于 2024-1-16 11:24
非常不错,我选的是“【有界面】目录内图转PDF”,感觉真的很好用,用其他的转出来的图片要么有颠倒,要么大小不一致。楼主的这个软件很强大。感谢(用了之后都说好)
 楼主| wkdxz 发表于 2023-12-7 07:28
vitrel 发表于 2023-11-2 11:18
wkdxz 发表于 2023-11-2 09:08
下载目录新增文件——【无界面_静默】目录内图片转PDF.exe

楼主,刚刚已经下载测试,
这次真是完美了!感谢感谢!!!
yaoshun3 发表于 2023-9-25 14:48
牛....动手能力强
dhwl9899 发表于 2023-9-25 15:21
谢谢,但愿有效实用。
dork 发表于 2023-9-25 15:50
感谢分 享
Zhui 发表于 2023-9-25 16:52
很有用,感谢
wasm2023 发表于 2023-9-25 17:07
太实用了,收藏了
focus009 发表于 2023-9-25 17:17
请问 为什么不用 Adobe Acrobat 9 Pro呢
 楼主| wkdxz 发表于 2023-9-25 17:23
focus009 发表于 2023-9-25 17:17
请问 为什么不用 Adobe Acrobat 9 Pro呢

因为没装
jidesheng6 发表于 2023-9-25 17:50
可以的,膜拜楼主,我们这种小白只能说一声佩服
qqcy44 发表于 2023-9-25 18:42
C:\Users\cy>E:\照片\壁纸\目录内图片转PDF.py E:\照片\壁纸
Traceback (most recent call last):
  File "E:\照片\壁纸\目录内图片转PDF.py", line 5, in <module>
    from PIL import Image
ModuleNotFoundError: No module named 'PIL'

你好 问下 这是什么情况
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-4-29 10:37

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表