目录内图片转PDF(多图片打印助手)

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

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


使用方法:

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

方法二:命令行运行

命令行参数: python convert_images_to_pdf.py \<图片文件夹路径\> \

> 图片文件夹路径:可选,默认为: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()
相关推荐
happylifetree9 分钟前
Python70:核心语法-函数进阶-案例2
python
王中阳Go37 分钟前
两个入口答案不一致先别调模型:6 行入口口径对账表(附脚本)
人工智能·后端·python·大语言模型·1024程序员节
BK贝壳1 小时前
bool-hybrid-array 落盘我只认 .bha:用 Create_BHA / Ask_BHA 做布尔数组序列化
数据结构·python·numpy·1024程序员节
Sakura_j_h_1 小时前
Python 在定时任务里输出 emoji,UnicodeEncodeError 从哪来
开发语言·字符编码·windows·python·定时任务
supabc1233 小时前
欧盟电子发票(XRechnung/Peppol/ZUGFeRD)踩坑记:用 Python 不装 Java 跑官方校验规则
xml·python·开源·电子发票·1024程序员节
ZhengEnCi3 小时前
AI Agent工具调用防护层怎么写-一份能直接跑的Python四层拦截实现
python·llm·agent
ZhengEnCi3 小时前
AI Agent工具误调用怎么解决-从参数校验到高危二次确认的四层工程防线
python·llm·agent
镜子AI5 小时前
镜子AI工程教程:用Python实现关键词布局检查器与语义改写查重(附完整代码)
人工智能·python·microsoft
小oo呆5 小时前
【学习心得】Python协程
python
信誓旦旦的程序猿6 小时前
【Python量化实战宝典 #22】涨跌停、连板情绪手册:情绪指标构建(Python 可跑)
python·1024程序员节·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口