池州市住房和城鄉(xiāng)建設(shè)委員會(huì)網(wǎng)站百度推廣聯(lián)系人
最近同事經(jīng)常找我?guī)退蛴≡嚲?#xff0c;很奇葩的是,她的試卷都是*紅書上下載的圖片,一張張打印不好看,而且可能打印不完全,大小也不協(xié)調(diào),所以有了這個(gè)腳本。
【需要給小孩打印圖片格式的試卷時(shí)也比較實(shí)用】
---------------------------------------------------------------------------------------------------------------------------------
使用方法:
方法一:直接將腳本放到圖片文件夾內(nèi),并運(yùn)行腳本
方法二:命令行運(yùn)行
命令行參數(shù):?python convert_images_to_pdf.py [<圖片文件夾路徑>] [<PDF保存路徑>]
>?圖片文件夾路徑:可選,默認(rèn)為:python腳本所在目錄
>?PDF保存路徑:可選,默認(rèn)路徑為 <圖片文件夾路徑> ,文件名為:<圖片文件夾名>.PDF。需先指定<圖片文件夾路徑>后,再指定<PDF保存路徑>
---------------------------------------------------------------------------------------------------------------------------------
命令行示例:
假設(shè)腳本名為:convert_images_to_pdf.py
只指定圖片目錄
> python convert_images_to_pdf.py C:\img_folder
同時(shí)指定圖片目錄和pdf路徑
>?python convert_images_to_pdf.py C:\img_folder??D:\result.pdf
代碼:
# -*- coding: utf-8 -*-import os
import subprocess
import sysfrom PIL import Image
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvasdef 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):"""設(shè)置每個(gè)圖片的大小"""with Image.open(img_file) as img:img_width, img_height = img.sizeif img_height > page_height * 0.95 or img_width > page_width * 0.95:height_scale = (page_height * 0.95) / img_heightwidth_scale = (page_width * 0.95) / img_widthscale = min(height_scale, width_scale)img_width *= scaleimg_height *= scalereturn img_width, img_heightdef create_pdf(pdf_file, images, page_width, page_height):"""創(chuàng)建 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) / 2y = (page_height - img_height) / 2c.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):"""遍歷給定路徑,將路徑下的圖片添加進(jìn)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 = lettercreate_pdf(pdf_file, images, page_width, page_height)return pdf_fileelse:print(f"{img_folder} 下沒有圖片,當(dāng)前支持的圖片格式為 jpg、png 和 bmp")pause_exit()def progress_bar(current, total, bar_length=60):"""進(jìn)度條"""filled_length = int(bar_length * current // total)bar = "+" * filled_length + "-" * (bar_length - filled_length)percent = current / total * 100sys.stdout.write(f"\r處理進(jìn)度:|{bar}| {percent:.2f}%")sys.stdout.flush()if __name__ == "__main__":subprocess.run("title 目錄內(nèi)圖片轉(zhuǎn)PDF", shell=True)try:(*rest,) = sys.argv[1:]if not rest:img_folder = os.getcwd() # 使用當(dāng)前文件夾作為 img_folderpdf_file = Noneelse:img_folder, *pdf_file = restpdf_file = pdf_file[0] if pdf_file else Noneexcept ValueError:print("請(qǐng)?zhí)峁﹫D片文件夾路徑作為參數(shù)")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} 不是一個(gè)文件夾!")pause_exit()else:pdf_file = create_pdf_from_path(img_folder, pdf_file)if pdf_file:subprocess.run(["explorer", pdf_file])else:pause_exit()