如何用python读取文件夹下的图片并生成pdf文件?这或许是一个比较常见的需求,市面上很多图片转pdf的软件,各有千秋。怎么用python实现这一功能?废话不多说,直接上代码。
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
from PIL import Image
import os
def get_image_paths_from_folder(folder_path):
# 定义支持的图片文件扩展名
image_extensions = {".png", ".jpg", ".jpeg", ".bmp", ".gif", ".tiff"}
# 初始化一个空列表来存储图片路径
image_paths = []
# 遍历文件夹中的所有文件
for filename in os.listdir(folder_path):
# 获取文件的完整路径
file_path = os.path.join(folder_path, filename)
# 检查文件是否是图片文件(通过扩展名判断)
if os.path.isfile(file_path) and os.path.splitext(file_path)[1].lower() in image_extensions:
image_paths.append(file_path)
return image_paths
def images_to_pdf(image_paths, output_pdf):
# 创建一个新的PDF文件
c = canvas.Canvas(output_pdf, pagesize=A4)
width, height = A4 # A4纸的宽度和高度
for image_path in image_paths:
img = Image.open(image_path)
img_width, img_height = img.size
# 根据图片尺寸调整在PDF中的位置
if img_width > img_height:
# 如果是横图,旋转90度
img = img.rotate(90, expand=True)
img_width, img_height = img.size
# 计算图片在PDF中的缩放比例
ratio = min(width / img_width, height / img_height)
img_width *= ratio
img_height *= ratio
# 计算图片在PDF中的位置
x = (width - img_width) / 2
y = (height - img_height) / 2
# 将图片插入到PDF中
c.drawImage(image_path, x, y, width=img_width, height=img_height)
c.showPage() # 新的一页
c.save() # 保存PDF文件
# 示例使用
image_paths = get_image_paths_from_folder("images") # 图片文件路径列表
output_pdf = "output.pdf" # 输出的PDF文件名
images_to_pdf(image_paths, output_pdf)